'use client'

import { useState } from 'react'
import Link from 'next/link'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Plus } from 'lucide-react'
import { toast } from 'sonner'
import { api, type PaginatedResponse, type DailyActivityLog, type Project } from '@/lib/api'
import { DataTable } from '@/components/DataTable'
import { Button } from '@/components/ui/Button'
import { Select } from '@/components/ui/Select'
import { Card } from '@/components/ui/Card'

export function DailyOpsPage() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [category, setCategory] = useState('')
  const [projectId, setProjectId] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['daily-ops', page, category, projectId],
    queryFn: () =>
      api.get<PaginatedResponse<DailyActivityLog>>('/daily-activity-logs', {
        params: {
          page,
          per_page: 25,
          category: category || undefined,
          project_id: projectId || undefined,
        },
      }),
  })

  const { data: projectsData } = useQuery({
    queryKey: ['projects-options'],
    queryFn: () => api.get<PaginatedResponse<Project>>('/projects', { params: { per_page: 200 } }),
  })

  const { data: summaryData } = useQuery({
    queryKey: ['daily-ops-summary', projectId],
    queryFn: () =>
      api.get<{
        data: {
          by_category: Record<string, { total: number; count: number }>
          cost_total: number
          revenue_total: number
        }
      }>(`/daily-activity-logs/project/${projectId}/summary`),
    enabled: Boolean(projectId),
  })

  const remove = useMutation({
    mutationFn: (id: number) => api.delete(`/daily-activity-logs/${id}`),
    onSuccess: () => {
      toast.success(t('dailyOps.messages.deleted'))
      queryClient.invalidateQueries({ queryKey: ['daily-ops'] })
      queryClient.invalidateQueries({ queryKey: ['daily-ops-summary'] })
    },
    onError: () => toast.error(t('common.somethingWentWrong')),
  })

  const rows = data?.data.data ?? []
  const meta = data?.data.meta
  const projects = projectsData?.data.data ?? []
  const categories = ['materials', 'labor', 'machinery', 'expenses', 'revenue'] as const
  const summary = summaryData?.data?.data

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex flex-wrap items-center justify-between gap-3">
        <h1 className="premium-heading text-2xl font-bold">{t('dailyOps.title')}</h1>
        <Link href="/daily-ops/new">
          <Button size="sm">
            <Plus size={14} />
            {t('dailyOps.create')}
          </Button>
        </Link>
      </div>

      {summary && (
        <Card elevated className="animate-fade-in-up stagger-1">
          <h3 className="mb-2 text-sm font-semibold">{t('dailyOps.summary')}</h3>
          <div className="grid gap-2 sm:grid-cols-3 text-sm">
            {categories.map((c) => (
              <div key={c}>
                <div className="text-xs text-[var(--text-muted)]">
                  {t(`dailyOps.categories.${c}`)}
                </div>
                <div className="font-medium">
                  {Number(summary.by_category?.[c]?.total ?? 0).toLocaleString()}
                </div>
              </div>
            ))}
            <div>
              <div className="text-xs text-[var(--text-muted)]">{t('dailyOps.costTotal')}</div>
              <div className="font-medium">{Number(summary.cost_total).toLocaleString()}</div>
            </div>
          </div>
        </Card>
      )}

      <div className="animate-fade-in-up stagger-2">
        <DataTable
          data={rows}
          loading={isLoading}
          emptyMessage={t('common.noResults')}
          toolbar={
            <div className="flex flex-wrap gap-2">
              <Select
                value={projectId}
                onChange={(e) => {
                  setProjectId(e.target.value)
                  setPage(1)
                }}
                options={[
                  { value: '', label: t('dailyOps.allProjects') },
                  ...projects.map((p) => ({ value: String(p.id), label: p.name })),
                ]}
              />
              <Select
                value={category}
                onChange={(e) => {
                  setCategory(e.target.value)
                  setPage(1)
                }}
                options={[
                  { value: '', label: t('dailyOps.allCategories') },
                  ...categories.map((value) => ({
                    value,
                    label: t(`dailyOps.categories.${value}`),
                  })),
                ]}
              />
            </div>
          }
          pagination={meta}
          onPageChange={setPage}
          columns={[
            {
              key: 'activity_date',
              header: t('dailyOps.date'),
              render: (r) => r.activity_date?.slice(0, 10),
            },
            {
              key: 'category',
              header: t('dailyOps.category'),
              render: (r) => t(`dailyOps.categories.${r.category}`, r.category),
            },
            {
              key: 'project',
              header: t('dailyOps.project'),
              render: (r) => r.project?.name || '—',
            },
            {
              key: 'site',
              header: t('dailyOps.site'),
              render: (r) => r.site?.name || '—',
            },
            { key: 'description', header: t('dailyOps.description') },
            {
              key: 'total_cost',
              header: t('dailyOps.totalCost'),
              render: (r) => Number(r.total_cost).toLocaleString(),
            },
            {
              key: 'actions',
              header: '',
              render: (r) => (
                <div className="flex gap-2">
                  <Link
                    href={`/daily-ops/${r.id}/edit`}
                    className="text-sm text-brand-600 hover:underline"
                  >
                    {t('common.edit')}
                  </Link>
                  <button
                    type="button"
                    className="text-sm text-red-600 hover:underline"
                    onClick={() => remove.mutate(r.id)}
                  >
                    {t('common.delete')}
                  </button>
                </div>
              ),
            },
          ]}
        />
      </div>
    </div>
  )
}
