'use client'

import { useState, useEffect } from 'react'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Chip from '@mui/material/Chip'
import CircularProgress from '@mui/material/CircularProgress'
import Dialog from '@mui/material/Dialog'
import DialogContent from '@mui/material/DialogContent'
import DialogTitle from '@mui/material/DialogTitle'
import Divider from '@mui/material/Divider'
import FormControl from '@mui/material/FormControl'
import Grid from '@mui/material/Grid'
import IconButton from '@mui/material/IconButton'
import InputLabel from '@mui/material/InputLabel'
import LinearProgress from '@mui/material/LinearProgress'
import MenuItem from '@mui/material/MenuItem'
import Select from '@mui/material/Select'
import Step from '@mui/material/Step'
import StepLabel from '@mui/material/StepLabel'
import Stepper from '@mui/material/Stepper'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'
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 TextField from '@mui/material/TextField'
import Tooltip from '@mui/material/Tooltip'
import Typography from '@mui/material/Typography'
import Alert from '@mui/material/Alert'

// ─── Types ────────────────────────────────────────────────────────────────────

interface Director {
  uid?: string; nameEn: string; nameTh: string; email: string; lineId?: string; role: 'director' | 'chairman'
}

interface Shareholder {
  uid?: string; entityNameEn: string; entityNameTh: string; shareCount: number; contactEmail: string; lineId?: string; proxyToUid?: string
}

interface ComplianceDoc {
  uid: string; templateStockId: string; label: string; recipientType?: string
  recipientUid?: string; recipientNameEn?: string; generatedFormId?: string
  status: 'draft' | 'sent' | 'signed' | 'returned'; retentionCategory: string
  sentAt?: string; signedAt?: string; returnedAt?: string
}

interface DashboardMatter {
  matterId: string; matterNumber: string; companyNameEn?: string; companyNameTh?: string
  fiscalYear?: string; yearEndDate?: string; agmDate?: string; status: string
  documentProgress: { total: number; signed: number }
  pendingSignatories: { name?: string; label: string; status: string }[]
}

interface MatterDetail {
  _id: string; matterNumber: string; title: string; status: string
  annualCompliance?: {
    companyNameEn: string; companyNameTh: string; fiscalYear: string
    yearEndDate: string; agmDate?: string; agmMeeting?: { date?: string; time?: string }
    directors: (Director & { signatureStatus: string })[]; shareholders: (Shareholder & { signatureStatus: string })[]
    documents: ComplianceDoc[]; auditorName?: string; auditorFeeThb?: number; feeThb: number
  }
}

interface DeadlineItem {
  _id: string; name: string; dueDate: string; status: string; obligationKey: string
}

const STEPS = ['Company', 'Directors', 'Shareholders', 'Meetings', 'Auditor & Fees', 'Review']

const STATUS_COLOR: Record<string, 'default' | 'primary' | 'warning' | 'success' | 'error'> = {
  draft: 'default', sent: 'primary', signed: 'warning', returned: 'success',
}

const URGENCY = (days: number, completed: boolean) => {
  if (completed) return 'success'
  if (days < 0) return 'error'
  if (days <= 14) return 'error'
  if (days <= 30) return 'warning'
  return 'success'
}

// ─── Wizard form ─────────────────────────────────────────────────────────────

const emptyDir = (): Director => ({ nameEn: '', nameTh: '', email: '', role: 'director' })
const emptySh  = (): Shareholder => ({ entityNameEn: '', entityNameTh: '', shareCount: 0, contactEmail: '' })

function WizardDialog({ open, onClose, onCreated }: {
  open: boolean
  onClose: () => void
  onCreated: (matterId: string) => void
}) {
  const [step, setStep] = useState(0)
  const [saving, setSaving] = useState(false)
  const [err, setErr]   = useState('')

  // Form state
  const [clientFolderId, setClientFolderId] = useState('')
  const [companyNameEn, setCompanyNameEn]   = useState('')
  const [companyNameTh, setCompanyNameTh]   = useState('')
  const [companyReg, setCompanyReg]         = useState('')
  const [fiscalYear, setFiscalYear]         = useState(String(new Date().getFullYear() - 1))
  const [yearEndDate, setYearEndDate]       = useState('')
  const [addrEn, setAddrEn]                 = useState('')
  const [addrTh, setAddrTh]                 = useState('')
  const [directors, setDirectors]           = useState<Director[]>([{ ...emptyDir(), role: 'chairman' }])
  const [shareholders, setShareholders]     = useState<Shareholder[]>([emptySh()])
  const [bodDate, setBodDate]               = useState('')
  const [bodTime, setBodTime]               = useState('10:00')
  const [bodVenue, setBodVenue]             = useState('')
  const [agmDate, setAgmDate]               = useState('')
  const [agmTime, setAgmTime]               = useState('10:00')
  const [agmVenue, setAgmVenue]             = useState('')
  const [auditorName, setAuditorName]       = useState('')
  const [auditorFee, setAuditorFee]         = useState('')
  const [feeThb, setFeeThb]                 = useState('15000')
  const [vatIncluded, setVatIncluded]       = useState(false)

  const [clients, setClients] = useState<{ _id: string; displayName: string; folderNumber: string }[]>([])
  useEffect(() => {
    fetch('/api/clients?limit=500').then(r => r.json()).then(d => setClients(d.items ?? []))
  }, [])

  const updateDir = (i: number, patch: Partial<Director>) =>
    setDirectors(prev => prev.map((d, j) => j === i ? { ...d, ...patch } : d))

  const updateSh = (i: number, patch: Partial<Shareholder>) =>
    setShareholders(prev => prev.map((s, j) => j === i ? { ...s, ...patch } : s))

  const validate = (): string => {
    if (step === 0) {
      if (!clientFolderId)   return 'Select a client folder'
      if (!companyNameEn)    return 'Company name (EN) is required'
      if (!companyNameTh)    return 'Company name (TH) is required'
      if (!yearEndDate)      return 'Year-end date is required'
    }
    if (step === 1 && directors.some(d => !d.nameEn || !d.nameTh || !d.email)) return 'Complete all director fields'
    if (step === 1 && !directors.some(d => d.role === 'chairman')) return 'At least one director must be Chairman'
    if (step === 2 && shareholders.some(s => !s.entityNameEn || !s.shareCount)) return 'Complete all shareholder fields'
    return ''
  }

  const handleNext = () => {
    const e = validate()
    if (e) { setErr(e); return }
    setErr('')
    setStep(s => s + 1)
  }

  const handleSubmit = async () => {
    setSaving(true)
    setErr('')
    try {
      const res = await fetch('/api/annual-compliance', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          clientFolderId,
          responsibleAttorney: 'attorney',
          companyNameEn, companyNameTh, companyRegNumber: companyReg,
          fiscalYear, yearEndDate,
          registeredAddressEn: addrEn, registeredAddressTh: addrTh,
          directors: directors.map(({ uid: _u, ...d }) => d),
          shareholders: shareholders.map(({ uid: _u, ...s }) => s),
          bodMeeting:  { date: bodDate, time: bodTime, venue: bodVenue || addrEn },
          agmMeeting:  { date: agmDate, time: agmTime, venue: agmVenue || addrEn },
          auditorName: auditorName || undefined,
          auditorFeeThb: auditorFee ? parseFloat(auditorFee) : undefined,
          feeThb: parseFloat(feeThb) || 15000,
          vatIncluded,
        }),
      })
      const matter = await res.json()
      if (!res.ok) throw new Error(matter.message ?? 'Failed to create matter')
      // Auto-generate all documents immediately after creation
      const genRes = await fetch(`/api/annual-compliance/${matter._id}/generate-documents`, { method: 'POST' })
      if (!genRes.ok) {
        // Matter created but doc generation failed — still open the matter panel
        console.error('Document generation failed:', await genRes.text())
      }
      onCreated(matter._id)
    } catch (e: any) {
      setErr(e.message)
    } finally {
      setSaving(false)
    }
  }

  const agmDeadline = yearEndDate
    ? new Date(new Date(yearEndDate).setMonth(new Date(yearEndDate).getMonth() + 4))
        .toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' })
    : null

  return (
    <Dialog open={open} onClose={onClose} maxWidth='md' fullWidth>
      <DialogTitle sx={{ pb: 1 }}>
        New Annual Compliance Matter
        <IconButton onClick={onClose} sx={{ position: 'absolute', right: 12, top: 12 }}>
          <i className='ri-close-line' />
        </IconButton>
      </DialogTitle>
      <DialogContent>
        <Stepper activeStep={step} alternativeLabel sx={{ mb: 3 }}>
          {STEPS.map(s => <Step key={s}><StepLabel>{s}</StepLabel></Step>)}
        </Stepper>

        {err && <Alert severity='error' sx={{ mb: 2 }}>{err}</Alert>}

        {/* Step 0: Company */}
        {step === 0 && (
          <Grid container spacing={2}>
            <Grid size={12}>
              <FormControl fullWidth required>
                <InputLabel>Client Folder</InputLabel>
                <Select value={clientFolderId} label='Client Folder' onChange={e => setClientFolderId(e.target.value)}>
                  {clients.map(c => <MenuItem key={c._id} value={c._id}>{c.folderNumber} — {c.displayName}</MenuItem>)}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={6}><TextField fullWidth required label='Company Name (EN)' value={companyNameEn} onChange={e => setCompanyNameEn(e.target.value)} /></Grid>
            <Grid size={6}><TextField fullWidth required label='ชื่อบริษัท (TH)' value={companyNameTh} onChange={e => setCompanyNameTh(e.target.value)} /></Grid>
            <Grid size={4}><TextField fullWidth label='Registration No. (บอจ.)' value={companyReg} onChange={e => setCompanyReg(e.target.value)} /></Grid>
            <Grid size={4}><TextField fullWidth required label='Fiscal Year' type='number' value={fiscalYear} onChange={e => setFiscalYear(e.target.value)} /></Grid>
            <Grid size={4}><TextField fullWidth required label='Year-End Date' type='date' value={yearEndDate} onChange={e => setYearEndDate(e.target.value)} InputLabelProps={{ shrink: true }} helperText='All deadlines calculated from this' /></Grid>
            <Grid size={12}><TextField fullWidth multiline rows={2} label='Registered Address (EN)' value={addrEn} onChange={e => setAddrEn(e.target.value)} /></Grid>
            <Grid size={12}><TextField fullWidth multiline rows={2} label='ที่อยู่จดทะเบียน (TH)' value={addrTh} onChange={e => setAddrTh(e.target.value)} /></Grid>
          </Grid>
        )}

        {/* Step 1: Directors */}
        {step === 1 && (
          <Box>
            <Typography variant='body2' color='text.secondary' mb={2}>One BOD Acknowledgment document is generated per director.</Typography>
            {directors.map((d, i) => (
              <Card key={i} variant='outlined' sx={{ mb: 2, p: 1 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='subtitle2'>Director {i + 1}</Typography>
                  {directors.length > 1 && <IconButton size='small' color='error' onClick={() => setDirectors(p => p.filter((_, j) => j !== i))}><i className='ri-delete-bin-line' /></IconButton>}
                </Box>
                <Grid container spacing={2}>
                  <Grid size={5}><TextField fullWidth required label='Full Name (EN)' value={d.nameEn} onChange={e => updateDir(i, { nameEn: e.target.value })} /></Grid>
                  <Grid size={5}><TextField fullWidth required label='ชื่อ-นามสกุล (TH)' value={d.nameTh} onChange={e => updateDir(i, { nameTh: e.target.value })} /></Grid>
                  <Grid size={2}>
                    <FormControl fullWidth><InputLabel>Role</InputLabel>
                      <Select value={d.role} label='Role' onChange={e => updateDir(i, { role: e.target.value as any })}>
                        <MenuItem value='director'>Director</MenuItem>
                        <MenuItem value='chairman'>Chairman</MenuItem>
                      </Select>
                    </FormControl>
                  </Grid>
                  <Grid size={6}><TextField fullWidth required label='Email' type='email' value={d.email} onChange={e => updateDir(i, { email: e.target.value })} /></Grid>
                  <Grid size={6}><TextField fullWidth label='LINE ID' value={d.lineId ?? ''} onChange={e => updateDir(i, { lineId: e.target.value })} /></Grid>
                </Grid>
              </Card>
            ))}
            <Button startIcon={<i className='ri-add-line' />} variant='outlined' onClick={() => setDirectors(p => [...p, emptyDir()])}>Add Director</Button>
          </Box>
        )}

        {/* Step 2: Shareholders */}
        {step === 2 && (
          <Box>
            <Typography variant='body2' color='text.secondary' mb={2}>Per shareholder: Invitation Receipt + Proxy Form + Voting Sheet.</Typography>
            {shareholders.map((s, i) => (
              <Card key={i} variant='outlined' sx={{ mb: 2, p: 1 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='subtitle2'>Shareholder {i + 1}</Typography>
                  {shareholders.length > 1 && <IconButton size='small' color='error' onClick={() => setShareholders(p => p.filter((_, j) => j !== i))}><i className='ri-delete-bin-line' /></IconButton>}
                </Box>
                <Grid container spacing={2}>
                  <Grid size={4}><TextField fullWidth required label='Entity Name (EN)' value={s.entityNameEn} onChange={e => updateSh(i, { entityNameEn: e.target.value })} /></Grid>
                  <Grid size={4}><TextField fullWidth required label='ชื่อผู้ถือหุ้น (TH)' value={s.entityNameTh} onChange={e => updateSh(i, { entityNameTh: e.target.value })} /></Grid>
                  <Grid size={4}><TextField fullWidth required label='Share Count' type='number' value={s.shareCount || ''} onChange={e => updateSh(i, { shareCount: parseInt(e.target.value) || 0 })} /></Grid>
                  <Grid size={5}><TextField fullWidth required label='Contact Email' type='email' value={s.contactEmail} onChange={e => updateSh(i, { contactEmail: e.target.value })} /></Grid>
                  <Grid size={4}><TextField fullWidth label='LINE ID' value={s.lineId ?? ''} onChange={e => updateSh(i, { lineId: e.target.value })} /></Grid>
                  <Grid size={3}>
                    <FormControl fullWidth><InputLabel>Proxy to</InputLabel>
                      <Select value={s.proxyToUid ?? ''} label='Proxy to' onChange={e => updateSh(i, { proxyToUid: e.target.value || undefined })}>
                        <MenuItem value=''>(Attends in person)</MenuItem>
                        {shareholders.filter((_, j) => j !== i).map((x, j) => <MenuItem key={j} value={x.uid ?? j.toString()}>{x.entityNameEn || `Shareholder ${j + 1}`}</MenuItem>)}
                      </Select>
                    </FormControl>
                  </Grid>
                </Grid>
              </Card>
            ))}
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Button startIcon={<i className='ri-add-line' />} variant='outlined' onClick={() => setShareholders(p => [...p, emptySh()])}>Add Shareholder</Button>
              <Typography variant='caption' color='text.secondary'>
                Total: {shareholders.reduce((s, x) => s + (x.shareCount || 0), 0).toLocaleString('en')} shares
              </Typography>
            </Box>
          </Box>
        )}

        {/* Step 3: Meetings */}
        {step === 3 && (
          <Grid container spacing={3}>
            <Grid size={12}>
              <Typography variant='subtitle1' fontWeight={700}>Board of Directors Meeting (BOD)</Typography>
              <Typography variant='body2' color='text.secondary'>Resolves to call the AGM</Typography>
            </Grid>
            <Grid size={4}><TextField fullWidth label='BOD Date' type='date' value={bodDate} onChange={e => setBodDate(e.target.value)} InputLabelProps={{ shrink: true }} /></Grid>
            <Grid size={2}><TextField fullWidth label='Time' type='time' value={bodTime} onChange={e => setBodTime(e.target.value)} InputLabelProps={{ shrink: true }} /></Grid>
            <Grid size={6}><TextField fullWidth label='Venue' value={bodVenue} onChange={e => setBodVenue(e.target.value)} placeholder={addrEn || 'Company address'} /></Grid>

            <Grid size={12}><Divider /></Grid>

            <Grid size={12}>
              <Typography variant='subtitle1' fontWeight={700}>Annual General Meeting (AGM)</Typography>
              {agmDeadline && <Typography variant='body2' color='text.secondary'>Must be held by {agmDeadline} (4 months from year-end)</Typography>}
            </Grid>
            <Grid size={4}><TextField fullWidth label='AGM Date' type='date' value={agmDate} onChange={e => setAgmDate(e.target.value)} InputLabelProps={{ shrink: true }} /></Grid>
            <Grid size={2}><TextField fullWidth label='Time' type='time' value={agmTime} onChange={e => setAgmTime(e.target.value)} InputLabelProps={{ shrink: true }} /></Grid>
            <Grid size={6}><TextField fullWidth label='Venue' value={agmVenue} onChange={e => setAgmVenue(e.target.value)} placeholder={addrEn || 'Company address'} /></Grid>
          </Grid>
        )}

        {/* Step 4: Auditor & Fees */}
        {step === 4 && (
          <Grid container spacing={2}>
            <Grid size={6}><TextField fullWidth label='Auditor Name' value={auditorName} onChange={e => setAuditorName(e.target.value)} /></Grid>
            <Grid size={6}><TextField fullWidth label='Auditor Fee (THB)' type='number' value={auditorFee} onChange={e => setAuditorFee(e.target.value)} /></Grid>
            <Grid size={12}><Divider /></Grid>
            <Grid size={6}><TextField fullWidth label='GPS Legal Fee (THB)' type='number' value={feeThb} onChange={e => setFeeThb(e.target.value)} helperText='Default: 15,000' /></Grid>
            <Grid size={6}>
              <FormControlLabel control={<Switch checked={vatIncluded} onChange={e => setVatIncluded(e.target.checked)} />} label='Include VAT (7%)' />
              {vatIncluded && <Typography variant='caption'>Total: THB {((parseFloat(feeThb) || 0) * 1.07).toLocaleString('en', { minimumFractionDigits: 2 })}</Typography>}
            </Grid>
          </Grid>
        )}

        {/* Step 5: Review */}
        {step === 5 && (
          <Grid container spacing={2}>
            <Grid size={12}>
              <Alert severity='info'>
                Clicking Create will save the matter and generate <strong>{(3 + directors.length) + (3 + shareholders.length * 3)} bilingual EN/TH PDF documents</strong> automatically.
                Document generation takes 15–30 seconds (one browser, all docs rendered in sequence).
              </Alert>
            </Grid>
            <Grid size={6}>
              <Typography variant='caption' color='text.secondary' display='block'>Company</Typography>
              <Typography variant='body2' fontWeight={600}>{companyNameEn}</Typography>
              <Typography variant='body2'>{companyNameTh}</Typography>
              <Typography variant='body2' color='text.secondary'>FY {fiscalYear} · Year-end: {yearEndDate}</Typography>
            </Grid>
            <Grid size={6}>
              <Typography variant='caption' color='text.secondary' display='block'>Meetings</Typography>
              <Typography variant='body2'>BOD: {bodDate || '—'} {bodTime}</Typography>
              <Typography variant='body2'>AGM: {agmDate || '—'} {agmTime}</Typography>
            </Grid>
            <Grid size={6}>
              <Typography variant='caption' color='text.secondary' display='block'>Directors ({directors.length})</Typography>
              {directors.map((d, i) => <Typography key={i} variant='body2'>{d.nameEn} ({d.role})</Typography>)}
            </Grid>
            <Grid size={6}>
              <Typography variant='caption' color='text.secondary' display='block'>Shareholders ({shareholders.length})</Typography>
              {shareholders.map((s, i) => <Typography key={i} variant='body2'>{s.entityNameEn} — {s.shareCount.toLocaleString('en')} shares</Typography>)}
            </Grid>
          </Grid>
        )}

        <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 3 }}>
          <Button onClick={onClose} color='inherit'>Cancel</Button>
          <Box sx={{ display: 'flex', gap: 1 }}>
            {step > 0 && <Button onClick={() => { setErr(''); setStep(s => s - 1) }}>Back</Button>}
            {step < STEPS.length - 1 && <Button variant='contained' onClick={handleNext}>Next</Button>}
            {step === STEPS.length - 1 && (
              <Button variant='contained' color='success' onClick={handleSubmit} disabled={saving}
                startIcon={saving ? <CircularProgress size={16} /> : <i className='ri-magic-line' />}>
                {saving ? 'Creating & Generating Docs…' : 'Create & Generate All Documents'}
              </Button>
            )}
          </Box>
        </Box>
      </DialogContent>
    </Dialog>
  )
}

// ─── Matter detail panel ─────────────────────────────────────────────────────

function MatterPanel({ matterId, onClose }: { matterId: string; onClose: () => void }) {
  const [matter, setMatter]     = useState<MatterDetail | null>(null)
  const [deadlines, setDeadlines] = useState<DeadlineItem[]>([])
  const [generating, setGenerating] = useState(false)
  const [err, setErr] = useState('')

  const load = () => {
    fetch(`/api/annual-compliance/${matterId}`).then(r => r.json()).then(setMatter)
    fetch(`/api/annual-compliance/${matterId}/deadlines`).then(r => r.json()).then(d => setDeadlines(Array.isArray(d) ? d : d.items ?? []))
  }

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

  const generateDocs = async () => {
    setGenerating(true); setErr('')
    try {
      const r = await fetch(`/api/annual-compliance/${matterId}/generate-documents`, { method: 'POST' })
      if (!r.ok) throw new Error('Generation failed')
      load()
    } catch (e: any) { setErr(e.message) } finally { setGenerating(false) }
  }

  const advanceStatus = async (docUid: string, current: string) => {
    const next: Record<string, string> = { draft: 'sent', sent: 'signed', signed: 'returned' }
    if (!next[current]) return
    await fetch(`/api/annual-compliance/${matterId}/documents/${docUid}/status`, {
      method: 'PATCH', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status: next[current] }),
    })
    load()
  }

  if (!matter) return <Box sx={{ p: 3, textAlign: 'center' }}><CircularProgress /></Box>

  const ac = matter.annualCompliance
  const docs = ac?.documents ?? []
  const signed = docs.filter(d => d.status === 'signed' || d.status === 'returned').length
  const pct = docs.length > 0 ? Math.round((signed / docs.length) * 100) : 0
  const now = Date.now()

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
        <Box>
          <Typography variant='h6' fontWeight={700}>{ac?.companyNameEn}</Typography>
          <Typography variant='body2' color='text.secondary'>{ac?.companyNameTh} · FY {ac?.fiscalYear}</Typography>
          <Typography variant='caption' color='text.secondary'>{matter.matterNumber}</Typography>
        </Box>
        <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
          {docs.length === 0 && (
            <Button variant='contained' color='success' size='small' onClick={generateDocs} disabled={generating}
              startIcon={generating ? <CircularProgress size={14} /> : <i className='ri-magic-line' />}>
              {generating ? 'Generating…' : 'Generate All Documents'}
            </Button>
          )}
          {docs.length > 0 && (
            <Button size='small' variant='outlined' onClick={generateDocs} disabled={generating}
              startIcon={generating ? <CircularProgress size={14} /> : <i className='ri-refresh-line' />}>
              Regenerate
            </Button>
          )}
          <IconButton size='small' onClick={onClose}><i className='ri-close-line' /></IconButton>
        </Box>
      </Box>

      {err && <Alert severity='error' sx={{ mb: 2 }}>{err}</Alert>}

      <Grid container spacing={2}>
        {/* Deadlines */}
        <Grid size={12}>
          <Typography variant='subtitle2' fontWeight={700} mb={1}>Statutory Deadlines</Typography>
          {deadlines.length === 0 && <Typography variant='body2' color='text.secondary'>No deadlines generated yet.</Typography>}
          <Grid container spacing={1}>
            {deadlines.map(d => {
              const daysLeft = Math.ceil((new Date(d.dueDate).getTime() - now) / 86400000)
              const color = URGENCY(daysLeft, d.status === 'completed')
              return (
                <Grid size={{ xs: 12, sm: 6 }} key={d._id}>
                  <Box sx={{ p: 1.5, borderRadius: 1, border: '1px solid', borderColor: 'divider', bgcolor: 'background.paper' }}>
                    <Typography variant='caption' fontWeight={600} display='block' noWrap>{d.name}</Typography>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 0.5 }}>
                      <Typography variant='caption' color='text.secondary'>
                        {new Date(d.dueDate).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}
                      </Typography>
                      <Chip
                        label={d.status === 'completed' ? 'Done' : daysLeft < 0 ? `${Math.abs(daysLeft)}d overdue` : `${daysLeft}d`}
                        color={color} size='small'
                      />
                    </Box>
                  </Box>
                </Grid>
              )
            })}
          </Grid>
        </Grid>

        {/* Document list */}
        {docs.length > 0 && (
          <Grid size={12}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
              <Typography variant='subtitle2' fontWeight={700}>Documents ({signed}/{docs.length} signed/returned)</Typography>
              <LinearProgress variant='determinate' value={pct} color={pct === 100 ? 'success' : 'primary'}
                sx={{ width: 160, height: 6, borderRadius: 3 }} />
            </Box>
            <Table size='small'>
              <TableHead>
                <TableRow>
                  <TableCell>Document</TableCell>
                  <TableCell>Recipient</TableCell>
                  <TableCell>Status</TableCell>
                  <TableCell>Actions</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {docs.map(doc => (
                  <TableRow key={doc.uid} hover>
                    <TableCell sx={{ maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      <Tooltip title={doc.label}><span>{doc.label}</span></Tooltip>
                    </TableCell>
                    <TableCell sx={{ color: 'text.secondary', fontSize: '0.8rem' }}>
                      {doc.recipientNameEn ?? 'All'}
                    </TableCell>
                    <TableCell>
                      <Chip label={doc.status} color={STATUS_COLOR[doc.status] ?? 'default'} size='small' />
                    </TableCell>
                    <TableCell>
                      {doc.status !== 'returned' && (
                        <Tooltip title={`Mark as ${({ draft: 'Sent', sent: 'Signed', signed: 'Returned' } as any)[doc.status] ?? ''}`}>
                          <IconButton size='small' color='primary' onClick={() => advanceStatus(doc.uid, doc.status)}>
                            <i className='ri-arrow-right-circle-line' style={{ fontSize: '1rem' }} />
                          </IconButton>
                        </Tooltip>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Grid>
        )}
      </Grid>
    </Box>
  )
}

// ─── Main view ────────────────────────────────────────────────────────────────

export default function AnnualComplianceView({ lang: _lang }: { lang: string }) {
  const [matters, setMatters]       = useState<DashboardMatter[]>([])
  const [loading, setLoading]       = useState(true)
  const [wizardOpen, setWizardOpen] = useState(false)
  const [selectedId, setSelectedId] = useState<string | null>(null)

  const loadDashboard = () => {
    setLoading(true)
    fetch('/api/annual-compliance/dashboard')
      .then(r => r.json())
      .then(d => setMatters(Array.isArray(d) ? d : []))
      .finally(() => setLoading(false))
  }

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

  const now = Date.now()

  return (
    <Box>
      {/* Header */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Box>
          <Typography variant='h5' fontWeight={700}>Annual Compliance</Typography>
          <Typography variant='body2' color='text.secondary'>BOD + AGM cycle management — Thai limited companies</Typography>
        </Box>
        <Button variant='contained' startIcon={<i className='ri-add-line' />} onClick={() => setWizardOpen(true)}>
          New Matter
        </Button>
      </Box>

      <Grid container spacing={3}>
        {/* Matter list */}
        <Grid size={{ xs: 12, md: selectedId ? 5 : 12 }}>
          {loading && <Box sx={{ textAlign: 'center', py: 6 }}><CircularProgress /></Box>}

          {!loading && matters.length === 0 && (
            <Card>
              <CardContent sx={{ textAlign: 'center', py: 6 }}>
                <i className='ri-building-line' style={{ fontSize: 48, opacity: 0.2 }} />
                <Typography variant='h6' color='text.secondary' mt={2}>No annual compliance matters</Typography>
                <Button variant='contained' sx={{ mt: 2 }} onClick={() => setWizardOpen(true)}>Create First Matter</Button>
              </CardContent>
            </Card>
          )}

          {!loading && matters.length > 0 && (
            <Card>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>Company</TableCell>
                    <TableCell>FY</TableCell>
                    <TableCell>AGM</TableCell>
                    <TableCell>Documents</TableCell>
                    <TableCell>Next Deadline</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {matters.map(m => {
                    const { total, signed } = m.documentProgress
                    const pct = total > 0 ? Math.round((signed / total) * 100) : 0

                    return (
                      <TableRow key={m.matterId} hover sx={{ cursor: 'pointer', bgcolor: selectedId === m.matterId ? 'action.selected' : 'inherit' }}
                        onClick={() => setSelectedId(s => s === m.matterId ? null : m.matterId)}>
                        <TableCell>
                          <Typography variant='body2' fontWeight={600}>{m.companyNameEn ?? '—'}</Typography>
                          <Typography variant='caption' color='text.secondary'>{m.matterNumber}</Typography>
                        </TableCell>
                        <TableCell>{m.fiscalYear}</TableCell>
                        <TableCell sx={{ fontSize: '0.8rem' }}>
                          {m.agmDate ? new Date(m.agmDate).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }) : '—'}
                        </TableCell>
                        <TableCell>
                          {total > 0 ? (
                            <Box sx={{ minWidth: 80 }}>
                              <Typography variant='caption'>{signed}/{total}</Typography>
                              <LinearProgress variant='determinate' value={pct} color={pct === 100 ? 'success' : 'primary'}
                                sx={{ height: 4, borderRadius: 2, mt: 0.5 }} />
                            </Box>
                          ) : <Typography variant='caption' color='text.secondary'>Not generated</Typography>}
                        </TableCell>
                        <TableCell>
                          {m.yearEndDate ? (() => {
                            const agmDl = new Date(m.yearEndDate)
                            agmDl.setMonth(agmDl.getMonth() + 4)
                            const days = Math.ceil((agmDl.getTime() - now) / 86400000)
                            return <Chip label={days < 0 ? `${Math.abs(days)}d over` : `${days}d`}
                              color={URGENCY(days, false)} size='small' />
                          })() : '—'}
                        </TableCell>
                      </TableRow>
                    )
                  })}
                </TableBody>
              </Table>
            </Card>
          )}
        </Grid>

        {/* Detail panel */}
        {selectedId && (
          <Grid size={{ xs: 12, md: 7 }}>
            <Card>
              <MatterPanel matterId={selectedId} onClose={() => setSelectedId(null)} />
            </Card>
          </Grid>
        )}
      </Grid>

      <WizardDialog
        open={wizardOpen}
        onClose={() => setWizardOpen(false)}
        onCreated={(id) => { setWizardOpen(false); loadDashboard(); setSelectedId(id) }}
      />
    </Box>
  )
}
