'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, cn } from '@/lib/utils'
import { DollarSign, Plus, Search, CheckCircle2 } from 'lucide-react'
import { StatCard, Card, CardHeader, CardTitle, Badge, Button, Modal, Input, Select, Textarea, FormGrid, PageHeader, Pagination, Amount } from '@/components/ui/components'

export default function ExpensesPage() {
  const qc = useQueryClient()
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [page, setPage]     = useState(1)
  const [newModal, setNewModal] = useState(false)
  const [form, setForm] = useState({ description:'', amount:'', categoryId:'', glAccountCode:'', paymentMethod:'CASH', paymentReference:'', supplierId:'', invoiceNo:'', expenseDate: new Date().toISOString().slice(0,10), notes:'' })
  const pageSize = 20

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

  const { data: cats } = useQuery({ queryKey:['expense-cats'], queryFn:()=>axios.get('/api/expenses/categories').then(r=>r.data.data) })

  const createMutation = useMutation({
    mutationFn: (payload: any) => axios.post('/api/expenses', payload),
    onSuccess: () => { toast.success('Expense submitted'); qc.invalidateQueries({queryKey:['expenses']}); setNewModal(false) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const approveMutation = useMutation({
    mutationFn: ({ id, action }: any) => axios.patch(`/api/expenses/${id}`, { action }),
    onSuccess: () => { toast.success('Action recorded'); qc.invalidateQueries({queryKey:['expenses']}) },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed'),
  })

  const expenses = data?.data ?? []
  const total    = data?.total ?? 0
  const summary  = data?.summary ?? {}

  const STATUS_OPTIONS = ['','DRAFT','SUBMITTED','PENDING_L1','PENDING_L2','APPROVED','DECLINED','PAID','CANCELLED']

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader title="Expenses" description={`${total.toLocaleString()} expense claims`} icon={<DollarSign className="w-6 h-6"/>}
        actions={<Button size="sm" icon={<Plus className="w-4 h-4"/>} onClick={() => setNewModal(true)}>New Expense</Button>}
      />

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <StatCard label="Pending Approval" value={(summary.pendingCount ?? 0).toLocaleString()}   icon={<DollarSign className="w-5 h-5"/>} color="amber"/>
        <StatCard label="Approved (MTD)"   value={formatCurrency(summary.approvedAmountMtd)}       icon={<DollarSign className="w-5 h-5"/>} color="green"/>
        <StatCard label="Paid (MTD)"       value={formatCurrency(summary.paidAmountMtd)}           icon={<DollarSign className="w-5 h-5"/>} color="teal"/>
        <StatCard label="Total (YTD)"      value={formatCurrency(summary.totalYtd)}               icon={<DollarSign className="w-5 h-5"/>} color="blue"/>
      </div>

      <div className="bg-card border rounded-xl p-4 flex gap-3 flex-wrap">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"/>
          <input value={search} onChange={e=>{setSearch(e.target.value);setPage(1)}} placeholder="Search description, reference…" className="w-full pl-9 pr-4 py-2 text-sm border rounded-lg focus:outline-none bg-background"/>
        </div>
        <select value={status} onChange={e=>{setStatus(e.target.value);setPage(1)}} className="px-3 py-2 text-sm border rounded-lg bg-background">
          {STATUS_OPTIONS.map(s => <option key={s} value={s}>{s || 'All Statuses'}</option>)}
        </select>
      </div>

      <Card>
        <div className="overflow-x-auto">
          <table className="table-lms w-full">
            <thead><tr><th>Ref</th><th>Description</th><th>Category</th><th>Amount</th><th>Supplier</th><th>Expense Date</th><th>Status</th><th>Actions</th></tr></thead>
            <tbody>
              {isLoading ? Array.from({length:8}).map((_,i)=><tr key={i}>{Array.from({length:8}).map((_,j)=><td key={j}><div className="h-4 bg-muted rounded animate-pulse"/></td>)}</tr>)
              : expenses.length === 0 ? <tr><td colSpan={8} className="text-center py-8 text-muted-foreground">No expenses found</td></tr>
              : expenses.map((e: any) => (
                <tr key={e.id}>
                  <td className="font-mono text-xs">{e.expenseRef}</td>
                  <td className="text-sm max-w-[180px] truncate">{e.description}</td>
                  <td className="text-sm text-muted-foreground">{e.category?.name}</td>
                  <td className="font-semibold"><Amount value={e.amount}/></td>
                  <td className="text-sm text-muted-foreground">{e.supplier?.name ?? '—'}</td>
                  <td className="text-xs">{fmtDate(e.expenseDate)}</td>
                  <td><Badge variant={e.status==='APPROVED'||e.status==='PAID'?'success':e.status==='DECLINED'||e.status==='CANCELLED'?'danger':e.status==='DRAFT'?'default':'warning'}>{e.status}</Badge></td>
                  <td>
                    <div className="flex items-center gap-1">
                      {['PENDING_L1','PENDING_L2'].includes(e.status) && (
                        <>
                          <Button size="xs" variant="success" onClick={() => approveMutation.mutate({id:e.id,action:'APPROVE'})}>Approve</Button>
                          <Button size="xs" variant="destructive" onClick={() => approveMutation.mutate({id:e.id,action:'DECLINE'})}>Decline</Button>
                        </>
                      )}
                      {e.status === 'DRAFT' && <Button size="xs" variant="outline" onClick={() => approveMutation.mutate({id:e.id,action:'SUBMIT'})}>Submit</Button>}
                      {e.status === 'APPROVED' && <Button size="xs" variant="outline" onClick={() => approveMutation.mutate({id:e.id,action:'PAY'})}>Mark Paid</Button>}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pagination page={page} pages={Math.ceil(total/pageSize)} total={total} pageSize={pageSize} onPage={setPage}/>
      </Card>

      {/* New expense modal */}
      <Modal open={newModal} onClose={() => setNewModal(false)} title="Submit New Expense" size="lg"
        footer={<><Button variant="outline" size="sm" onClick={() => setNewModal(false)}>Cancel</Button><Button size="sm" loading={createMutation.isPending} onClick={() => createMutation.mutate({...form, amount: parseFloat(form.amount)})}>Submit Expense</Button></>}
      >
        <div className="space-y-4">
          <Textarea label="Description" required rows={2} value={form.description} onChange={e=>setForm(f=>({...f,description:e.target.value}))} placeholder="What is this expense for?"/>
          <FormGrid>
            <Input label="Amount (KES)" required type="number" min={1} value={form.amount} onChange={e=>setForm(f=>({...f,amount:e.target.value}))}/>
            <Input label="Expense Date" required type="date" value={form.expenseDate} onChange={e=>setForm(f=>({...f,expenseDate:e.target.value}))}/>
          </FormGrid>
          <FormGrid>
            <Select label="Category" required value={form.categoryId} onChange={e=>setForm(f=>({...f,categoryId:e.target.value}))}
              placeholder="Select category…"
              options={cats?.map((c: any) => ({value:c.id, label:c.name})) ?? []}
            />
            <Select label="Payment Method" value={form.paymentMethod} onChange={e=>setForm(f=>({...f,paymentMethod:e.target.value}))}
              options={[{value:'CASH',label:'Cash'},{value:'MPESA',label:'M-Pesa'},{value:'BANK_TRANSFER',label:'Bank Transfer'},{value:'CHEQUE',label:'Cheque'},{value:'CREDIT_CARD',label:'Credit Card'}]}
            />
          </FormGrid>
          <FormGrid>
            <Input label="Invoice / Receipt No." value={form.invoiceNo} onChange={e=>setForm(f=>({...f,invoiceNo:e.target.value}))} placeholder="INV-001"/>
            <Input label="Payment Reference" value={form.paymentReference} onChange={e=>setForm(f=>({...f,paymentReference:e.target.value}))} placeholder="M-Pesa ref, cheque no…"/>
          </FormGrid>
          <Textarea label="Additional Notes" rows={2} value={form.notes} onChange={e=>setForm(f=>({...f,notes:e.target.value}))}/>
        </div>
      </Modal>
    </div>
  )
}
