'use client'
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { toast } from 'sonner'
import { formatCurrency, cn } from '@/lib/utils'
import { Database, ChevronRight, ChevronDown, Plus, RefreshCw } from 'lucide-react'
import { Card, Badge, Button, PageHeader, Amount, Modal, Input, Select, FormGrid } from '@/components/ui/components'

function AccountNode({ account, depth = 0 }: { account: any; depth?: number }) {
  const [open, setOpen] = useState(depth < 2)
  const hasChildren = account.children?.length > 0
  const balance = parseFloat(account.balance ?? 0)
  return (
    <div>
      <div className={cn('flex items-center gap-2 py-2 px-3 hover:bg-accent/50 rounded cursor-pointer transition-colors', depth === 0 && 'bg-muted/40 font-semibold')} style={{ paddingLeft: `${(depth * 20) + 12}px` }} onClick={() => hasChildren && setOpen(!open)}>
        <div className="w-4 shrink-0">{hasChildren && (open ? <ChevronDown className="w-3.5 h-3.5 text-muted-foreground"/> : <ChevronRight className="w-3.5 h-3.5 text-muted-foreground"/>)}</div>
        <span className="font-mono text-xs w-16 text-muted-foreground shrink-0">{account.code}</span>
        <span className={cn('flex-1 text-sm', depth === 0 && 'font-semibold')}>{account.name}</span>
        <Badge variant="default" className="text-xs shrink-0">{account.accountType}</Badge>
        <span className={cn('text-sm font-medium w-36 text-right shrink-0', balance < 0 ? 'text-red-600' : 'text-foreground')}>{formatCurrency(Math.abs(balance))}{balance < 0 && ' Cr'}</span>
        <Badge variant={account.isActive ? 'success' : 'default'} className="shrink-0">{account.isActive ? 'Active' : 'Inactive'}</Badge>
      </div>
      {open && hasChildren && <div>{account.children.map((c: any) => <AccountNode key={c.id} account={c} depth={depth+1}/>)}</div>}
    </div>
  )
}

export default function CoaPage() {
  const qc = useQueryClient()
  const [modal, setModal] = useState(false)
  const [form, setForm]   = useState({ code:'', name:'', accountType:'ASSET', parentId:'', isLeaf:true, normalBalance:'DEBIT', description:'' })

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

  const createMutation = useMutation({
    mutationFn: (payload: any) => axios.post('/api/accounting', { action: 'create-account', ...payload }),
    onSuccess: () => {
      toast.success('Account created')
      qc.invalidateQueries({ queryKey: ['coa'] })
      setModal(false)
      setForm({ code:'', name:'', accountType:'ASSET', parentId:'', isLeaf:true, normalBalance:'DEBIT', description:'' })
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to create account'),
  })

  const recalcMutation = useMutation({
    mutationFn: () => axios.post('/api/accounting', { action: 'recalculate-balances' }),
    onSuccess: (r: any) => {
      toast.success(r.data?.message ?? 'Balances recalculated successfully')
      qc.invalidateQueries({ queryKey: ['coa'] })
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Recalculation failed'),
  })

  const allAccounts = accounts ?? []
  const flatList    = allAccounts.flatMap((a: any) => [a, ...(a.children ?? [])])
  const totalDebit  = allAccounts.filter((a: any) => ['ASSET','EXPENSE'].includes(a.accountType)).reduce((s: number, a: any) => s + parseFloat(a.balance ?? 0), 0)
  const totalCredit = allAccounts.filter((a: any) => ['LIABILITY','EQUITY','INCOME'].includes(a.accountType)).reduce((s: number, a: any) => s + parseFloat(a.balance ?? 0), 0)

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader title="Chart of Accounts" description={`${allAccounts.length} account groups`} icon={<Database className="w-6 h-6"/>}
        actions={
          <div className="flex gap-2">
            <Button size="sm" variant="outline" icon={<RefreshCw className="w-4 h-4"/>}
              loading={recalcMutation.isPending}
              onClick={() => recalcMutation.mutate()}>
              Recalculate Balances
            </Button>
            <Button size="sm" icon={<Plus className="w-4 h-4"/>} onClick={() => setModal(true)}>Add Account</Button>
          </div>
        }
      />
      <div className="grid grid-cols-2 gap-4 max-w-sm">
        <div className="p-4 border rounded-lg"><p className="text-xs text-muted-foreground">Total Debits</p><Amount value={totalDebit} className="font-bold text-primary"/></div>
        <div className="p-4 border rounded-lg"><p className="text-xs text-muted-foreground">Total Credits</p><Amount value={totalCredit} className="font-bold"/></div>
      </div>
      <Card>
        <div className="p-3 border-b grid grid-cols-4 gap-2 text-xs font-semibold text-muted-foreground">
          <span className="col-span-2">Account Name</span><span>Type</span><span className="text-right">Balance</span>
        </div>
        <div className="p-2">
          {isLoading ? <div className="p-8 text-center text-muted-foreground">Loading accounts…</div>
          : allAccounts.map((a: any) => <AccountNode key={a.id} account={a} depth={0}/>)}
        </div>
      </Card>

      <Modal open={modal} onClose={() => setModal(false)} title="Add Account"
        footer={<><Button variant="outline" size="sm" onClick={() => setModal(false)}>Cancel</Button>
          <Button size="sm" loading={createMutation.isPending} onClick={() => createMutation.mutate(form)}>Create Account</Button></>}
      >
        <div className="space-y-4">
          <FormGrid>
            <Input label="Account Code" required value={form.code} onChange={e=>setForm(f=>({...f,code:e.target.value}))} placeholder="1101"/>
            <Select label="Account Type" required value={form.accountType} onChange={e=>setForm(f=>({...f,accountType:e.target.value}))}
              options={[{value:'ASSET',label:'Asset'},{value:'LIABILITY',label:'Liability'},{value:'EQUITY',label:'Equity'},{value:'INCOME',label:'Income'},{value:'EXPENSE',label:'Expense'}]}/>
          </FormGrid>
          <Input label="Account Name" required value={form.name} onChange={e=>setForm(f=>({...f,name:e.target.value}))} placeholder="Petty Cash"/>
          <FormGrid>
            <Select label="Parent Account" value={form.parentId} onChange={e=>setForm(f=>({...f,parentId:e.target.value}))}
              options={[{value:'',label:'No parent (top level)'}, ...flatList.filter((a: any)=>!a.isLeaf||!a.parentId).map((a: any)=>({value:a.id,label:`${a.code} — ${a.name}`}))]}/>
            <Select label="Normal Balance" value={form.normalBalance} onChange={e=>setForm(f=>({...f,normalBalance:e.target.value}))}
              options={[{value:'DEBIT',label:'Debit'},{value:'CREDIT',label:'Credit'}]}/>
          </FormGrid>
          <Input label="Description" value={form.description} onChange={e=>setForm(f=>({...f,description:e.target.value}))} placeholder="Optional description"/>
        </div>
      </Modal>
    </div>
  )
}
