'use client'

import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { formatCurrency, cn } from '@/lib/utils'
import { BarChart2, Download, RefreshCw } from 'lucide-react'
import { Card, Button, PageHeader, Amount, Badge, Alert } from '@/components/ui/components'

export default function TrialBalancePage() {
  const [asAt, setAsAt] = useState(new Date().toISOString().slice(0, 10))

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['trial-balance', asAt],
    queryFn: () => axios.get(`/api/accounting?sub=trial-balance&asAt=${asAt}`).then(r => r.data.data),
  })

  const accounts = data?.accounts ?? []
  const totals   = data?.totals ?? { totalDebit: 0, totalCredit: 0 }
  const isBalanced = Math.abs(totals.totalDebit - totals.totalCredit) < 0.01

  const groupedByType: Record<string, any[]> = {}
  accounts.forEach((a: any) => {
    if (!groupedByType[a.accountType]) groupedByType[a.accountType] = []
    groupedByType[a.accountType].push(a)
  })

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader title="Trial Balance" description="Summarised GL balances at a point in time" icon={<BarChart2 className="w-6 h-6"/>}
        actions={
          <div className="flex items-center gap-2">
            <label className="text-sm text-muted-foreground">As at:</label>
            <input type="date" value={asAt} onChange={e => setAsAt(e.target.value)} className="border rounded-lg px-3 py-1.5 text-sm bg-background focus:outline-none focus:ring-2 focus:ring-primary/20"/>
            <Button variant="outline" size="sm" icon={<RefreshCw className="w-4 h-4"/>} onClick={() => refetch()}>Refresh</Button>
            <Button variant="outline" size="sm" icon={<Download className="w-4 h-4"/>}>Export</Button>
          </div>
        }
      />

      {!isBalanced && accounts.length > 0 && (
        <Alert variant="error" title="Trial Balance is OUT OF BALANCE">Difference: {formatCurrency(Math.abs(totals.totalDebit - totals.totalCredit))}. Please investigate journal posting errors.</Alert>
      )}

      {isBalanced && accounts.length > 0 && (
        <Alert variant="success">Trial balance is in balance — Total Debits = Total Credits = {formatCurrency(totals.totalDebit)}</Alert>
      )}

      <Card>
        <div className="overflow-x-auto">
          <table className="table-lms w-full">
            <thead>
              <tr>
                <th className="text-left">Code</th>
                <th className="text-left">Account Name</th>
                <th className="text-left">Type</th>
                <th className="text-right">Debit (KES)</th>
                <th className="text-right">Credit (KES)</th>
              </tr>
            </thead>
            <tbody>
              {isLoading
                ? Array.from({length:20}).map((_,i)=><tr key={i}>{Array.from({length:5}).map((_,j)=><td key={j}><div className="h-4 bg-muted rounded animate-pulse"/></td>)}</tr>)
                : Object.entries(groupedByType).map(([type, accs]) => (
                  <>
                    <tr key={`hdr-${type}`} className="bg-muted/40">
                      <td colSpan={5} className="font-semibold text-xs uppercase tracking-wider text-muted-foreground py-2">{type}</td>
                    </tr>
                    {accs.map((a: any) => {
                      const isDebitNormal = ['ASSET','EXPENSE'].includes(a.accountType)
                      const bal = parseFloat(a.balance ?? 0)
                      return (
                        <tr key={a.id}>
                          <td className="font-mono text-xs text-muted-foreground">{a.code}</td>
                          <td className="text-sm">{a.name}</td>
                          <td><Badge variant="default">{a.accountType}</Badge></td>
                          <td className="text-right text-sm font-medium">{(isDebitNormal && bal > 0) || (!isDebitNormal && bal < 0) ? formatCurrency(Math.abs(bal)) : '—'}</td>
                          <td className="text-right text-sm font-medium">{(!isDebitNormal && bal > 0) || (isDebitNormal && bal < 0) ? formatCurrency(Math.abs(bal)) : '—'}</td>
                        </tr>
                      )
                    })}
                  </>
                ))
              }
            </tbody>
            <tfoot>
              <tr className="border-t-2 border-foreground bg-muted/60 font-bold">
                <td colSpan={3} className="py-3 text-right text-sm">TOTALS</td>
                <td className="text-right text-sm py-3">{formatCurrency(totals.totalDebit)}</td>
                <td className={cn('text-right text-sm py-3', !isBalanced && accounts.length > 0 && 'text-destructive')}>{formatCurrency(totals.totalCredit)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </Card>
    </div>
  )
}
