'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { toast } from 'sonner'
import { formatCurrency, fmtDate } from '@/lib/utils'
import { DollarSign, Plus, CheckCircle2, XCircle, ArrowRight } from 'lucide-react'
import {
  StatCard, Card, CardHeader, CardTitle, Badge, Button, Modal,
  Input, Select, Textarea, PageHeader, Pagination, Amount, Alert,
} from '@/components/ui/components'

const STATUS_VARIANT: Record<string, any> = {
  PENDING:  'warning',
  APPROVED: 'info',
  DISBURSED:'info',
  ACTIVE:   'success',
  CLEARED:  'success',   // schema enum (not PAID_OFF)
  DECLINED: 'danger',
}

export default function AdvancesPage() {
  const qc = useQueryClient()
  const [page, setPage]   = useState(1)
  const [modal, setModal] = useState(false)
  const [form, setForm]   = useState({ staffId: '', amount: '', reason: '', repaymentMonths: '3' })

  const { data, isLoading } = useQuery({
    queryKey: ['advances', page],
    queryFn:  () => axios.get(`/api/payroll/advances?page=${page}&pageSize=20`).then(r => r.data),
    placeholderData: (prev: unknown) => prev,
  })

  // Staff mini-list for dropdown
  const { data: staffData } = useQuery({
    queryKey: ['staff-mini'],
    queryFn:  () => axios.get('/api/payroll/staff?pageSize=200').then(r => r.data.data),
    staleTime: 120_000,
  })

  const createMutation = useMutation({
    mutationFn: (p: any) => axios.post('/api/payroll/advances', p),
    onSuccess: () => {
      toast.success('Advance request submitted')
      qc.invalidateQueries({ queryKey: ['advances'] })
      setModal(false)
      setForm({ staffId: '', amount: '', reason: '', repaymentMonths: '3' })
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to submit advance'),
  })

  const actionMutation = useMutation({
    mutationFn: (p: any) => axios.patch('/api/payroll/advances', p),
    onSuccess: (_, vars) => {
      const labels: Record<string, string> = {
        APPROVE: 'Advance approved', DECLINE: 'Advance declined', DISBURSE: 'Advance disbursed',
      }
      toast.success(labels[vars.action] ?? 'Updated')
      qc.invalidateQueries({ queryKey: ['advances'] })
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Action failed'),
  })

  const advances = data?.data    ?? []
  const total    = data?.total   ?? 0
  const summary  = data?.summary ?? {}
  const staff    = staffData     ?? []

  const monthly = form.amount && form.repaymentMonths
    ? Math.ceil(parseFloat(form.amount) / parseInt(form.repaymentMonths))
    : 0

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader
        title="Cash Advances"
        description="Staff salary advances and recovery tracking"
        icon={<DollarSign className="w-6 h-6"/>}
        actions={
          <Button size="sm" icon={<Plus className="w-4 h-4"/>} onClick={() => setModal(true)}>
            New Advance
          </Button>
        }
      />

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <StatCard label="Active Advances"   value={(summary.activeCount    ?? 0).toLocaleString()} icon={<DollarSign className="w-5 h-5"/>} color="amber"/>
        <StatCard label="Total Outstanding" value={formatCurrency(summary.totalOutstanding)}       icon={<DollarSign className="w-5 h-5"/>} color="red"/>
        <StatCard label="Recovered (MTD)"   value={formatCurrency(summary.recoveredMtd)}           icon={<CheckCircle2 className="w-5 h-5"/>} color="green"/>
      </div>

      <Card>
        <CardHeader><CardTitle>Cash Advances</CardTitle></CardHeader>
        <div className="overflow-x-auto">
          <table className="table-lms w-full">
            <thead>
              <tr>
                <th>Ref</th><th>Staff</th><th>Amount</th>
                {/* FIX: was a.remainingBalance — schema field is outstandingBalance */}
                <th>Outstanding</th><th>Monthly Deduction</th><th>Installments</th>
                {/* FIX: was a.reason — schema field is purpose */}
                <th>Purpose</th><th>Status</th><th>Date</th><th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {isLoading
                ? Array.from({length:6}).map((_,i) => (
                    <tr key={i}>{Array.from({length:10}).map((_,j) => <td key={j}><div className="h-4 bg-muted rounded animate-pulse"/></td>)}</tr>
                  ))
                : advances.length === 0
                  ? <tr><td colSpan={10} className="text-center py-8 text-muted-foreground">No cash advances found</td></tr>
                  : advances.map((a: any) => (
                    <tr key={a.id}>
                      <td className="font-mono text-xs">{a.advanceRef}</td>
                      <td>
                        <p className="font-medium text-sm">{a.staff?.fullName}</p>
                        {/* employeeNumber exists in Staff schema */}
                        <p className="text-xs text-muted-foreground">{a.staff?.staffNo}</p>
                      </td>
                      <td><Amount value={a.amount}/></td>
                      {/* FIX: outstandingBalance (not remainingBalance) */}
                      <td className="font-bold text-amber-600"><Amount value={a.outstandingBalance}/></td>
                      <td><Amount value={a.monthlyDeduction}/></td>
                      <td className="text-xs text-center">
                        {a.remainingInstallments ?? '—'} / {a.totalInstallments ?? '—'}
                      </td>
                      {/* FIX: purpose (not reason) */}
                      <td className="text-sm text-muted-foreground max-w-[180px] truncate">{a.purpose ?? '—'}</td>
                      <td>
                        {/* FIX: CLEARED not PAID_OFF */}
                        <Badge variant={STATUS_VARIANT[a.status] ?? 'default'}>{a.status}</Badge>
                      </td>
                      <td className="text-xs text-muted-foreground">{fmtDate(a.createdAt)}</td>
                      <td>
                        <div className="flex gap-1 flex-wrap">
                          {a.status === 'PENDING' && (
                            <>
                              <Button size="xs" icon={<CheckCircle2 className="w-3 h-3"/>}
                                loading={actionMutation.isPending}
                                onClick={() => actionMutation.mutate({ id: a.id, action: 'APPROVE' })}>
                                Approve
                              </Button>
                              <Button size="xs" variant="destructive" icon={<XCircle className="w-3 h-3"/>}
                                loading={actionMutation.isPending}
                                onClick={() => actionMutation.mutate({ id: a.id, action: 'DECLINE' })}>
                                Decline
                              </Button>
                            </>
                          )}
                          {a.status === 'APPROVED' && (
                            <Button size="xs" variant="success" icon={<ArrowRight className="w-3 h-3"/>}
                              loading={actionMutation.isPending}
                              onClick={() => actionMutation.mutate({ id: a.id, action: 'DISBURSE' })}>
                              Disburse
                            </Button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))
              }
            </tbody>
          </table>
        </div>
        <Pagination page={page} pages={Math.ceil(total/20)} total={total} pageSize={20} onPage={setPage}/>
      </Card>

      {/* ══ New Advance Modal ══ */}
      <Modal open={modal} onClose={() => setModal(false)} title="New Cash Advance"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setModal(false)}>Cancel</Button>
            <Button size="sm" loading={createMutation.isPending}
              onClick={() => createMutation.mutate({
                staffId:         form.staffId,
                amount:          parseFloat(form.amount || '0'),
                reason:          form.reason,
                repaymentMonths: parseInt(form.repaymentMonths || '3'),
              })}>
              Submit Request
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Select label="Staff Member" required value={form.staffId}
            onChange={e => setForm(f => ({ ...f, staffId: e.target.value }))}
            placeholder="Select staff member…"
            options={staff.map((s: any) => ({
              value: s.id,
              label: `${s.fullName} (${s.staffNo ?? s.employeeNumber ?? s.id.slice(0,6)})`,
            }))} />

          <Input label="Advance Amount (KES)" required type="number" min={1}
            value={form.amount}
            onChange={e => setForm(f => ({ ...f, amount: e.target.value }))}
            placeholder="Enter amount…" />

          <Select label="Repayment Duration" value={form.repaymentMonths}
            onChange={e => setForm(f => ({ ...f, repaymentMonths: e.target.value }))}
            options={[
              { value: '1',  label: '1 Month'   },
              { value: '2',  label: '2 Months'  },
              { value: '3',  label: '3 Months'  },
              { value: '6',  label: '6 Months'  },
              { value: '12', label: '12 Months' },
            ]} />

          {monthly > 0 && (
            <Alert variant="info">
              Monthly payroll deduction: <strong>{formatCurrency(monthly)}</strong>
            </Alert>
          )}

          <Textarea label="Reason / Purpose" required rows={3}
            value={form.reason}
            onChange={e => setForm(f => ({ ...f, reason: e.target.value }))}
            placeholder="Describe the reason for this advance…" />
        </div>
      </Modal>
    </div>
  )
}
