'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { toast } from 'sonner'
import { formatCurrency } from '@/lib/utils'
import { FileText, Plus, Edit2, Trash2, Save } from 'lucide-react'
import {
  Card, CardHeader, CardTitle, Badge, Button, Modal,
  Input, Select, Textarea, PageHeader, Alert, FormGrid,
} from '@/components/ui/components'

const CALC_TYPES = [
  { value: 'PERCENTAGE', label: 'Percentage (e.g. 6% of gross)' },
  { value: 'FLAT',       label: 'Flat Amount (e.g. 50 KES)' },
  { value: 'TIERED',     label: 'Tiered Brackets (e.g. NHIF table)' },
]

export default function StatutoryRatesPage() {
  const qc = useQueryClient()
  const [editModal, setEditModal] = useState(false)
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [form, setForm] = useState<any>({
    name: '', code: '', description: '', calculationType: 'PERCENTAGE',
    percentage: '', capAmount: '', floorAmount: '', flatAmount: '',
    employerPercentage: '', employerCap: '', employerFlat: '',
    reliefAmount: '', glCode: '', order: '0',
    brackets: [] as any[],
  })

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

  const { data: accounts } = useQuery({
    queryKey: ['coa'],
    queryFn: () => axios.get('/api/accounting?sub=coa').then(r => r.data.data),
  })

  const accountOptions = (accounts ?? [])
    .filter((a: any) => a.isLeaf)
    .map((a: any) => ({ value: a.code, label: `${a.code} — ${a.name}` }))

  const saveMutation = useMutation({
    mutationFn: (p: any) => axios.post('/api/payroll/statutory', p),
    onSuccess: () => {
      toast.success('Rate saved')
      qc.invalidateQueries({ queryKey: ['statutory-rates'] })
      setEditModal(false)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => axios.post('/api/payroll/statutory', { action: 'delete', id }),
    onSuccess: () => {
      toast.success('Rate deleted')
      qc.invalidateQueries({ queryKey: ['statutory-rates'] })
      setDeleteId(null)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  function openEdit(rate?: any) {
    if (rate) {
      setForm({
        name: rate.name ?? '',
        code: rate.code ?? '',
        description: rate.description ?? '',
        calculationType: rate.calculationType ?? 'PERCENTAGE',
        percentage: rate.percentage ?? '',
        capAmount: rate.capAmount ?? '',
        floorAmount: rate.floorAmount ?? '',
        flatAmount: rate.flatAmount ?? '',
        employerPercentage: rate.employerPercentage ?? '',
        employerCap: rate.employerCap ?? '',
        employerFlat: rate.employerFlat ?? '',
        reliefAmount: rate.reliefAmount ?? '',
        glCode: rate.glCode ?? '',
        order: String(rate.order ?? 0),
        brackets: (rate.brackets ?? []).map((b: any) => ({
          fromAmount: String(b.fromAmount),
          toAmount: b.toAmount ? String(b.toAmount) : '',
          amount: String(b.amount),
          percentage: b.percentage ? String(b.percentage) : '',
        })),
      })
    } else {
      setForm({
        name: '', code: '', description: '', calculationType: 'PERCENTAGE',
        percentage: '', capAmount: '', floorAmount: '', flatAmount: '',
        employerPercentage: '', employerCap: '', employerFlat: '',
        reliefAmount: '', glCode: '', order: '0',
        brackets: [],
      })
    }
    setEditModal(true)
  }

  function prepPayload() {
    const p: any = {
      name: form.name,
      code: form.code,
      calculationType: form.calculationType,
      order: parseInt(form.order) || 0,
    }
    if (form.description) p.description = form.description
    if (form.glCode) p.glCode = form.glCode
    if (form.percentage) p.percentage = parseFloat(form.percentage)
    if (form.capAmount) p.capAmount = parseFloat(form.capAmount)
    if (form.floorAmount) p.floorAmount = parseFloat(form.floorAmount)
    if (form.flatAmount) p.flatAmount = parseFloat(form.flatAmount)
    if (form.employerPercentage) p.employerPercentage = parseFloat(form.employerPercentage)
    if (form.employerCap) p.employerCap = parseFloat(form.employerCap)
    if (form.employerFlat) p.employerFlat = parseFloat(form.employerFlat)
    if (form.reliefAmount) p.reliefAmount = parseFloat(form.reliefAmount)
    if (form.calculationType === 'TIERED') {
      p.brackets = form.brackets
        .filter((b: any) => b.fromAmount && b.amount)
        .map((b: any) => ({
          fromAmount: parseFloat(b.fromAmount),
          toAmount: b.toAmount ? parseFloat(b.toAmount) : null,
          amount: parseFloat(b.amount),
          percentage: b.percentage ? parseFloat(b.percentage) : undefined,
        }))
    }
    return p
  }

  function addBracket() {
    setForm((f: any) => ({
      ...f,
      brackets: [...f.brackets, { fromAmount: '', toAmount: '', amount: '', percentage: '' }],
    }))
  }

  function updBracket(i: number, field: string, value: string) {
    setForm((f: any) => {
      const b = [...f.brackets]
      b[i] = { ...b[i], [field]: value }
      return { ...f, brackets: b }
    })
  }

  function rmBracket(i: number) {
    setForm((f: any) => ({ ...f, brackets: f.brackets.filter((_: any, idx: number) => idx !== i) }))
  }

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader title="Statutory Rates" description="Configure payroll statutory deductions (PAYE, NSSF, NHIF, NITA, Housing Levy)"
        icon={<FileText className="w-6 h-6"/>}
        actions={<Button size="sm" icon={<Plus className="w-4 h-4"/>} onClick={() => openEdit()}>Add Rate</Button>}
      />

      <Alert variant="info">
        These rates replace hardcoded values. New rates are automatically picked up by payroll run generation.
        For TIERED types (e.g. NHIF), add brackets. For PERCENTAGE types (e.g. NSSF), set a percentage and optional cap.
      </Alert>

      <Card>
        <CardHeader><CardTitle>Configured Statutory Deductions</CardTitle></CardHeader>
        <div className="overflow-x-auto">
          <table className="table-lms w-full">
            <thead>
              <tr><th>Code</th><th>Name</th><th>Type</th><th>Rate / Amount</th><th>Employer</th><th>Relief</th><th>Order</th><th>Status</th><th>Actions</th></tr>
            </thead>
            <tbody>
              {isLoading ? Array.from({length:5}).map((_,i)=><tr key={i}>{Array.from({length:9}).map((_,j)=><td key={j}><div className="h-4 bg-muted rounded animate-pulse"/></td>)}</tr>)
              : !rates?.length ? <tr><td colSpan={9} className="text-center py-8 text-muted-foreground">No statutory rates configured. Add one to get started.</td></tr>
              : rates.map((r: any) => (
                <tr key={r.id} className={!r.isActive ? 'opacity-50' : ''}>
                  <td className="font-mono text-xs font-bold">{r.code}</td>
                  <td className="text-sm font-medium">{r.name}</td>
                  <td><Badge variant="info">{r.calculationType}</Badge></td>
                  <td className="text-sm">
                    {r.calculationType === 'PERCENTAGE' && `${r.percentage}%${r.capAmount ? ` (cap ${formatCurrency(r.capAmount)})` : ''}`}
                    {r.calculationType === 'FLAT' && formatCurrency(r.flatAmount)}
                    {r.calculationType === 'TIERED' && `${r.brackets?.length ?? 0} brackets`}
                  </td>
                  <td className="text-xs text-muted-foreground">
                    {r.employerPercentage ? `${r.employerPercentage}%${r.employerCap ? `/${formatCurrency(r.employerCap)}` : ''}` : r.employerFlat ? formatCurrency(r.employerFlat) : '—'}
                  </td>
                  <td className="text-xs">{r.reliefAmount ? formatCurrency(r.reliefAmount) : '—'}</td>
                  <td className="text-xs text-center">{r.order}</td>
                  <td><Badge variant={r.isActive ? 'success' : 'default'}>{r.isActive ? 'Active' : 'Inactive'}</Badge></td>
                  <td>
                    <div className="flex gap-1">
                      <Button size="xs" variant="ghost" icon={<Edit2 className="w-3 h-3"/>} onClick={() => openEdit(r)} />
                      <Button size="xs" variant="ghost" icon={<Trash2 className="w-3 h-3 text-red-500"/>} onClick={() => setDeleteId(r.id)} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {/* Edit Modal */}
      <Modal open={editModal} onClose={() => setEditModal(false)} size="2xl"
        title={form.code ? `Edit — ${form.name}` : 'New Statutory Rate'}
        footer={<><Button variant="outline" size="sm" onClick={() => setEditModal(false)}>Cancel</Button><Button size="sm" loading={saveMutation.isPending} onClick={() => saveMutation.mutate(prepPayload())}><Save className="w-3.5 h-3.5 mr-1"/>Save</Button></>}>
        <div className="space-y-5 max-h-[70vh] overflow-y-auto pr-1">
          <FormGrid cols={2}>
            <Input label="Name" required value={form.name} onChange={e => setForm(f=>({...f,name:e.target.value}))} placeholder="e.g. NSSF Employee" />
            <Input label="Code" required value={form.code} onChange={e => setForm(f=>({...f,code:e.target.value}))} placeholder="e.g. NSSF" />
          </FormGrid>
          <Textarea label="Description" rows={2} value={form.description} onChange={e => setForm(f=>({...f,description:e.target.value}))} />
          <FormGrid cols={2}>
            <Select label="Calculation Type" required value={form.calculationType}
              onChange={e => setForm(f=>({...f,calculationType:e.target.value}))}
              options={CALC_TYPES} />
            <Input label="Sort Order" type="number" value={form.order} onChange={e => setForm(f=>({...f,order:e.target.value}))} />
          </FormGrid>

          {form.calculationType === 'PERCENTAGE' && (
            <>
              <FormGrid cols={3}>
                <Input label="Percentage (%)" type="number" step="0.01" value={form.percentage} onChange={e => setForm(f=>({...f,percentage:e.target.value}))} />
                <Input label="Cap Amount (KES)" type="number" value={form.capAmount} onChange={e => setForm(f=>({...f,capAmount:e.target.value}))} hint="Optional: max deduction" />
                <Input label="Floor Amount (KES)" type="number" value={form.floorAmount} onChange={e => setForm(f=>({...f,floorAmount:e.target.value}))} hint="Optional: min deduction" />
              </FormGrid>
              <FormGrid cols={2}>
                <Input label="Employer Percentage (%)" type="number" step="0.01" value={form.employerPercentage} onChange={e => setForm(f=>({...f,employerPercentage:e.target.value}))} />
                <Input label="Employer Cap (KES)" type="number" value={form.employerCap} onChange={e => setForm(f=>({...f,employerCap:e.target.value}))} />
              </FormGrid>
            </>
          )}

          {form.calculationType === 'FLAT' && (
            <FormGrid cols={3}>
              <Input label="Flat Amount (KES)" required type="number" value={form.flatAmount} onChange={e => setForm(f=>({...f,flatAmount:e.target.value}))} />
              <Input label="Employer Amount (KES)" type="number" value={form.employerFlat} onChange={e => setForm(f=>({...f,employerFlat:e.target.value}))} />
            </FormGrid>
          )}

          {(form.calculationType === 'PERCENTAGE' || form.calculationType === 'FLAT') && (
            <FormGrid cols={2}>
              <Input label="Tax Relief (KES)" type="number" value={form.reliefAmount} onChange={e => setForm(f=>({...f,reliefAmount:e.target.value}))} hint="e.g. PAYE personal relief 2400" />
              <Select label="GL Account" value={form.glCode} onChange={e => setForm(f=>({...f,glCode:e.target.value}))}
                placeholder="Select GL account..." options={accountOptions} />
            </FormGrid>
          )}

          {form.calculationType === 'TIERED' && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <p className="text-sm font-medium">Brackets (income range → deduction)</p>
                <Button size="xs" variant="outline" onClick={addBracket}>+ Add Bracket</Button>
              </div>
              {form.brackets.length === 0 && <p className="text-xs text-muted-foreground">No brackets defined. Click "Add Bracket" to add one.</p>}
              {form.brackets.map((b: any, i: number) => (
                <div key={i} className="flex items-end gap-2 p-3 bg-muted/30 rounded-lg">
                  <Input label="From (KES)" type="number" value={b.fromAmount} onChange={e => updBracket(i, 'fromAmount', e.target.value)} />
                  <Input label="To (KES)" type="number" value={b.toAmount} onChange={e => updBracket(i, 'toAmount', e.target.value)} hint="Leave empty = unlimited" />
                  <Input label="Deduction (KES)" type="number" value={b.amount} onChange={e => updBracket(i, 'amount', e.target.value)} />
                  <Input label="Or %" type="number" step="0.01" value={b.percentage} onChange={e => updBracket(i, 'percentage', e.target.value)} />
                  <Button size="xs" variant="ghost" className="text-red-500 mb-1" onClick={() => rmBracket(i)}>×</Button>
                </div>
              ))}
            </div>
          )}
        </div>
      </Modal>

      {/* Delete confirmation */}
      <Modal open={!!deleteId} onClose={() => setDeleteId(null)} title="Delete Statutory Rate"
        footer={<><Button variant="outline" size="sm" onClick={() => setDeleteId(null)}>Cancel</Button><Button variant="destructive" size="sm" loading={deleteMutation.isPending} onClick={() => deleteMutation.mutate(deleteId!)}>Delete</Button></>}>
        <Alert variant="error">Are you sure? This will remove the rate permanently. Existing payroll runs are not affected.</Alert>
      </Modal>
    </div>
  )
}
