'use client'

import { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardHeader from '@mui/material/CardHeader'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import TextField from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
import Alert from '@mui/material/Alert'
import type { ClientFolder, Invoice, TrustAccount, TrustTransaction, TrustTxType } from './types'
type RetainerTransaction = { txId?: string; type: string; amount: number; currency: string; date: string; description: string; matterId?: string; invoiceRef?: string; createdBy: string }

// ─── Billing config summary strip ────────────────────────────────────────────

function BillingConfigSummary({ folder, lang }: { folder: ClientFolder; lang: string }) {
  const router = useRouter()
  const cfg = folder.billingConfig

  const BILLING_LABELS: Record<string, string> = {
    hourly: 'Hourly', fixed: 'Fixed Fee', retainer: 'Retainer Draw',
    contingency: 'Contingency', hybrid: 'Hybrid',
  }
  const FREQ_LABELS: Record<string, string> = {
    monthly: 'Monthly', bi_monthly: 'Bi-Monthly', quarterly: 'Quarterly',
    upon_completion: 'On Completion', as_incurred: 'As Incurred', milestone: 'Milestone',
  }

  if (!cfg) {
    return (
      <Button
        size='small' variant='outlined' color='warning'
        startIcon={<i className='ri-settings-3-line' />}
        onClick={() => router.push(`/${lang}/clients/${folder._id}/billing/settings`)}
      >
        Configure Billing Settings
      </Button>
    )
  }

  return (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
      {(cfg.billingTypes ?? (cfg.billingType ? [cfg.billingType] : ['hourly'])).map(t => (
        <Chip key={t} label={BILLING_LABELS[t] ?? t} size='small'
          sx={{ bgcolor: '#E8F7F7', color: '#0D9394', fontWeight: 600, height: 22 }} />
      ))}
      {((cfg.billingTypes ?? [cfg.billingType]).includes('hourly') || (cfg.billingTypes ?? [cfg.billingType]).includes('hybrid')) && (
        <Typography variant='caption' color='text.secondary'>
          {cfg.rateSchedule?.length
            ? `${cfg.rateSchedule.length} timekeeper rate${cfg.rateSchedule.length > 1 ? 's' : ''}`
            : `Default ${new Intl.NumberFormat('en-TH', { maximumFractionDigits: 0 }).format(cfg.defaultHourlyRate)} ${folder.currency}/hr`
          }
        </Typography>
      )}
      <Typography variant='caption' color='text.disabled'>·</Typography>
      <Typography variant='caption' color='text.secondary'>
        {FREQ_LABELS[cfg.billingFrequency] ?? cfg.billingFrequency}
      </Typography>
      <Typography variant='caption' color='text.disabled'>·</Typography>
      <Typography variant='caption' color='text.secondary'>
        {cfg.paymentTermsDays === 0 ? 'Due on receipt' : `Net ${cfg.paymentTermsDays}d`}
      </Typography>
      {!cfg.vatExempt && (
        <>
          <Typography variant='caption' color='text.disabled'>·</Typography>
          <Typography variant='caption' color='text.secondary'>{(cfg.vatRate * 100).toFixed(0)}% VAT</Typography>
        </>
      )}
      <Tooltip title='Edit Billing Settings'>
        <IconButton size='small' onClick={() => router.push(`/${lang}/clients/${folder._id}/billing/settings`)}>
          <i className='ri-settings-3-line' style={{ fontSize: '0.9rem', color: '#8A92A3' }} />
        </IconButton>
      </Tooltip>
    </Box>
  )
}

const INV_STATUS_CONFIG: Record<string, { label: string; color: string; bg: string }> = {
  draft: { label: 'Draft',  color: '#8A92A3', bg: '#F0F0F0' },
  sent:  { label: 'Sent',   color: '#03C3EC', bg: '#E5F9FF' },
  paid:  { label: 'Paid',   color: '#71DD37', bg: '#EEFBE5' },
  void:  { label: 'Void',   color: '#FF4C51', bg: '#FFECEC' },
}

function InvoicesSection({ folderId, currency }: { folderId: string; currency: string }) {
  const [invoices, setInvoices]   = useState<Invoice[]>([])
  const [loading, setLoading]     = useState(true)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const r = await fetch(`/api/invoices?clientFolderId=${folderId}&limit=100`)
      const data = await r.json()
      setInvoices(data.items ?? [])
    } finally { setLoading(false) }
  }, [folderId])

  useEffect(() => { load() }, [load])

  async function action(id: string, path: string, body?: object) {
    await fetch(`/api/invoices/${id}/${path}`, {
      method: 'POST',
      headers: body ? { 'Content-Type': 'application/json' } : {},
      body: body ? JSON.stringify(body) : undefined,
    })
    load()
  }

  const totalBilled = invoices.filter(i => i.status !== 'void').reduce((s, i) => s + i.total, 0)
  const totalPaid   = invoices.filter(i => i.status === 'paid').reduce((s, i) => s + (i.paidAmount ?? i.total), 0)
  const outstanding = invoices.filter(i => i.status === 'sent').reduce((s, i) => s + i.total, 0)

  // AR Aging — days overdue from dueDate
  const today = new Date()
  const aging = { current: 0, d30: 0, d60: 0, d90: 0, d90plus: 0 }
  for (const inv of invoices.filter(i => i.status === 'sent')) {
    const days = Math.floor((today.getTime() - new Date(inv.dueDate).getTime()) / 86400000)
    if (days <= 0)       aging.current += inv.total
    else if (days <= 30) aging.d30     += inv.total
    else if (days <= 60) aging.d60     += inv.total
    else if (days <= 90) aging.d90     += inv.total
    else                 aging.d90plus += inv.total
  }
  const agingBuckets = [
    { label: 'Current',  value: aging.current, color: '#0D9394' },
    { label: '1-30d',    value: aging.d30,     color: '#FFB400' },
    { label: '31-60d',   value: aging.d60,     color: '#FF9F43' },
    { label: '61-90d',   value: aging.d90,     color: '#FF6B6B' },
    { label: '90d+',     value: aging.d90plus, color: '#FF4C51' },
  ]

  return (
    <Card>
      <CardHeader
        title='Invoices'
        titleTypographyProps={{ variant: 'subtitle2' }}
        avatar={<i className='ri-file-text-line' style={{ color: '#0D9394', fontSize: '1rem' }} />}
        subheader={
          <Box sx={{ display: 'flex', gap: 3, mt: 0.5 }}>
            <Box>
              <Typography variant='caption' color='text.disabled'>Total Billed</Typography>
              <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace' }}>
                {new Intl.NumberFormat('en-TH', { style: 'currency', currency, maximumFractionDigits: 0 }).format(totalBilled)}
              </Typography>
            </Box>
            <Box>
              <Typography variant='caption' color='text.disabled'>Paid</Typography>
              <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace', color: '#71DD37' }}>
                {new Intl.NumberFormat('en-TH', { style: 'currency', currency, maximumFractionDigits: 0 }).format(totalPaid)}
              </Typography>
            </Box>
            <Box>
              <Typography variant='caption' color='text.disabled'>Outstanding</Typography>
              <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace', color: outstanding > 0 ? '#FF4C51' : 'text.secondary' }}>
                {new Intl.NumberFormat('en-TH', { style: 'currency', currency, maximumFractionDigits: 0 }).format(outstanding)}
              </Typography>
            </Box>
          </Box>
        }
        sx={{ pb: 0.5 }}
      />
      <CardContent sx={{ pt: 0 }}>
        {/* AR Aging strip */}
        {!loading && outstanding > 0 && (
          <Box sx={{ mb: 2 }}>
            <Typography variant='caption' color='text.disabled' sx={{ display: 'block', mb: 0.75, fontWeight: 600 }}>
              ACCOUNTS RECEIVABLE AGING
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              {agingBuckets.map(b => b.value > 0 && (
                <Box key={b.label} sx={{ flex: '1 1 80px', p: 1.25, borderRadius: 1.5, bgcolor: `${b.color}15`, border: `1px solid ${b.color}30`, textAlign: 'center' }}>
                  <Typography variant='caption' sx={{ fontWeight: 700, color: b.color, display: 'block' }}>{b.label}</Typography>
                  <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace', color: b.color }}>
                    {new Intl.NumberFormat('en-TH', { maximumFractionDigits: 0 }).format(b.value)}
                  </Typography>
                </Box>
              ))}
            </Box>
          </Box>
        )}
        {loading ? (
          <Typography variant='body2' color='text.disabled' sx={{ py: 3, textAlign: 'center' }}>Loading…</Typography>
        ) : invoices.length === 0 ? (
          <Typography variant='body2' color='text.disabled' sx={{ py: 3, textAlign: 'center' }}>
            No invoices yet — generate one from a matter's time entries
          </Typography>
        ) : (
          <Table size='small'>
            <TableHead>
              <TableRow>
                <TableCell sx={{ fontWeight: 600 }}>Invoice #</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Issue Date</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Due Date</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Status</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Lines</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align='right'>Subtotal</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align='right'>VAT</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align='right'>Total</TableCell>
                <TableCell width={120} />
              </TableRow>
            </TableHead>
            <TableBody>
              {invoices.map(inv => {
                const cfg = INV_STATUS_CONFIG[inv.status] ?? INV_STATUS_CONFIG.draft
                return (
                  <TableRow key={inv._id} hover>
                    <TableCell>
                      <Typography variant='caption' sx={{ fontFamily: 'monospace', fontWeight: 700 }}>{inv.invoiceNumber}</Typography>
                    </TableCell>
                    <TableCell><Typography variant='caption'>{new Date(inv.issueDate).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}</Typography></TableCell>
                    <TableCell><Typography variant='caption'>{new Date(inv.dueDate).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}</Typography></TableCell>
                    <TableCell>
                      <Chip label={cfg.label} size='small' sx={{ bgcolor: cfg.bg, color: cfg.color, fontWeight: 600, height: 18, fontSize: '0.65rem' }} />
                    </TableCell>
                    <TableCell><Typography variant='caption' color='text.secondary'>{inv.lineItems.length}</Typography></TableCell>
                    <TableCell align='right'>
                      <Typography variant='caption' sx={{ fontFamily: 'monospace' }}>
                        {new Intl.NumberFormat('en-TH', { maximumFractionDigits: 0 }).format(inv.subtotal)}
                      </Typography>
                    </TableCell>
                    <TableCell align='right'>
                      <Typography variant='caption' sx={{ fontFamily: 'monospace' }} color='text.secondary'>
                        {new Intl.NumberFormat('en-TH', { maximumFractionDigits: 0 }).format(inv.vatAmount)}
                      </Typography>
                    </TableCell>
                    <TableCell align='right'>
                      <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace' }}>
                        {new Intl.NumberFormat('en-TH', { maximumFractionDigits: 0 }).format(inv.total)}
                      </Typography>
                    </TableCell>
                    <TableCell align='right' sx={{ whiteSpace: 'nowrap' }}>
                      {inv.status === 'draft' && (
                        <Tooltip title='Mark Sent'>
                          <IconButton size='small' onClick={() => action(inv._id, 'send')}>
                            <i className='ri-send-plane-line' style={{ fontSize: '0.85rem' }} />
                          </IconButton>
                        </Tooltip>
                      )}
                      {(inv.status === 'draft' || inv.status === 'sent') && (
                        <Tooltip title='Mark Paid'>
                          <IconButton size='small' onClick={() => action(inv._id, 'pay', { paidAmount: inv.total })}>
                            <i className='ri-checkbox-circle-line' style={{ fontSize: '0.85rem', color: '#71DD37' }} />
                          </IconButton>
                        </Tooltip>
                      )}
                      {inv.status !== 'paid' && inv.status !== 'void' && (
                        <Tooltip title='Void'>
                          <IconButton size='small' onClick={() => action(inv._id, 'void')}>
                            <i className='ri-close-circle-line' style={{ fontSize: '0.85rem', color: '#FF4C51' }} />
                          </IconButton>
                        </Tooltip>
                      )}
                      <Tooltip title='Download PDF'>
                        <IconButton size='small' component='a' href={`/api/invoices/${inv._id}/pdf`} target='_blank'>
                          <i className='ri-file-pdf-2-line' style={{ fontSize: '0.85rem', color: '#FF4C51' }} />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        )}
      </CardContent>
    </Card>
  )
}

// ─── Trust Ledger Section ─────────────────────────────────────────────────────

const TRUST_TX_CONFIG: Record<TrustTxType, { label: string; dir: 1 | -1; color: string }> = {
  receipt:      { label: 'Receipt',      dir:  1, color: '#0D9394' },
  disbursement: { label: 'Disbursement', dir: -1, color: '#FF4C51' },
  transfer_out: { label: 'Transfer Out', dir: -1, color: '#7C6AF7' },
  interest:     { label: 'Interest',     dir:  1, color: '#71DD37' },
  fee_draw:     { label: 'Fee Draw',     dir: -1, color: '#FF9F43' },
  refund:       { label: 'Refund',       dir: -1, color: '#FF6B6B' },
  adjustment:   { label: 'Adjustment',   dir:  1, color: '#8A92A3' },
}

const TRUST_TX_TYPES: TrustTxType[] = ['receipt','disbursement','fee_draw','refund','disbursement','transfer_out','interest','adjustment']
const TRUST_TX_UNIQUE: TrustTxType[] = ['receipt','disbursement','transfer_out','interest','fee_draw','refund','adjustment']

function TrustLedgerSection({ folderId, currency }: { folderId: string; currency: string }) {
  const [account, setAccount]     = useState<TrustAccount | null>(null)
  const [txns, setTxns]           = useState<TrustTransaction[]>([])
  const [loading, setLoading]     = useState(true)
  const [addOpen, setAddOpen]     = useState(false)
  const [reconcileOpen, setRecOpen] = useState(false)
  const [saving, setSaving]       = useState(false)
  const [err, setErr]             = useState('')
  const [txForm, setTxForm]       = useState({
    type: 'receipt' as TrustTxType, amount: '', description: '',
    txDate: new Date().toISOString().slice(0, 10), reference: '', createdBy: 'Counsel',
  })
  const [reconForm, setReconForm] = useState({ bankBalance: '', reconciledBy: 'Counsel', notes: '' })

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const [acctRes, txRes] = await Promise.all([
        fetch(`/api/trust/accounts/${folderId}`),
        fetch(`/api/trust/transactions?clientFolderId=${folderId}&limit=100`),
      ])
      const acctData = await acctRes.json()
      const txData   = await txRes.json()
      setAccount(acctData)
      setTxns(txData.items ?? [])
    } finally { setLoading(false) }
  }, [folderId])

  useEffect(() => { load() }, [load])

  async function addTx() {
    if (!txForm.amount || !txForm.description) { setErr('Amount and description required'); return }
    setSaving(true); setErr('')
    try {
      const r = await fetch('/api/trust/transactions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...txForm, amount: parseFloat(txForm.amount), clientFolderId: folderId, currency }),
      })
      if (!r.ok) { const d = await r.json(); setErr(d.message ?? 'Failed'); return }
      setAddOpen(false)
      setTxForm(f => ({ ...f, amount: '', description: '', reference: '' }))
      load()
    } finally { setSaving(false) }
  }

  async function reconcile() {
    if (!reconForm.bankBalance) { setErr('Bank balance required'); return }
    setSaving(true); setErr('')
    try {
      const r = await fetch(`/api/trust/accounts/${folderId}/reconcile`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...reconForm, bankBalance: parseFloat(reconForm.bankBalance) }),
      })
      if (!r.ok) { const d = await r.json(); setErr(d.message ?? 'Failed'); return }
      setRecOpen(false)
      load()
    } finally { setSaving(false) }
  }

  const fmt = (n: number) => new Intl.NumberFormat('en-TH', { maximumFractionDigits: 2 }).format(n)
  const variance = account ? account.bookBalance - account.bankBalance : 0

  return (
    <Card>
      <CardHeader
        title='Trust Account'
        titleTypographyProps={{ variant: 'subtitle2' }}
        avatar={<i className='ri-bank-line' style={{ color: '#0D9394', fontSize: '1rem' }} />}
        action={
          <Box sx={{ display: 'flex', gap: 1, mr: 1 }}>
            <Button size='small' variant='outlined' startIcon={<i className='ri-scales-line' />} onClick={() => { setErr(''); setRecOpen(true) }}>
              Reconcile
            </Button>
            <Button size='small' variant='contained' startIcon={<i className='ri-add-line' />} onClick={() => { setErr(''); setAddOpen(true) }}>
              New Entry
            </Button>
          </Box>
        }
        subheader={
          !loading && account ? (
            <Box sx={{ display: 'flex', gap: 3, mt: 0.5, flexWrap: 'wrap' }}>
              <Box>
                <Typography variant='caption' color='text.disabled'>Book Balance</Typography>
                <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace', color: account.bookBalance >= 0 ? '#0D9394' : '#FF4C51' }}>
                  {fmt(account.bookBalance)} {account.currency}
                </Typography>
              </Box>
              <Box>
                <Typography variant='caption' color='text.disabled'>Bank Balance</Typography>
                <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace' }}>
                  {fmt(account.bankBalance)} {account.currency}
                </Typography>
              </Box>
              <Box>
                <Typography variant='caption' color='text.disabled'>Variance</Typography>
                <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace', color: Math.abs(variance) < 0.01 ? '#71DD37' : '#FF4C51' }}>
                  {variance >= 0 ? '+' : ''}{fmt(variance)}
                </Typography>
              </Box>
              <Box sx={{ alignSelf: 'center' }}>
                {account.isReconciled
                  ? <Chip label='Reconciled' size='small' sx={{ bgcolor: '#EEFBE5', color: '#71DD37', fontWeight: 600, height: 20, fontSize: '0.65rem' }} />
                  : <Chip label='Unreconciled' size='small' sx={{ bgcolor: '#FFECEC', color: '#FF4C51', fontWeight: 600, height: 20, fontSize: '0.65rem' }} />
                }
              </Box>
            </Box>
          ) : null
        }
        sx={{ pb: 0.5 }}
      />
      <CardContent sx={{ pt: 0 }}>
        {loading ? (
          <Typography variant='body2' color='text.disabled' sx={{ py: 3, textAlign: 'center' }}>Loading…</Typography>
        ) : txns.length === 0 ? (
          <Typography variant='body2' color='text.disabled' sx={{ py: 3, textAlign: 'center' }}>
            No trust transactions — add a receipt to start the trust ledger
          </Typography>
        ) : (
          <Table size='small'>
            <TableHead>
              <TableRow>
                <TableCell sx={{ fontWeight: 600 }}>Date</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Type</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Description</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Reference</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align='right'>Debit</TableCell>
                <TableCell sx={{ fontWeight: 600 }} align='right'>Credit</TableCell>
                <TableCell sx={{ fontWeight: 600, width: 70 }}>Rec.</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {txns.map(tx => {
                const cfg = TRUST_TX_CONFIG[tx.type]
                const isCredit = cfg.dir === 1
                return (
                  <TableRow key={tx._id} hover>
                    <TableCell>
                      <Typography variant='caption'>{new Date(tx.txDate).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}</Typography>
                    </TableCell>
                    <TableCell>
                      <Chip label={cfg.label} size='small' sx={{ bgcolor: `${cfg.color}20`, color: cfg.color, fontWeight: 600, height: 18, fontSize: '0.65rem' }} />
                    </TableCell>
                    <TableCell><Typography variant='caption'>{tx.description}</Typography></TableCell>
                    <TableCell><Typography variant='caption' color='text.secondary'>{tx.reference ?? '—'}</Typography></TableCell>
                    <TableCell align='right'>
                      {!isCredit && <Typography variant='caption' sx={{ fontFamily: 'monospace', color: '#FF4C51' }}>{fmt(tx.amount)}</Typography>}
                    </TableCell>
                    <TableCell align='right'>
                      {isCredit && <Typography variant='caption' sx={{ fontFamily: 'monospace', color: '#0D9394' }}>{fmt(tx.amount)}</Typography>}
                    </TableCell>
                    <TableCell>
                      {tx.reconciled
                        ? <i className='ri-checkbox-circle-fill' style={{ color: '#71DD37', fontSize: '0.9rem' }} />
                        : <i className='ri-checkbox-blank-circle-line' style={{ color: '#8A92A3', fontSize: '0.9rem' }} />
                      }
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        )}
      </CardContent>

      {/* Add Transaction Dialog */}
      <Dialog open={addOpen} onClose={() => setAddOpen(false)} maxWidth='sm' fullWidth>
        <DialogTitle>New Trust Transaction</DialogTitle>
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '16px !important' }}>
          <Box sx={{ display: 'flex', gap: 1.5 }}>
            <TextField select label='Type' value={txForm.type} onChange={e => setTxForm(f => ({ ...f, type: e.target.value as TrustTxType }))} fullWidth size='small'>
              {TRUST_TX_UNIQUE.map(t => <MenuItem key={t} value={t}>{TRUST_TX_CONFIG[t].label}</MenuItem>)}
            </TextField>
            <TextField label='Amount' type='number' value={txForm.amount} onChange={e => setTxForm(f => ({ ...f, amount: e.target.value }))} fullWidth size='small' inputProps={{ min: 0.01, step: 0.01 }} />
          </Box>
          <TextField label='Date' type='date' value={txForm.txDate} onChange={e => setTxForm(f => ({ ...f, txDate: e.target.value }))} fullWidth size='small' InputLabelProps={{ shrink: true }} />
          <TextField label='Description' value={txForm.description} onChange={e => setTxForm(f => ({ ...f, description: e.target.value }))} fullWidth size='small' />
          <TextField label='Reference (optional)' value={txForm.reference} onChange={e => setTxForm(f => ({ ...f, reference: e.target.value }))} fullWidth size='small' placeholder='Cheque #, wire ref, etc.' />
          {err && <Alert severity='error'>{err}</Alert>}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setAddOpen(false)}>Cancel</Button>
          <Button variant='contained' disabled={saving} onClick={addTx}>Save</Button>
        </DialogActions>
      </Dialog>

      {/* Reconcile Dialog */}
      <Dialog open={reconcileOpen} onClose={() => setRecOpen(false)} maxWidth='xs' fullWidth>
        <DialogTitle>Bank Reconciliation</DialogTitle>
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '16px !important' }}>
          <Typography variant='body2' color='text.secondary'>
            Enter the closing balance from your trust account bank statement. The system will compare it to the book balance and flag any variance.
          </Typography>
          {account && (
            <Box sx={{ p: 1.5, bgcolor: 'action.hover', borderRadius: 1.5 }}>
              <Typography variant='caption' color='text.secondary'>Book balance: <strong>{fmt(account.bookBalance)} {account.currency}</strong></Typography>
            </Box>
          )}
          <TextField label='Bank Statement Balance' type='number' value={reconForm.bankBalance} onChange={e => setReconForm(f => ({ ...f, bankBalance: e.target.value }))} fullWidth size='small' inputProps={{ step: 0.01 }} />
          <TextField label='Reconciled by' value={reconForm.reconciledBy} onChange={e => setReconForm(f => ({ ...f, reconciledBy: e.target.value }))} fullWidth size='small' />
          <TextField label='Notes (optional)' value={reconForm.notes} onChange={e => setReconForm(f => ({ ...f, notes: e.target.value }))} fullWidth size='small' multiline rows={2} />
          {err && <Alert severity='error'>{err}</Alert>}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRecOpen(false)}>Cancel</Button>
          <Button variant='contained' disabled={saving} onClick={reconcile}>Reconcile</Button>
        </DialogActions>
      </Dialog>
    </Card>
  )
}

function fmtCurrency(amount: number, currency = 'THB') {
  return new Intl.NumberFormat('en-TH', { style: 'currency', currency, maximumFractionDigits: 0 }).format(amount)
}

function fmtDate(iso?: string) {
  if (!iso) return '—'
  return new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })
}

const TX_TYPES: RetainerTransaction['type'][] = ['intake', 'disbursement', 'refund', 'invoice_applied']

const TX_CONFIG: Record<RetainerTransaction['type'], { label: string; color: string; bg: string; sign: 1 | -1 }> = {
  intake:          { label: 'Intake',          color: '#0D9394', bg: '#E8F7F7', sign:  1 },
  disbursement:    { label: 'Disbursement',    color: '#FF4C51', bg: '#FFECEC', sign: -1 },
  refund:          { label: 'Refund',          color: '#7C6AF7', bg: '#EEF2FF', sign: -1 },
  invoice_applied: { label: 'Invoice Applied', color: '#FFB400', bg: '#FFF5DB', sign: -1 },
}

interface Props {
  folder: ClientFolder
  lang: string
  embedded?: boolean   // true = rendered as a tab, hides page header
}

export default function ClientBillingView({ folder: initial, lang, embedded }: Props) {
  const router = useRouter()
  const [folder, setFolder]   = useState(initial)
  const [dialog, setDialog]   = useState(false)
  const [saving, setSaving]   = useState(false)
  const [err, setErr]         = useState<string | null>(null)
  const [draft, setDraft]     = useState({
    type: 'intake' as RetainerTransaction['type'],
    amount: '',
    date: new Date().toISOString().split('T')[0],
    description: '',
    matterId: '',
    invoiceRef: '',
    createdBy: 'Patchara S.',
  })

  const ledger = [...(folder.retainerLedger ?? [])].sort(
    (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
  )

  const low = folder.status === 'active' && folder.retainerBalance < folder.retainerThreshold

  const openDialog = () => {
    setDraft({ type: 'intake', amount: '', date: new Date().toISOString().split('T')[0], description: '', matterId: '', invoiceRef: '', createdBy: 'Patchara S.' })
    setErr(null); setDialog(true)
  }

  const save = async () => {
    if (!draft.amount || isNaN(Number(draft.amount))) { setErr('Enter a valid amount'); return }
    if (!draft.description.trim()) { setErr('Description is required'); return }
    setSaving(true); setErr(null)

    try {
      const res = await fetch(`/api/clients/${folder._id}/retainer/transactions`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: draft.type,
          amount: Math.abs(Number(draft.amount)),
          date: draft.date,
          description: draft.description,
          ...(draft.matterId   ? { matterId:   draft.matterId   } : {}),
          ...(draft.invoiceRef ? { invoiceRef: draft.invoiceRef } : {}),
          createdBy: draft.createdBy,
        }),
      })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? 'Save failed')
      setFolder(await res.json()); setDialog(false)
    } catch (e: any) { setErr(e.message) }
    finally { setSaving(false) }
  }

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, maxWidth: embedded ? undefined : 900 }}>

      {/* Header — hidden when embedded as a tab */}
      {!embedded && (
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <Box>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.25 }}>
              <Button size='small' variant='text' startIcon={<i className='ri-arrow-left-line' />}
                onClick={() => router.push(`/${lang}/clients/${folder._id}`)}
                sx={{ fontSize: '0.75rem', color: 'text.secondary', p: 0, minWidth: 0 }}>
                {folder.displayName}
              </Button>
              <Typography variant='caption' color='text.disabled'>/ Billing Ledger</Typography>
            </Box>
            <Typography variant='h4' sx={{ fontWeight: 700 }}>Billing Ledger</Typography>
            <Typography variant='body2' color='text.secondary'>{folder.folderNumber}</Typography>
          </Box>
          <Button variant='contained' startIcon={<i className='ri-add-line' />} onClick={openDialog}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            Add Transaction
          </Button>
        </Box>
      )}

      {embedded && (
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <BillingConfigSummary folder={folder} lang={lang} />
          <Button variant='contained' size='small' startIcon={<i className='ri-add-line' />} onClick={openDialog}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            Add Transaction
          </Button>
        </Box>
      )}

      {/* Balance summary cards */}
      <Box sx={{ display: 'flex', gap: 2 }}>
        <Card sx={{ flex: 1, borderLeft: `4px solid ${low ? '#FF4C51' : '#0D9394'}` }}>
          <CardContent sx={{ py: 1.5, '&:last-child': { pb: 1.5 } }}>
            <Typography variant='caption' color='text.disabled'>Current Balance</Typography>
            <Typography variant='h4' sx={{ fontWeight: 700, color: low ? '#FF4C51' : 'text.primary', mt: 0.25 }}>
              {fmtCurrency(folder.retainerBalance, folder.currency)}
            </Typography>
            {low && <Chip label='Below threshold' size='small' sx={{ mt: 0.5, bgcolor: '#FFECEC', color: '#FF4C51', fontWeight: 600, fontSize: '0.65rem', height: 18 }} />}
          </CardContent>
        </Card>
        <Card sx={{ flex: 1 }}>
          <CardContent sx={{ py: 1.5, '&:last-child': { pb: 1.5 } }}>
            <Typography variant='caption' color='text.disabled'>Threshold</Typography>
            <Typography variant='h4' sx={{ fontWeight: 700, mt: 0.25 }}>
              {fmtCurrency(folder.retainerThreshold, folder.currency)}
            </Typography>
          </CardContent>
        </Card>
        <Card sx={{ flex: 1 }}>
          <CardContent sx={{ py: 1.5, '&:last-child': { pb: 1.5 } }}>
            <Typography variant='caption' color='text.disabled'>Total Transactions</Typography>
            <Typography variant='h4' sx={{ fontWeight: 700, mt: 0.25 }}>{ledger.length}</Typography>
          </CardContent>
        </Card>
        <Card sx={{ flex: 1 }}>
          <CardContent sx={{ py: 1.5, '&:last-child': { pb: 1.5 } }}>
            <Typography variant='caption' color='text.disabled'>Total Intake</Typography>
            <Typography variant='h4' sx={{ fontWeight: 700, color: '#0D9394', mt: 0.25 }}>
              {fmtCurrency(ledger.filter(t => t.amount > 0).reduce((s, t) => s + t.amount, 0), folder.currency)}
            </Typography>
          </CardContent>
        </Card>
      </Box>

      <Divider />

      {/* Ledger table */}
      <Card>
        <CardContent sx={{ pt: 0.5 }}>
          {ledger.length === 0 ? (
            <Typography variant='body2' color='text.disabled' sx={{ py: 4, textAlign: 'center' }}>
              No transactions on record — add the first intake above
            </Typography>
          ) : (
            <Table size='small'>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 600 }}>Date</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Type</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Description</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Matter / Invoice</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align='right'>Amount</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>By</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {ledger.map((tx, i) => {
                  const cfg = TX_CONFIG[tx.type] ?? { label: tx.type, color: '#6B7280', bg: '#F0F0F0' }
                  return (
                    <TableRow key={tx.txId ?? i} hover>
                      <TableCell><Typography variant='caption'>{fmtDate(tx.date)}</Typography></TableCell>
                      <TableCell>
                        <Chip label={cfg.label} size='small'
                          sx={{ fontSize: '0.65rem', height: 18, bgcolor: cfg.bg, color: cfg.color, fontWeight: 600 }} />
                      </TableCell>
                      <TableCell><Typography variant='body2'>{tx.description}</Typography></TableCell>
                      <TableCell>
                        <Typography variant='caption' color='text.secondary'>
                          {[tx.matterId, tx.invoiceRef].filter(Boolean).join(' / ') || '—'}
                        </Typography>
                      </TableCell>
                      <TableCell align='right'>
                        <Typography variant='body2' sx={{ fontWeight: 600, fontFamily: 'monospace',
                          color: tx.amount > 0 ? '#0D9394' : '#FF4C51' }}>
                          {tx.amount > 0 ? '+' : ''}{fmtCurrency(tx.amount, folder.currency)}
                        </Typography>
                      </TableCell>
                      <TableCell><Typography variant='caption' color='text.disabled'>{tx.createdBy}</Typography></TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <InvoicesSection folderId={folder._id} currency={folder.currency} />

      <TrustLedgerSection folderId={folder._id} currency={folder.currency} />

      {/* Add Transaction dialog */}
      <Dialog open={dialog} onClose={() => setDialog(false)} maxWidth='sm' fullWidth>
        <DialogTitle>Add Retainer Transaction</DialogTitle>
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '12px !important' }}>
          {err && <Alert severity='error'>{err}</Alert>}
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField select fullWidth size='small' label='Type' value={draft.type}
              onChange={e => setDraft(d => ({ ...d, type: e.target.value as RetainerTransaction['type'] }))}>
              {TX_TYPES.map(t => <MenuItem key={t} value={t}>{TX_CONFIG[t].label}</MenuItem>)}
            </TextField>
            <TextField fullWidth size='small' label='Amount' type='number'
              value={draft.amount} onChange={e => setDraft(d => ({ ...d, amount: e.target.value }))}
              InputProps={{ startAdornment: <Typography variant='caption' color='text.disabled' sx={{ mr: 0.5 }}>{folder.currency}</Typography> }} />
            <TextField fullWidth size='small' label='Date' type='date'
              value={draft.date} onChange={e => setDraft(d => ({ ...d, date: e.target.value }))}
              InputLabelProps={{ shrink: true }} />
          </Box>
          <TextField fullWidth required size='small' label='Description'
            value={draft.description} onChange={e => setDraft(d => ({ ...d, description: e.target.value }))}
            placeholder='e.g. Initial retainer intake per engagement letter EL-2026-0001' />
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' label='Matter ID (optional)'
              value={draft.matterId} onChange={e => setDraft(d => ({ ...d, matterId: e.target.value }))} />
            <TextField fullWidth size='small' label='Invoice Ref (optional)'
              value={draft.invoiceRef} onChange={e => setDraft(d => ({ ...d, invoiceRef: e.target.value }))} />
          </Box>
          <TextField fullWidth size='small' label='Recorded by'
            value={draft.createdBy} onChange={e => setDraft(d => ({ ...d, createdBy: e.target.value }))} />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialog(false)} disabled={saving}>Cancel</Button>
          <Button variant='contained' onClick={save} disabled={saving}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            {saving ? 'Saving…' : 'Save Transaction'}
          </Button>
        </DialogActions>
      </Dialog>

    </Box>
  )
}
