'use client'

import { useState, useEffect, useCallback } from 'react'
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 Chip from '@mui/material/Chip'
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 LinearProgress from '@mui/material/LinearProgress'
import type { Invoice, TrustAccount } from '@/views/clients/types'

// ─── Helpers ──────────────────────────────────────────────────────────────────

const fmt = (n: number, currency = 'THB') =>
  new Intl.NumberFormat('en-TH', { style: 'currency', currency, maximumFractionDigits: 0 }).format(n)
const fmtDate = (iso: string) =>
  new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })

// ─── Stat card ────────────────────────────────────────────────────────────────

function StatCard({ icon, label, value, sub, color = '#0D9394' }: {
  icon: string; label: string; value: string; sub?: string; color?: string
}) {
  return (
    <Card sx={{ flex: '1 1 200px' }}>
      <CardContent sx={{ display: 'flex', alignItems: 'flex-start', gap: 1.5, pb: '12px !important' }}>
        <Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: `${color}20`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <i className={icon} style={{ fontSize: '1.2rem', color }} />
        </Box>
        <Box>
          <Typography variant='caption' color='text.disabled' display='block'>{label}</Typography>
          <Typography variant='h6' sx={{ fontWeight: 700, fontFamily: 'monospace', lineHeight: 1.2 }}>{value}</Typography>
          {sub && <Typography variant='caption' color='text.secondary'>{sub}</Typography>}
        </Box>
      </CardContent>
    </Card>
  )
}

// ─── Main ─────────────────────────────────────────────────────────────────────

export default function FirmBillingDashboard({ lang }: { lang: string }) {
  const [invoices, setInvoices]   = useState<Invoice[]>([])
  const [trust, setTrust]         = useState<{ items: TrustAccount[]; totalTrustHeld: number; unreconciled: number } | null>(null)
  const [loading, setLoading]     = useState(true)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const [invRes, trustRes] = await Promise.all([
        fetch('/api/invoices?limit=500'),
        fetch('/api/trust/accounts?limit=500'),
      ])
      const invData   = await invRes.json()
      const trustData = await trustRes.json()
      setInvoices(invData.items ?? [])
      setTrust(trustData)
    } finally { setLoading(false) }
  }, [])

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

  // ── Invoice pipeline metrics ────────────────────────────────────────────────

  const nonVoid = invoices.filter(i => i.status !== 'void')
  const drafts  = invoices.filter(i => i.status === 'draft')
  const sent    = invoices.filter(i => i.status === 'sent')
  const paid    = invoices.filter(i => i.status === 'paid')

  const totalBilled      = nonVoid.reduce((s, i) => s + i.total, 0)
  const totalOutstanding = sent.reduce((s, i) => s + i.total, 0)
  const totalCollected   = paid.reduce((s, i) => s + (i.paidAmount ?? i.total), 0)
  const totalDraft       = drafts.reduce((s, i) => s + i.total, 0)

  const collectionRate = totalBilled > 0 ? (totalCollected / totalBilled) * 100 : 0

  // ── AR Aging ────────────────────────────────────────────────────────────────

  const today = new Date()
  const aging = { current: 0, d30: 0, d60: 0, d90: 0, d90plus: 0 }
  for (const inv of 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-30 days',  value: aging.d30,     color: '#FFB400' },
    { label: '31-60 days', value: aging.d60,     color: '#FF9F43' },
    { label: '61-90 days', value: aging.d90,     color: '#FF6B6B' },
    { label: '90+ days',   value: aging.d90plus, color: '#FF4C51' },
  ]
  const agingTotal = agingBuckets.reduce((s, b) => s + b.value, 0)

  // ── Top debtors (sent invoices, grouped by client) ──────────────────────────

  const debtorMap = new Map<string, { clientFolderId: string; total: number; oldest: Date; currency: string }>()
  for (const inv of sent) {
    const existing = debtorMap.get(inv.clientFolderId)
    const dueDate  = new Date(inv.dueDate)
    if (!existing) {
      debtorMap.set(inv.clientFolderId, { clientFolderId: inv.clientFolderId, total: inv.total, oldest: dueDate, currency: inv.currency })
    } else {
      existing.total += inv.total
      if (dueDate < existing.oldest) existing.oldest = dueDate
    }
  }
  const topDebtors = [...debtorMap.values()]
    .sort((a, b) => b.total - a.total)
    .slice(0, 10)

  if (loading) {
    return (
      <Box sx={{ p: 4 }}>
        <LinearProgress />
      </Box>
    )
  }

  return (
    <Box sx={{ p: { xs: 2, md: 4 }, display: 'flex', flexDirection: 'column', gap: 3 }}>

      {/* Page title */}
      <Box>
        <Typography variant='h5' sx={{ fontWeight: 700 }}>Billing Dashboard</Typography>
        <Typography variant='body2' color='text.secondary'>Firm-wide AR, trust, and invoice pipeline</Typography>
      </Box>

      {/* Summary stats */}
      <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
        <StatCard icon='ri-bill-line'         label='Total Billed (YTD)'  value={fmt(totalBilled)} sub={`${nonVoid.length} invoices`} />
        <StatCard icon='ri-money-dollar-circle-line' label='Collected'    value={fmt(totalCollected)} sub={`${collectionRate.toFixed(0)}% collection rate`} color='#71DD37' />
        <StatCard icon='ri-time-line'         label='Outstanding'         value={fmt(totalOutstanding)} sub={`${sent.length} sent invoice${sent.length !== 1 ? 's' : ''}`} color='#FF9F43' />
        <StatCard icon='ri-draft-line'        label='In Draft'            value={fmt(totalDraft)} sub={`${drafts.length} draft invoice${drafts.length !== 1 ? 's' : ''}`} color='#8A92A3' />
        <StatCard icon='ri-bank-line'         label='Trust Held'          value={fmt(trust?.totalTrustHeld ?? 0)} sub={trust?.unreconciled ? `${trust.unreconciled} unreconciled` : 'All reconciled'} color='#7C6AF7' />
      </Box>

      {/* AR Aging */}
      {agingTotal > 0 && (
        <Card>
          <CardHeader
            title='AR Aging'
            titleTypographyProps={{ variant: 'subtitle2' }}
            avatar={<i className='ri-calendar-todo-line' style={{ color: '#0D9394', fontSize: '1rem' }} />}
            subheader={`${fmt(agingTotal)} total outstanding`}
          />
          <CardContent sx={{ pt: 0 }}>
            <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', mb: 2 }}>
              {agingBuckets.map(b => (
                <Box key={b.label} sx={{ flex: '1 1 100px', textAlign: 'center', p: 1.5, borderRadius: 2, bgcolor: `${b.color}15`, border: `1px solid ${b.color}25` }}>
                  <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 }}>
                    {fmt(b.value)}
                  </Typography>
                  {agingTotal > 0 && (
                    <Typography variant='caption' color='text.disabled'>
                      {((b.value / agingTotal) * 100).toFixed(0)}%
                    </Typography>
                  )}
                </Box>
              ))}
            </Box>
            {/* Proportional bar */}
            <Box sx={{ display: 'flex', height: 8, borderRadius: 4, overflow: 'hidden', bgcolor: 'action.hover' }}>
              {agingBuckets.filter(b => b.value > 0).map(b => (
                <Box
                  key={b.label}
                  sx={{ height: '100%', bgcolor: b.color, width: `${(b.value / agingTotal) * 100}%` }}
                />
              ))}
            </Box>
          </CardContent>
        </Card>
      )}

      {/* Invoice Pipeline */}
      <Card>
        <CardHeader
          title='Invoice Pipeline'
          titleTypographyProps={{ variant: 'subtitle2' }}
          avatar={<i className='ri-flow-chart' style={{ color: '#0D9394', fontSize: '1rem' }} />}
        />
        <CardContent sx={{ pt: 0 }}>
          <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
            {[
              { label: 'Draft',   count: drafts.length,  total: totalDraft,       color: '#8A92A3', icon: 'ri-draft-line' },
              { label: 'Sent',    count: sent.length,    total: totalOutstanding, color: '#FFB400', icon: 'ri-send-plane-line' },
              { label: 'Paid',    count: paid.length,    total: totalCollected,   color: '#71DD37', icon: 'ri-checkbox-circle-line' },
            ].map(stage => (
              <Box key={stage.label} sx={{ flex: '1 1 160px', p: 2, border: '1px solid', borderColor: `${stage.color}40`, borderRadius: 2, bgcolor: `${stage.color}08` }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
                  <i className={stage.icon} style={{ color: stage.color, fontSize: '1rem' }} />
                  <Typography variant='caption' sx={{ fontWeight: 700, color: stage.color }}>{stage.label}</Typography>
                </Box>
                <Typography variant='h6' sx={{ fontWeight: 700, fontFamily: 'monospace' }}>{fmt(stage.total)}</Typography>
                <Typography variant='caption' color='text.secondary'>{stage.count} invoice{stage.count !== 1 ? 's' : ''}</Typography>
              </Box>
            ))}
          </Box>
        </CardContent>
      </Card>

      {/* Top Debtors */}
      {topDebtors.length > 0 && (
        <Card>
          <CardHeader
            title='Top Outstanding Balances'
            titleTypographyProps={{ variant: 'subtitle2' }}
            avatar={<i className='ri-alert-line' style={{ color: '#FF4C51', fontSize: '1rem' }} />}
          />
          <CardContent sx={{ pt: 0 }}>
            <Table size='small'>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 600 }}>Client Folder ID</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Oldest Due Date</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align='right'>Outstanding</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Age</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {topDebtors.map(d => {
                  const days = Math.floor((today.getTime() - d.oldest.getTime()) / 86400000)
                  const ageColor = days <= 0 ? '#0D9394' : days <= 30 ? '#FFB400' : days <= 60 ? '#FF9F43' : '#FF4C51'
                  return (
                    <TableRow key={d.clientFolderId} hover>
                      <TableCell>
                        <Typography variant='caption' sx={{ fontFamily: 'monospace', fontWeight: 600 }}>{d.clientFolderId.slice(-8).toUpperCase()}</Typography>
                      </TableCell>
                      <TableCell><Typography variant='caption'>{fmtDate(d.oldest.toISOString())}</Typography></TableCell>
                      <TableCell align='right'>
                        <Typography variant='body2' sx={{ fontWeight: 700, fontFamily: 'monospace' }}>{fmt(d.total, d.currency)}</Typography>
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={days <= 0 ? 'Current' : `${days}d overdue`}
                          size='small'
                          sx={{ bgcolor: `${ageColor}20`, color: ageColor, fontWeight: 600, height: 18, fontSize: '0.65rem' }}
                        />
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Trust Accounts Summary */}
      {(trust?.items?.length ?? 0) > 0 && (
        <Card>
          <CardHeader
            title='Trust Accounts'
            titleTypographyProps={{ variant: 'subtitle2' }}
            avatar={<i className='ri-bank-line' style={{ color: '#7C6AF7', fontSize: '1rem' }} />}
            subheader={`${fmt(trust!.totalTrustHeld)} held in trust · ${trust!.unreconciled} account${trust!.unreconciled !== 1 ? 's' : ''} unreconciled`}
          />
          <CardContent sx={{ pt: 0 }}>
            <Table size='small'>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 600 }}>Client Folder</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align='right'>Book Balance</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align='right'>Bank Balance</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align='right'>Variance</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Status</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {trust!.items.map(acc => {
                  const variance = acc.bookBalance - acc.bankBalance
                  return (
                    <TableRow key={acc._id} hover>
                      <TableCell>
                        <Typography variant='caption' sx={{ fontFamily: 'monospace', fontWeight: 600 }}>{acc.clientFolderId.slice(-8).toUpperCase()}</Typography>
                      </TableCell>
                      <TableCell align='right'>
                        <Typography variant='caption' sx={{ fontFamily: 'monospace' }}>{new Intl.NumberFormat('en-TH', { maximumFractionDigits: 2 }).format(acc.bookBalance)}</Typography>
                      </TableCell>
                      <TableCell align='right'>
                        <Typography variant='caption' sx={{ fontFamily: 'monospace' }}>{new Intl.NumberFormat('en-TH', { maximumFractionDigits: 2 }).format(acc.bankBalance)}</Typography>
                      </TableCell>
                      <TableCell align='right'>
                        <Typography variant='caption' sx={{ fontFamily: 'monospace', color: Math.abs(variance) < 0.01 ? 'text.secondary' : '#FF4C51' }}>
                          {variance >= 0 ? '+' : ''}{new Intl.NumberFormat('en-TH', { maximumFractionDigits: 2 }).format(variance)}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        {acc.isReconciled
                          ? <Chip label='Reconciled'   size='small' sx={{ bgcolor: '#EEFBE5', color: '#71DD37', fontWeight: 600, height: 18, fontSize: '0.65rem' }} />
                          : <Chip label='Unreconciled' size='small' sx={{ bgcolor: '#FFECEC', color: '#FF4C51', fontWeight: 600, height: 18, fontSize: '0.65rem' }} />
                        }
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

    </Box>
  )
}
