'use client'

import Link from 'next/link'
import { useParams } from 'next/navigation'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { ArrowLeft, Download } from 'lucide-react'
import { toast } from 'sonner'
import { api, type PayrollRun } from '@/lib/api'
import { Button } from '@/components/ui/Button'
import { Card } from '@/components/ui/Card'
import { Badge } from '@/components/ui/Badge'
import { PermissionGate } from '@/components/auth/PermissionGate'

export function PayrollDetailPage() {
  const { t } = useTranslation()
  const params = useParams()
  const id = params?.id as string
  const queryClient = useQueryClient()

  const { data, refetch, isLoading } = useQuery({
    queryKey: ['payroll-run', id],
    queryFn: () => api.get<{ data: PayrollRun }>(`/payroll/runs/${id}`),
    enabled: Boolean(id),
  })

  const calculate = useMutation({
    mutationFn: () => api.post(`/payroll/runs/${id}/calculate`),
    onSuccess: () => {
      toast.success(t('payroll.messages.calculated'))
      refetch()
      queryClient.invalidateQueries({ queryKey: ['payroll-runs'] })
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const handleExport = async () => {
    try {
      const res = await api.get(`/payroll/runs/${id}/export`, { responseType: 'blob' })
      const url = window.URL.createObjectURL(new Blob([res.data as BlobPart]))
      const a = document.createElement('a')
      a.href = url
      a.download = `payroll_${id}.csv`
      a.click()
      window.URL.revokeObjectURL(url)
      refetch()
    } catch {
      toast.error(t('common.somethingWentWrong'))
    }
  }

  const run = data?.data?.data

  if (isLoading || !run) {
    return <div className="p-6 text-sm text-[var(--text-muted)]">{t('common.loading')}</div>
  }

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap items-center gap-3">
          <Link href="/payroll">
            <button
              type="button"
              className="premium-chip press-btn flex items-center gap-1.5 rounded-xl px-3 py-2 text-sm"
            >
              <ArrowLeft size={15} />
              {t('common.back')}
            </button>
          </Link>
          <h1 className="premium-heading text-2xl font-bold">{run.period_ym}</h1>
          <Badge variant="muted">{t(`payroll.status.${run.status}`, run.status)}</Badge>
        </div>
        <div className="flex gap-2">
          <PermissionGate permission="payroll.manage">
            {(run.status === 'draft' || run.status === 'calculated') && (
              <Button size="sm" onClick={() => calculate.mutate()} disabled={calculate.isPending}>
                {t('payroll.calculate')}
              </Button>
            )}
          </PermissionGate>
          <PermissionGate permission="payroll.view">
            <Button size="sm" variant="secondary" onClick={handleExport}>
              <Download size={14} />
              {t('common.exportCsv')}
            </Button>
          </PermissionGate>
        </div>
      </div>

      <Card elevated className="grid gap-3 sm:grid-cols-3 text-sm">
        <div>
          <div className="text-xs text-[var(--text-muted)]">{t('payroll.gross')}</div>
          <div className="font-semibold">{Number(run.total_gross).toFixed(2)}</div>
        </div>
        <div>
          <div className="text-xs text-[var(--text-muted)]">{t('payroll.deductions')}</div>
          <div className="font-semibold">{Number(run.total_deductions).toFixed(2)}</div>
        </div>
        <div>
          <div className="text-xs text-[var(--text-muted)]">{t('payroll.net')}</div>
          <div className="font-semibold">{Number(run.total_net).toFixed(2)}</div>
        </div>
      </Card>

      <Card elevated>
        <div className="overflow-x-auto">
          <table className="min-w-full text-sm">
            <thead>
              <tr className="border-b text-left text-[var(--text-muted)]">
                <th className="py-2 pr-3">{t('payroll.employee')}</th>
                <th className="py-2 pr-3">{t('payroll.days')}</th>
                <th className="py-2 pr-3">{t('payroll.hours')}</th>
                <th className="py-2 pr-3">{t('payroll.gross')}</th>
                <th className="py-2 pr-3">{t('payroll.tax')}</th>
                <th className="py-2">{t('payroll.net')}</th>
              </tr>
            </thead>
            <tbody>
              {(run.lines ?? []).map((l) => (
                <tr key={l.id} className="border-b border-[var(--premium-border)]/60">
                  <td className="py-2 pr-3">{l.employee?.full_name || l.employee_id}</td>
                  <td className="py-2 pr-3">{l.days_worked}</td>
                  <td className="py-2 pr-3">{l.hours_worked}</td>
                  <td className="py-2 pr-3">{Number(l.gross).toFixed(2)}</td>
                  <td className="py-2 pr-3">{Number(l.tax).toFixed(2)}</td>
                  <td className="py-2 font-medium">{Number(l.net).toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  )
}
