'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useParams, useRouter } from 'next/navigation'
import axios from 'axios'
import { toast } from 'sonner'
import { formatCurrency, fmtDate, cn } from '@/lib/utils'
import { Briefcase, ArrowLeft, Download, FileText, Play, Loader2, Printer, X } from 'lucide-react'
import { Card, CardHeader, CardTitle, Badge, Button, Modal, Amount } from '@/components/ui/components'

const MONTHS = ['','January','February','March','April','May','June','July','August','September','October','November','December']

function fmt(n: number): string {
  return n.toLocaleString('en-KE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function PayslipPreview({ item, orgName, run }: { item: any; orgName: string; run: any }) {
  const s = item.staff
  return (
    <div className="bg-white rounded-xl overflow-hidden" id="payslip-preview">
      {/* Header */}
      <div className="bg-[#1e3a5f] px-6 py-4 flex items-center justify-between print:bg-[#1e3a5f] print:text-white">
        <span className="text-white font-semibold text-lg">{orgName}</span>
        <span className="text-white font-bold text-xl tracking-wide">PAY SLIP</span>
      </div>

      {/* Period & Ref */}
      <div className="px-6 pt-4 pb-2 flex justify-between text-xs text-gray-500 border-b">
        <span>Period: {run.period}</span>
        <span>Ref: {run.payrollRef}</span>
        <span>Payment: {fmtDate(run.paymentDate)}</span>
      </div>

      {/* Employee Details */}
      <div className="px-6 pt-4 pb-2">
        <div className="bg-[#f5f7fa] px-3 py-1.5 rounded mb-3">
          <span className="text-[#1e3a5f] font-semibold text-xs uppercase tracking-wide">Employee Details</span>
        </div>
        <div className="grid grid-cols-2 gap-y-2 gap-x-8 text-sm">
          <div className="flex"><span className="text-gray-500 w-24 shrink-0">Staff No</span><span>{s.staffNo}</span></div>
          <div className="flex"><span className="text-gray-500 w-24 shrink-0">KRA PIN</span><span>{s.kraPin || '—'}</span></div>
          <div className="flex"><span className="text-gray-500 w-24 shrink-0">Full Name</span><span className="font-medium">{s.fullName}</span></div>
          <div className="flex"><span className="text-gray-500 w-24 shrink-0">NSSF No</span><span>{s.nssfNo || '—'}</span></div>
          <div className="flex"><span className="text-gray-500 w-24 shrink-0">Designation</span><span>{s.designation || '—'}</span></div>
          <div className="flex"><span className="text-gray-500 w-24 shrink-0">NHIF No</span><span>{s.nhifNo || '—'}</span></div>
          <div className="flex"><span className="text-gray-500 w-24 shrink-0">Department</span><span>{s.department || '—'}</span></div>
          <div className="flex"><span className="text-gray-500 w-24 shrink-0">Bank / A/c</span><span>{s.bankName || '—'}{s.accountNumber ? ' / ' + s.accountNumber : ''}</span></div>
        </div>
      </div>

      <div className="border-t mx-6"/>

      {/* Earnings & Deductions */}
      <div className="px-6 pt-4 pb-2 grid grid-cols-2 gap-6">
        {/* Earnings */}
        <div>
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-[#1e3a5f] text-white">
                <th className="text-left px-3 py-1.5 rounded-tl font-medium">Earnings</th>
                <th className="text-right px-3 py-1.5 rounded-tr font-medium">Amount (KES)</th>
              </tr>
            </thead>
            <tbody>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">Basic Salary</td><td className="px-3 py-1.5 text-right">{fmt(item.basicSalary)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">House Allowance</td><td className="px-3 py-1.5 text-right">{fmt(item.houseAllowance)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">Transport Allowance</td><td className="px-3 py-1.5 text-right">{fmt(item.transportAllowance)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">Medical Allowance</td><td className="px-3 py-1.5 text-right">{fmt(item.medicalAllowance)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">Other Allowances</td><td className="px-3 py-1.5 text-right">{fmt(item.otherAllowances)}</td></tr>
            </tbody>
            <tfoot>
              <tr className="bg-[#f5f7fa] font-semibold text-[#1e3a5f]">
                <td className="px-3 py-1.5">GROSS PAY</td>
                <td className="px-3 py-1.5 text-right">{fmt(item.grossPay)}</td>
              </tr>
            </tfoot>
          </table>
        </div>

        {/* Deductions */}
        <div>
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-[#1e3a5f] text-white">
                <th className="text-left px-3 py-1.5 rounded-tl font-medium">Deductions</th>
                <th className="text-right px-3 py-1.5 rounded-tr font-medium">Amount (KES)</th>
              </tr>
            </thead>
            <tbody>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">PAYE (Tax)</td><td className="px-3 py-1.5 text-right">{fmt(item.paye)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">NSSF Employee</td><td className="px-3 py-1.5 text-right">{fmt(item.nssfEmployee)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">NHIF</td><td className="px-3 py-1.5 text-right">{fmt(item.nhif)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">NITA</td><td className="px-3 py-1.5 text-right">{fmt(item.nita)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">Housing Levy</td><td className="px-3 py-1.5 text-right">{fmt(item.housingLevy)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">Advance Deduction</td><td className="px-3 py-1.5 text-right">{fmt(item.advanceDeduction)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">Loan Deduction</td><td className="px-3 py-1.5 text-right">{fmt(item.loanDeduction)}</td></tr>
              <tr className="border-b border-gray-200"><td className="px-3 py-1.5">Other Deductions</td><td className="px-3 py-1.5 text-right">{fmt(item.otherDeductions)}</td></tr>
            </tbody>
            <tfoot>
              <tr className="bg-[#f5f7fa] font-semibold text-[#1e3a5f]">
                <td className="px-3 py-1.5">TOTAL DEDUCTIONS</td>
                <td className="px-3 py-1.5 text-right">{fmt(item.totalDeductions)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>

      {/* Net Pay */}
      <div className="px-6 pb-2">
        <div className="border-2 border-[#1e3a5f] rounded-lg bg-[#f8f9fb] px-4 py-3 text-center">
          <span className="text-[#1e3a5f] text-lg font-bold">NET PAY: KES {fmt(item.netPay)}</span>
        </div>
      </div>

      {/* Footer */}
      <div className="px-6 pb-4 text-xs text-gray-400 border-t pt-3 mt-2 flex justify-between">
        <span>Generated: {new Date().toISOString().split('T')[0]}</span>
        {run.paymentDate && <span>Payment Date: {fmtDate(run.paymentDate)}</span>}
        <span>This is a computer-generated payslip.</span>
      </div>
    </div>
  )
}

export default function PayrollRunViewPage() {
  const params = useParams()
  const router = useRouter()
  const qc = useQueryClient()
  const runId = params.id as string
  const [previewItem, setPreviewItem] = useState<any>(null)

  const { data, isLoading } = useQuery({
    queryKey: ['payroll-run', runId],
    queryFn: () => axios.get(`/api/payroll/${runId}/run`).then(r => r.data.data),
  })

  const actionRun = useMutation({
    mutationFn: ({ action }: any) => axios.patch(`/api/payroll/${runId}`, { action }),
    onSuccess: () => { toast.success('Payroll updated'); qc.invalidateQueries({queryKey:['payroll-run', runId]}) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const downloadPayslip = (staffId?: string) => {
    const url = `/api/payroll/${runId}/payslip${staffId ? `?staffId=${staffId}` : ''}`
    window.open(url, '_blank')
  }

  if (isLoading) return (
    <div className="p-6 max-w-screen-xl mx-auto">
      <div className="flex items-center justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-primary"/></div>
    </div>
  )
  if (!data) return (
    <div className="p-6 max-w-screen-xl mx-auto">
      <p className="text-center py-20 text-muted-foreground">Payroll run not found</p>
    </div>
  )

  const r = data

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-center gap-3">
          <button onClick={() => router.back()} className="p-1.5 rounded-lg hover:bg-accent text-muted-foreground"><ArrowLeft className="w-5 h-5"/></button>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-xl font-semibold">{r.payrollRef}</h1>
              <Badge variant={r.status==='PAID'?'success':r.status==='APPROVED'?'info':r.status==='CANCELLED'?'danger':'warning'}>{r.status}</Badge>
            </div>
            <p className="text-sm text-muted-foreground">{r.period} · {r.employeeCount} staff · Payment: {fmtDate(r.paymentDate)}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {r.status === 'DRAFT' && <Button size="sm" onClick={() => actionRun.mutate({action:'SUBMIT'})}>Submit for Approval</Button>}
          {r.status === 'PENDING_APPROVAL' && <Button size="sm" onClick={() => actionRun.mutate({action:'APPROVE'})}>Approve</Button>}
          {r.status === 'APPROVED' && <Button size="sm" variant="success" icon={<Play className="w-4 h-4"/>} onClick={() => actionRun.mutate({action:'PAY'})}>Mark Paid</Button>}
          <Button size="sm" variant="outline" icon={<Download className="w-4 h-4"/>} onClick={() => downloadPayslip()} disabled={r.status !== 'PAID'}>Download All Payslips</Button>
        </div>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <Card className="p-4"><p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">Basic Salary</p><p className="text-xl font-bold">{formatCurrency(r.totalBasicSalary)}</p></Card>
        <Card className="p-4"><p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">Gross Pay</p><p className="text-xl font-bold">{formatCurrency(r.totalGross)}</p></Card>
        <Card className="p-4"><p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">Total Deductions</p><p className="text-xl font-bold">{formatCurrency(r.totalDeductions)}</p></Card>
        <Card className="p-4"><p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">Net Pay</p><p className="text-xl font-bold text-green-600">{formatCurrency(r.totalNet)}</p></Card>
      </div>

      <Card>
        <CardHeader><CardTitle>Staff Breakdown ({r.items.length})</CardTitle></CardHeader>
        <div className="overflow-x-auto">
          <table className="table-lms w-full text-sm">
            <thead>
              <tr>
                <th>Staff</th>
                <th>Basic</th>
                <th>House</th>
                <th>Transport</th>
                <th>Medical</th>
                <th>Gross</th>
                <th>PAYE</th>
                <th>NSSF</th>
                <th>NHIF</th>
                <th>Adv</th>
                <th>Ded</th>
                <th>Net</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {r.items.map((item: any) => (
                <tr key={item.id}>
                  <td>
                    <p className="font-medium">{item.staff.fullName}</p>
                    <p className="text-xs text-muted-foreground">{item.staff.staffNo}</p>
                  </td>
                  <td><Amount value={item.basicSalary} size="sm"/></td>
                  <td><Amount value={item.houseAllowance} size="sm"/></td>
                  <td><Amount value={item.transportAllowance} size="sm"/></td>
                  <td><Amount value={item.medicalAllowance} size="sm"/></td>
                  <td className="font-medium"><Amount value={item.grossPay} size="sm"/></td>
                  <td><Amount value={item.paye} size="sm"/></td>
                  <td><Amount value={item.nssfEmployee} size="sm"/></td>
                  <td><Amount value={item.nhif} size="sm"/></td>
                  <td><Amount value={item.advanceDeduction} size="sm"/></td>
                  <td><Amount value={item.totalDeductions} size="sm"/></td>
                  <td className="font-bold text-green-600"><Amount value={item.netPay} size="sm"/></td>
                  <td>
                    <div className="flex items-center gap-1">
                      <Button size="xs" variant="ghost" icon={<FileText className="w-3 h-3"/>} onClick={() => setPreviewItem(item)}>View</Button>
                      <Button size="xs" variant="ghost" icon={<Download className="w-3 h-3"/>} onClick={() => downloadPayslip(item.staffId)} disabled={r.status !== 'PAID'}/>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr className="font-bold bg-muted/30">
                <td>{r.items.length} staff</td>
                <td><Amount value={r.totalBasicSalary} size="sm"/></td>
                <td colSpan={3}></td>
                <td><Amount value={r.totalGross} size="sm"/></td>
                <td><Amount value={r.totalPaye} size="sm"/></td>
                <td><Amount value={r.totalNssfEmployee} size="sm"/></td>
                <td><Amount value={r.totalNhif} size="sm"/></td>
                <td><Amount value={r.totalAdvances} size="sm"/></td>
                <td><Amount value={r.totalDeductions} size="sm"/></td>
                <td className="text-green-600"><Amount value={r.totalNet} size="sm"/></td>
                <td></td>
              </tr>
            </tfoot>
          </table>
        </div>
      </Card>

      {/* Payslip Preview Modal */}
      <Modal open={!!previewItem} onClose={() => setPreviewItem(null)} title="Payslip Preview" size="xl"
        footer={<>
          <Button variant="outline" size="sm" icon={<Printer className="w-4 h-4"/>} onClick={() => window.print()}>Print</Button>
          <Button variant="outline" size="sm" onClick={() => setPreviewItem(null)}>Close</Button>
          <Button size="sm" icon={<Download className="w-4 h-4"/>} onClick={() => downloadPayslip(previewItem?.staffId)}>Download PDF</Button>
        </>}
      >
        {previewItem && <PayslipPreview item={previewItem} orgName={r.organisation?.name || 'Organisation'} run={r}/>}
      </Modal>
    </div>
  )
}
