'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 { BookOpen, Search, Download, RotateCcw } from 'lucide-react'
import { Card, CardHeader, CardTitle, Badge, Button, Tabs, PageHeader, Amount, Pagination, Skeleton, Modal, Input, Alert } from '@/components/ui/components'

export default function JournalsPage() {
  const qc = useQueryClient()
  const [search, setSearch]     = useState('')
  const [source, setSource]     = useState('')
  const [page, setPage]         = useState(1)
  const [selected, setSelected] = useState<any>(null)
  const [voidModal, setVoidModal] = useState(false)
  const [voidReason, setVoidReason] = useState('')
  const pageSize = 20

  const { data, isLoading } = useQuery({
    queryKey: ['journals', { search, source, page }],
    queryFn: () => {
      const p = new URLSearchParams({ page: String(page), pageSize: String(pageSize), sub: 'journals' })
      if (search) p.set('search', search)
      if (source) p.set('sourceType', source)
      return axios.get(`/api/accounting?${p}`).then(r => r.data)
    },
    placeholderData: (prev: unknown) => prev,
  })

  const voidMutation = useMutation({
    mutationFn: (reason: string) => axios.post(`/api/accounting/journals/${selected?.id}/void`, { reason }),
    onSuccess: (r: any) => {
      toast.success(r.data?.message ?? 'Journal entry voided')
      qc.invalidateQueries({ queryKey: ['journals'] })
      setVoidModal(false)
      setVoidReason('')
      setSelected(null)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to void journal'),
  })

  const journals = data?.data ?? []
  const total    = data?.total ?? 0
  const pages    = Math.ceil(total / pageSize)

  const SOURCE_TYPES = ['', 'LOAN_DISBURSEMENT', 'LOAN_REPAYMENT', 'INTEREST_ACCRUAL', 'PENALTY_ACCRUAL', 'IFRS9_PROVISION', 'SAVINGS_DEPOSIT', 'SAVINGS_WITHDRAWAL', 'SHARE_PURCHASE', 'EXPENSE', 'LOAN_WRITEOFF', 'PAYROLL']

  return (
    <div className="p-6 space-y-5 max-w-screen-2xl mx-auto">
      <PageHeader title="Journal Entries" description={`${total.toLocaleString()} total entries`} icon={<BookOpen className="w-6 h-6"/>}
        actions={<Button variant="outline" size="sm" icon={<Download className="w-4 h-4"/>}>Export</Button>}
      />

      <div className="bg-card border rounded-xl p-4 flex flex-wrap items-center gap-3">
        <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 entry ref, description..." className="w-full pl-9 pr-4 py-2 text-sm border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 bg-background"/>
        </div>
        <select value={source} onChange={e => { setSource(e.target.value); setPage(1) }} className="px-3 py-2 text-sm border rounded-lg bg-background">
          <option value="">All Source Types</option>
          {SOURCE_TYPES.filter(Boolean).map(s => <option key={s} value={s}>{s.replace(/_/g,' ')}</option>)}
        </select>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        {/* Journal list */}
        <div className="lg:col-span-2">
          <Card>
            <div className="overflow-x-auto">
              <table className="table-lms w-full">
                <thead><tr><th>Entry Ref</th><th>Description</th><th>Source Type</th><th>Total Debit</th><th>Status</th><th>Date</th></tr></thead>
                <tbody>
                  {isLoading ? Array.from({length:10}).map((_,i)=><tr key={i}>{Array.from({length:6}).map((_,j)=><td key={j}><Skeleton className="h-4"/></td>)}</tr>)
                  : journals.length === 0 ? <tr><td colSpan={6} className="text-center py-8 text-muted-foreground">No journal entries found</td></tr>
                  : journals.map((j: any) => (
                    <tr key={j.id} className={cn('cursor-pointer', selected?.id === j.id && 'bg-primary/5')} onClick={() => setSelected(j)}>
                      <td className="font-mono text-xs">{j.entryRef}</td>
                      <td className="text-sm max-w-[200px] truncate">{j.description}</td>
                      <td><Badge variant="default">{j.sourceType?.replace(/_/g,' ')}</Badge></td>
                      <td><Amount value={j.totalDebit} size="sm"/></td>
                      <td><Badge variant={j.status==='POSTED'?'success':j.status==='VOIDED'?'danger':'warning'}>{j.status}</Badge></td>
                      <td className="text-xs text-muted-foreground">{fmtDate(j.postingDate)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Pagination page={page} pages={pages} total={total} pageSize={pageSize} onPage={setPage}/>
          </Card>
        </div>

        {/* Journal detail */}
        <div>
          {selected ? (
            <Card>
              <CardHeader>
                <div>
                  <h3 className="font-semibold font-mono text-sm">{selected.entryRef}</h3>
                  <p className="text-xs text-muted-foreground">{fmtDate(selected.postingDate)}</p>
                </div>
                <Badge variant={selected.status==='POSTED'?'success':selected.status==='VOIDED'?'danger':'warning'}>{selected.status}</Badge>
              </CardHeader>
              <div className="p-5 space-y-4">
                <p className="text-sm">{selected.description}</p>
                <div className="text-xs text-muted-foreground space-y-1">
                  <p>Source: {selected.sourceType?.replace(/_/g,' ')}</p>
                  <p>Posted: {fmtDate(selected.postingDate)}</p>
                  {selected.isAutoPosted && <Badge variant="info">Auto Posted</Badge>}
                  {selected.voidedAt && <p className="text-red-600">Voided: {fmtDate(selected.voidedAt)}</p>}
                  {selected.voidReason && <p className="text-red-600">Reason: {selected.voidReason}</p>}
                </div>
                {selected.lines?.length > 0 && (
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">Journal Lines</p>
                    <div className="space-y-1">
                      {selected.lines.map((l: any, i: number) => (
                        <div key={i} className="flex items-center justify-between text-xs p-2 bg-muted/30 rounded">
                          <div>
                            <p className="font-medium">{l.account?.code} — {l.account?.name}</p>
                            <p className="text-muted-foreground">{l.description}</p>
                          </div>
                          <div className="text-right">
                            {parseFloat(l.debitAmount) > 0 && <p className="text-foreground font-medium">Dr {formatCurrency(l.debitAmount)}</p>}
                            {parseFloat(l.creditAmount) > 0 && <p className="text-muted-foreground">Cr {formatCurrency(l.creditAmount)}</p>}
                          </div>
                        </div>
                      ))}
                    </div>
                    <div className="flex justify-between mt-2 pt-2 border-t text-xs font-semibold">
                      <span>Total</span>
                      <div className="flex gap-4">
                        <span>Dr {formatCurrency(selected.totalDebit)}</span>
                        <span>Cr {formatCurrency(selected.totalCredit)}</span>
                      </div>
                    </div>
                  </div>
                )}
                {selected.status === 'POSTED' && (
                  <Button variant="outline" size="sm" className="w-full text-destructive border-destructive hover:bg-destructive hover:text-white"
                    icon={<RotateCcw className="w-4 h-4"/>} onClick={() => setVoidModal(true)}>
                    Void Entry
                  </Button>
                )}
              </div>
            </Card>
          ) : (
            <div className="h-64 border rounded-xl bg-muted/20 flex items-center justify-center text-muted-foreground text-sm">Select a journal entry to view details</div>
          )}
        </div>
      </div>

      {/* Void Confirmation Modal */}
      <Modal open={voidModal} onClose={() => setVoidModal(false)} title={`Void Journal Entry — ${selected?.entryRef}`} size="sm"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setVoidModal(false)}>Cancel</Button>
            <Button variant="destructive" size="sm" loading={voidMutation.isPending}
              disabled={!voidReason.trim()}
              onClick={() => voidMutation.mutate(voidReason)}>
              Void Entry
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Alert variant="warning">
            This will create a <strong>reversal journal entry</strong> (swapping all Dr and Cr amounts) and mark the original entry as voided.
            {selected?.sourceType && ['LOAN_REPAYMENT','SAVINGS_DEPOSIT','SAVINGS_WITHDRAWAL','LOAN_DISBURSEMENT'].includes(selected.sourceType) && (
              <p className="mt-1 text-xs">
                Associated {selected.sourceType === 'LOAN_REPAYMENT' ? 'repayment record(s)' :
                  selected.sourceType === 'LOAN_DISBURSEMENT' ? 'disbursement' :
                  'savings transaction(s)'} will also be reversed.
              </p>
            )}
          </Alert>
          <Input label="Reason for voiding *" required value={voidReason}
            onChange={e => setVoidReason(e.target.value)}
            placeholder="Explain why this entry is being voided…" />
        </div>
      </Modal>
    </div>
  )
}
