'use client'
import { useState, useRef, useEffect, useCallback } 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 CardActions from '@mui/material/CardActions'
import Chip from '@mui/material/Chip'
import Dialog from '@mui/material/Dialog'
import DialogActions from '@mui/material/DialogActions'
import DialogContent from '@mui/material/DialogContent'
import DialogTitle from '@mui/material/DialogTitle'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import TextField from '@mui/material/TextField'
import Tooltip from '@mui/material/Tooltip'
import Typography from '@mui/material/Typography'
import Alert from '@mui/material/Alert'
import Divider from '@mui/material/Divider'
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 type { ClientFolder, FolderAgency, ComplianceEvent, AgencyType, EventType, EventStatus } from './types'

// ─── Constants ────────────────────────────────────────────────────────────────

const AGENCY_TYPES: { value: AgencyType; label: string }[] = [
  { value: 'consulate',        label: 'Consulate' },
  { value: 'embassy',          label: 'Embassy' },
  { value: 'boi',              label: 'BOI' },
  { value: 'immigration_office', label: 'Immigration Office' },
  { value: 'ministry',         label: 'Ministry' },
  { value: 'regulatory',       label: 'Regulatory Body' },
  { value: 'court',            label: 'Court' },
  { value: 'municipality',     label: 'Municipality' },
  { value: 'customs',          label: 'Customs' },
  { value: 'tax',              label: 'Tax Authority' },
  { value: 'other',            label: 'Other' },
]

const EVENT_TYPES: { value: EventType; label: string }[] = [
  { value: 'submission',  label: 'Document Submission' },
  { value: 'appointment', label: 'Appointment' },
  { value: 'deadline',    label: 'Deadline' },
  { value: 'renewal',     label: 'Renewal' },
  { value: 'approval',    label: 'Approval' },
  { value: 'rejection',   label: 'Rejection' },
  { value: 'inspection',  label: 'Inspection' },
  { value: 'payment',     label: 'Payment' },
  { value: 'hearing',     label: 'Hearing' },
  { value: 'other',       label: 'Other' },
]

const EVENT_STATUSES: { value: EventStatus; label: string; color: string }[] = [
  { value: 'upcoming',    label: 'Upcoming',    color: '#4A90D9' },
  { value: 'in_progress', label: 'In Progress', color: '#F39C12' },
  { value: 'completed',   label: 'Completed',   color: '#2ECC71' },
  { value: 'overdue',     label: 'Overdue',     color: '#E8533A' },
  { value: 'cancelled',   label: 'Cancelled',   color: '#95A5A6' },
]

const AGENCY_COLORS = ['#4A90D9', '#7B68EE', '#E8533A', '#2ECC71', '#F39C12', '#0D9394', '#E91E63', '#FF9800']

const statusColor = (s: string) => EVENT_STATUSES.find(e => e.value === s)?.color ?? '#94A3B8'
const agencyTypeLabel = (t: string) => AGENCY_TYPES.find(a => a.value === t)?.label ?? t

// ─── Fishbone SVG ─────────────────────────────────────────────────────────────

interface Selected { ev: ComplianceEvent; svgX: number; svgY: number; above: boolean }

function FishboneChart({ agencies, events, onEdit, highlightedId, onHighlight }: {
  agencies: FolderAgency[]
  events: ComplianceEvent[]
  onEdit: (ev: ComplianceEvent) => void
  highlightedId?: string | null
  onHighlight?: (id: string | null) => void
}) {
  const containerRef = useRef<HTMLDivElement>(null)
  const svgRef       = useRef<SVGSVGElement>(null)
  const [width, setWidth] = useState(760)

  // Zoom / pan
  const [zoom, setZoom]   = useState(1)
  const [pan, setPan]     = useState({ x: 0, y: 0 })
  const isDragging        = useRef(false)
  const dragOrigin        = useRef({ x: 0, y: 0 })
  const hasDragged        = useRef(false)

  // Selected event (inline callout)
  const [selected, setSelected] = useState<Selected | null>(null)

  useEffect(() => {
    const el = containerRef.current
    if (!el) return
    const ro = new ResizeObserver(entries => setWidth(entries[0].contentRect.width))
    ro.observe(el)
    return () => ro.disconnect()
  }, [])

  // Prevent page scroll while wheeling over chart
  useEffect(() => {
    const el = svgRef.current
    if (!el) return
    const handler = (e: WheelEvent) => e.preventDefault()
    el.addEventListener('wheel', handler, { passive: false })
    return () => el.removeEventListener('wheel', handler)
  }, [])

  const LABEL_W = 170
  const MARGIN  = 30
  const RIB_GAP = 90
  const ribX0   = 4
  const spineX0 = LABEL_W
  const spineX1 = width - MARGIN

  const maxRibs = Math.ceil(agencies.length / 2)
  const H = Math.max(320, (maxRibs + 1) * RIB_GAP * 2 + 80)
  const spineY = H / 2

  const now = Date.now()
  const dateTimes = events.map(e => new Date(e.date).getTime()).filter(Boolean)
  const minTime = Math.min(...(dateTimes.length ? dateTimes : [now]), now) - 45 * 86400000
  const maxTime = Math.max(...(dateTimes.length ? dateTimes : [now]), now) + 75 * 86400000

  const timeToX = useCallback((d: string | number) => {
    const t = typeof d === 'string' ? new Date(d).getTime() : d
    return spineX0 + ((t - minTime) / (maxTime - minTime)) * (spineX1 - spineX0)
  }, [spineX0, spineX1, minTime, maxTime])

  const ticks: { x: number; label: string }[] = []
  const td = new Date(minTime); td.setDate(1); td.setHours(0, 0, 0, 0)
  while (td.getTime() <= maxTime) {
    const x = timeToX(td.getTime())
    if (x >= spineX0 + 20 && x <= spineX1 - 20)
      ticks.push({ x, label: td.toLocaleDateString('en', { month: 'short', year: '2-digit' }) })
    td.setMonth(td.getMonth() + 1)
  }

  type RibInfo = { agency: FolderAgency; ribY: number; color: string }
  const ribs: RibInfo[] = agencies.map((agency, i) => {
    const rank = Math.floor(i / 2) + 1
    const side = i % 2 === 0 ? -1 : 1
    return { agency, ribY: spineY + side * rank * RIB_GAP, color: AGENCY_COLORS[i % AGENCY_COLORS.length] }
  })

  const pointOnRib = (ribY: number, x: number) => {
    const t = (x - ribX0) / (spineX1 - ribX0)
    return { x, y: ribY + t * (spineY - ribY) }
  }

  const nowX = timeToX(now)

  // ── Zoom/pan handlers ──────────────────────────────────────────────────────
  const handleWheel = (e: React.WheelEvent) => {
    const delta = -e.deltaY / 600
    const newZoom = Math.max(0.35, Math.min(5, zoom * (1 + delta)))
    const rect = svgRef.current!.getBoundingClientRect()
    const cx = e.clientX - rect.left
    const cy = e.clientY - rect.top
    const svgPx = (cx - pan.x) / zoom
    const svgPy = (cy - pan.y) / zoom
    setPan({ x: cx - svgPx * newZoom, y: cy - svgPy * newZoom })
    setZoom(newZoom)
  }

  const handleMouseDown = (e: React.MouseEvent) => {
    if (e.button !== 0) return
    isDragging.current = true
    hasDragged.current = false
    dragOrigin.current = { x: e.clientX - pan.x, y: e.clientY - pan.y }
  }

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isDragging.current) return
    const dx = e.clientX - dragOrigin.current.x
    const dy = e.clientY - dragOrigin.current.y
    if (Math.abs(dx - pan.x) > 3 || Math.abs(dy - pan.y) > 3) hasDragged.current = true
    setPan({ x: dx, y: dy })
  }

  const handleMouseUp = () => { isDragging.current = false }

  const handleReset = () => { setZoom(1); setPan({ x: 0, y: 0 }); setSelected(null) }

  // ── Callout position (screen coords from SVG coords) ──────────────────────
  const calloutPos = selected ? {
    left: selected.svgX * zoom + pan.x,
    top:  selected.svgY * zoom + pan.y,
  } : null

  if (agencies.length === 0) {
    return (
      <Box sx={{ textAlign: 'center', py: 6, color: 'text.disabled' }}>
        <i className='ri-organization-chart' style={{ fontSize: '2.5rem' }} />
        <Typography variant='body2' sx={{ mt: 1 }}>Add agencies above to see the compliance timeline</Typography>
      </Box>
    )
  }

  return (
    <Box ref={containerRef} sx={{ width: '100%', position: 'relative', overflow: 'hidden' }}>

      {/* ── Zoom controls ── */}
      <Box sx={{ position: 'absolute', top: 8, right: 8, zIndex: 10, display: 'flex', gap: 0.5, bgcolor: 'background.paper', border: '1px solid', borderColor: 'divider', borderRadius: 1.5, p: 0.25 }}>
        <Tooltip title='Zoom in'><IconButton size='small' onClick={() => setZoom(z => Math.min(5, z * 1.3))} sx={{ fontSize: '0.9rem' }}><i className='ri-zoom-in-line' /></IconButton></Tooltip>
        <Tooltip title='Zoom out'><IconButton size='small' onClick={() => setZoom(z => Math.max(0.35, z / 1.3))} sx={{ fontSize: '0.9rem' }}><i className='ri-zoom-out-line' /></IconButton></Tooltip>
        <Tooltip title='Reset view'><IconButton size='small' onClick={handleReset} sx={{ fontSize: '0.9rem' }}><i className='ri-fullscreen-exit-line' /></IconButton></Tooltip>
        <Typography variant='caption' sx={{ px: 0.75, alignSelf: 'center', color: 'text.disabled', minWidth: 32, textAlign: 'center' }}>{Math.round(zoom * 100)}%</Typography>
      </Box>

      <svg
        ref={svgRef}
        width={width} height={H}
        style={{ display: 'block', userSelect: 'none', cursor: isDragging.current ? 'grabbing' : 'grab' }}
        onWheel={handleWheel}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        onMouseLeave={handleMouseUp}
        onClick={() => { if (!hasDragged.current) setSelected(null) }}
      >
        <g transform={`translate(${pan.x},${pan.y}) scale(${zoom})`}>
          {/* ── Spine ── */}
          <line x1={spineX0} y1={spineY} x2={spineX1 - 8} y2={spineY} stroke='#94A3B8' strokeWidth={2.5} />
          <polygon points={`${spineX1},${spineY} ${spineX1-14},${spineY-6} ${spineX1-14},${spineY+6}`} fill='#94A3B8' />
          <text x={spineX1 - 16} y={spineY - 10} textAnchor='end' fontSize={10} fontWeight='600' fill='#94A3B8'>TIMELINE</text>

          {/* ── Month ticks ── */}
          {ticks.map((tk, i) => (
            <g key={i}>
              <line x1={tk.x} y1={spineY - 5} x2={tk.x} y2={spineY + 5} stroke='#CBD5E1' strokeWidth={1} />
              <text x={tk.x} y={spineY + 16} textAnchor='middle' fontSize={9} fill='#94A3B8'>{tk.label}</text>
            </g>
          ))}

          {/* ── Today line ── */}
          {nowX >= spineX0 && nowX <= spineX1 && (
            <g>
              <line x1={nowX} y1={spineY - RIB_GAP * 0.6} x2={nowX} y2={spineY + RIB_GAP * 0.6}
                stroke='#0D9394' strokeWidth={1.5} strokeDasharray='5,3' />
              <text x={nowX} y={spineY - RIB_GAP * 0.6 - 5} textAnchor='middle' fontSize={9} fill='#0D9394' fontWeight='600'>TODAY</text>
            </g>
          )}

          {/* ── Ribs + events ── */}
          {ribs.map(({ agency, ribY, color }) => {
            const agEvents = events.filter(e => e.agencyId === agency.id)
              .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
            return (
              <g key={agency.id}>
                <line x1={ribX0} y1={ribY} x2={spineX1} y2={spineY} stroke={color} strokeWidth={1.5} opacity={0.5} />
                <text x={ribX0 + 2} y={ribY + (ribY < spineY ? -6 : 14)} textAnchor='start' fontSize={11} fontWeight='700' fill={color}>{agency.name}</text>
                <text x={ribX0 + 2} y={ribY + (ribY < spineY ? 6 : 26)} textAnchor='start' fontSize={9} fill={color} opacity={0.7}>{agencyTypeLabel(agency.agencyType)}</text>

                {agEvents.map(ev => {
                  const xDate = timeToX(ev.date)
                  if (xDate < spineX0 + 2 || xDate > spineX1 - 10) return null
                  const pt = pointOnRib(ribY, xDate)
                  const sc = statusColor(ev.status)
                  const isSelected    = selected?.ev.id === ev.id
                  const isHighlighted = highlightedId === ev.id
                  const labelY = ribY < spineY ? pt.y - 14 : pt.y + 20
                  return (
                    <g key={ev.id}
                      style={{ cursor: 'pointer' }}
                      onClick={e => {
                        e.stopPropagation()
                        if (hasDragged.current) return
                        const next = isSelected ? null : { ev, svgX: pt.x, svgY: pt.y, above: ribY < spineY }
                        setSelected(next)
                        onHighlight?.(next ? ev.id : null)
                      }}>
                      <line x1={pt.x} y1={pt.y} x2={pt.x} y2={spineY} stroke={sc} strokeWidth={1} strokeDasharray='3,2' opacity={0.45} />
                      {/* Outer glow ring when selected or highlighted from table */}
                      {(isSelected || isHighlighted) && <circle cx={pt.x} cy={pt.y} r={14} fill={sc} opacity={0.18} />}
                      {(isSelected || isHighlighted) && <circle cx={pt.x} cy={pt.y} r={11} fill='none' stroke={sc} strokeWidth={2} opacity={0.55} />}
                      <circle cx={pt.x} cy={pt.y} r={(isSelected || isHighlighted) ? 9 : 7} fill={sc} stroke='white' strokeWidth={2} />
                      <text x={pt.x} y={labelY} textAnchor='middle' fontSize={9} fill={color} opacity={0.85}
                        style={{ fontWeight: isSelected ? 700 : 400 }}>
                        {ev.title.length > 16 ? ev.title.slice(0, 15) + '…' : ev.title}
                      </text>
                    </g>
                  )
                })}

                {agEvents.length === 0 && (
                  <text x={(ribX0 + spineX1) / 2} y={ribY + (ribY < spineY ? -8 : 18)}
                    textAnchor='middle' fontSize={9} fill={color} opacity={0.4}>no events</text>
                )}
              </g>
            )
          })}
        </g>
      </svg>

      {/* ── Inline callout ── */}
      {selected && calloutPos && (
        <Box
          onClick={e => e.stopPropagation()}
          sx={{
            position: 'absolute',
            left: calloutPos.left,
            top: selected.above ? calloutPos.top - 12 : calloutPos.top + 12,
            transform: selected.above ? 'translate(-50%, -100%)' : 'translate(-50%, 8px)',
            zIndex: 20,
            width: 220,
            bgcolor: 'background.paper',
            border: '1px solid',
            borderColor: statusColor(selected.ev.status) + '88',
            borderRadius: 2,
            boxShadow: `0 4px 20px rgba(0,0,0,0.18)`,
            p: 1.5,
            pointerEvents: 'auto',
          }}
        >
          {/* Arrow pointer */}
          <Box sx={{
            position: 'absolute',
            left: '50%', transform: 'translateX(-50%)',
            ...(selected.above
              ? { bottom: -7, borderLeft: '7px solid transparent', borderRight: '7px solid transparent', borderTop: `7px solid ${statusColor(selected.ev.status)}88` }
              : { top: -7, borderLeft: '7px solid transparent', borderRight: '7px solid transparent', borderBottom: `7px solid ${statusColor(selected.ev.status)}88` }),
            width: 0, height: 0,
          }} />

          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 0.75 }}>
            <Typography sx={{ fontWeight: 700, fontSize: 12, lineHeight: 1.3, pr: 1 }}>{selected.ev.title}</Typography>
            <Box sx={{ display: 'flex', gap: 0.25, flexShrink: 0 }}>
              <Tooltip title='Edit event'>
                <IconButton size='small' onClick={() => { onEdit(selected.ev); setSelected(null) }}
                  sx={{ p: 0.25 }}>
                  <i className='ri-edit-line' style={{ fontSize: '0.8rem' }} />
                </IconButton>
              </Tooltip>
              <IconButton size='small' onClick={() => setSelected(null)} sx={{ p: 0.25 }}>
                <i className='ri-close-line' style={{ fontSize: '0.8rem' }} />
              </IconButton>
            </Box>
          </Box>

          <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', mb: 0.75 }}>
            <Chip label={selected.ev.status.replace('_', ' ')} size='small'
              sx={{ bgcolor: statusColor(selected.ev.status) + '22', color: statusColor(selected.ev.status), fontSize: '0.62rem', height: 18, fontWeight: 700, textTransform: 'capitalize' }} />
            <Chip label={EVENT_TYPES.find(t => t.value === selected.ev.eventType)?.label ?? selected.ev.eventType}
              size='small' variant='outlined' sx={{ fontSize: '0.62rem', height: 18 }} />
          </Box>

          <Typography variant='caption' color='text.secondary' sx={{ display: 'block' }}>
            <i className='ri-calendar-line' style={{ marginRight: 4 }} />
            {new Date(selected.ev.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' })}
          </Typography>
          <Typography variant='caption' color='text.secondary' sx={{ display: 'block' }}>
            <i className='ri-bank-line' style={{ marginRight: 4 }} />{selected.ev.agencyName}
          </Typography>
          {selected.ev.referenceNumber && (
            <Typography variant='caption' color='text.secondary' sx={{ display: 'block' }}>
              <i className='ri-hashtag' style={{ marginRight: 4 }} />Ref: {selected.ev.referenceNumber}
            </Typography>
          )}
          {selected.ev.notes && (
            <Typography variant='caption' sx={{ display: 'block', mt: 0.5, fontStyle: 'italic', color: 'text.secondary' }}>
              {selected.ev.notes}
            </Typography>
          )}
        </Box>
      )}

      {/* ── Legend ── */}
      <Box sx={{ display: 'flex', gap: 2, px: 2, pb: 1.5, pt: 0.5, flexWrap: 'wrap' }}>
        {EVENT_STATUSES.map(s => (
          <Box key={s.value} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <Box sx={{ width: 10, height: 10, borderRadius: '50%', bgcolor: s.color, flexShrink: 0 }} />
            <Typography variant='caption' color='text.secondary'>{s.label}</Typography>
          </Box>
        ))}
        <Typography variant='caption' color='text.disabled' sx={{ ml: 'auto' }}>Scroll to zoom · Drag to pan · Click event for details</Typography>
      </Box>
    </Box>
  )
}

// ─── Agency Dialog ────────────────────────────────────────────────────────────

const emptyAgency = (): Omit<FolderAgency, 'id'> => ({
  name: '', agencyType: 'other', country: '', contactPerson: '',
  phone: '', email: '', website: '', referenceNumber: '', notes: '',
})

const emptyEvent = (agencyId = '', agencyName = ''): Omit<ComplianceEvent, 'id'> => ({
  title: '', agencyId, agencyName, eventType: 'deadline',
  date: new Date().toISOString().slice(0, 10), status: 'upcoming',
  matterId: '', matterTitle: '', referenceNumber: '', notes: '',
})

// ─── Agencies Section (for Parties tab) ───────────────────────────────────────

export function AgenciesSection({ folder, onUpdate }: { folder: ClientFolder; onUpdate: (f: ClientFolder) => void }) {
  const agencies: FolderAgency[] = folder.folderAgencies ?? []
  const events: ComplianceEvent[] = folder.complianceEvents ?? []

  const [agencyDialog, setAgencyDialog] = useState<{ open: boolean; editId: string | null }>({ open: false, editId: null })
  const [agencyDraft, setAgencyDraft] = useState<Omit<FolderAgency, 'id'>>(emptyAgency())
  const [eventDialog, setEventDialog]  = useState<{ open: boolean; editId: string | null; prefillAgencyId?: string; prefillAgencyName?: string }>({ open: false, editId: null })
  const [eventDraft, setEventDraft]    = useState<Omit<ComplianceEvent, 'id'>>(emptyEvent())
  const [saving, setSaving] = useState(false)
  const [err, setErr] = useState<string | null>(null)

  const patch = async (body: Record<string, any>) => {
    const res = await fetch(`/api/clients/${folder._id}`, {
      method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
    })
    if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? 'Save failed')
    onUpdate(await res.json())
  }

  // ── Agency CRUD ──
  const openAddAgency  = () => { setAgencyDraft(emptyAgency()); setErr(null); setAgencyDialog({ open: true, editId: null }) }
  const openEditAgency = (id: string) => {
    const a = agencies.find(a => a.id === id)!
    setAgencyDraft({ name: a.name, agencyType: a.agencyType, country: a.country ?? '', contactPerson: a.contactPerson ?? '',
      phone: a.phone ?? '', email: a.email ?? '', website: a.website ?? '', referenceNumber: a.referenceNumber ?? '', notes: a.notes ?? '' })
    setErr(null); setAgencyDialog({ open: true, editId: id })
  }
  const saveAgency = async () => {
    if (!agencyDraft.name.trim()) { setErr('Agency name is required'); return }
    setSaving(true); setErr(null)
    try {
      const next = agencyDialog.editId
        ? agencies.map(a => a.id === agencyDialog.editId ? { ...agencyDraft, id: agencyDialog.editId } : a)
        : [...agencies, { ...agencyDraft, id: crypto.randomUUID() }]
      await patch({ folderAgencies: next })
      setAgencyDialog({ open: false, editId: null })
    } catch (e: any) { setErr(e.message) } finally { setSaving(false) }
  }
  const deleteAgency = async (id: string) => {
    const next = agencies.filter(a => a.id !== id)
    const evNext = events.filter(e => e.agencyId !== id)
    await patch({ folderAgencies: next, complianceEvents: evNext })
  }

  // ── Event CRUD ──
  const openAddEvent = (agencyId?: string, agencyName?: string) => {
    setEventDraft(emptyEvent(agencyId, agencyName)); setErr(null)
    setEventDialog({ open: true, editId: null, prefillAgencyId: agencyId, prefillAgencyName: agencyName })
  }
  const openEditEvent = (id: string) => {
    const e = events.find(e => e.id === id)!
    setEventDraft({ title: e.title, agencyId: e.agencyId, agencyName: e.agencyName,
      eventType: e.eventType, date: e.date.slice(0, 10), status: e.status,
      matterId: e.matterId ?? '', matterTitle: e.matterTitle ?? '',
      referenceNumber: e.referenceNumber ?? '', notes: e.notes ?? '' })
    setErr(null); setEventDialog({ open: true, editId: id })
  }
  const saveEvent = async () => {
    if (!eventDraft.title.trim()) { setErr('Event title is required'); return }
    if (!eventDraft.agencyId) { setErr('Select an agency'); return }
    if (!eventDraft.date) { setErr('Date is required'); return }
    setSaving(true); setErr(null)
    try {
      const agency = agencies.find(a => a.id === eventDraft.agencyId)
      const withName = { ...eventDraft, agencyName: agency?.name ?? eventDraft.agencyName }
      const next = eventDialog.editId
        ? events.map(e => e.id === eventDialog.editId ? { ...withName, id: eventDialog.editId } : e)
        : [...events, { ...withName, id: crypto.randomUUID() }]
      await patch({ complianceEvents: next })
      setEventDialog({ open: false, editId: null })
    } catch (e: any) { setErr(e.message) } finally { setSaving(false) }
  }
  const deleteEvent = async (id: string) => {
    await patch({ complianceEvents: events.filter(e => e.id !== id) })
  }

  const agEventCount = (agencyId: string) => events.filter(e => e.agencyId === agencyId).length

  return (
    <Box>
      {/* ── Agency cards ── */}
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1.5 }}>
        <Typography variant='subtitle2' sx={{ fontWeight: 700, color: 'text.secondary', textTransform: 'uppercase', fontSize: '0.72rem', letterSpacing: 0.8 }}>
          Agencies & Intermediaries
        </Typography>
        <Button size='small' startIcon={<i className='ri-add-line' />} onClick={openAddAgency} sx={{ fontSize: '0.72rem' }}>
          Add Agency
        </Button>
      </Box>

      {agencies.length === 0 ? (
        <Typography variant='body2' color='text.disabled' sx={{ py: 3, textAlign: 'center' }}>
          No agencies on record — add consulates, BOI, immigration offices, or other intermediaries
        </Typography>
      ) : (
        <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 1.5 }}>
          {agencies.map((ag, i) => (
            <Card key={ag.id} variant='outlined' sx={{ borderColor: AGENCY_COLORS[i % AGENCY_COLORS.length] + '55', borderRadius: 2 }}>
              <CardContent sx={{ pb: '8px !important', pt: 1.5 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 0.5 }}>
                  <Typography variant='body2' sx={{ fontWeight: 700, lineHeight: 1.3, pr: 1 }}>{ag.name}</Typography>
                  <Box sx={{ display: 'flex', gap: 0.5, flexShrink: 0 }}>
                    <Tooltip title='Edit agency'><IconButton size='small' onClick={() => openEditAgency(ag.id)}><i className='ri-edit-line' style={{ fontSize: '0.8rem' }} /></IconButton></Tooltip>
                    <Tooltip title='Delete agency'><IconButton size='small' onClick={() => deleteAgency(ag.id)}><i className='ri-delete-bin-line' style={{ fontSize: '0.8rem', color: '#FF4C51' }} /></IconButton></Tooltip>
                  </Box>
                </Box>
                <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', mb: 1 }}>
                  <Chip label={agencyTypeLabel(ag.agencyType)} size='small'
                    sx={{ bgcolor: AGENCY_COLORS[i % AGENCY_COLORS.length] + '22', color: AGENCY_COLORS[i % AGENCY_COLORS.length], fontSize: '0.62rem', height: 18, fontWeight: 600 }} />
                  {ag.country && <Chip label={ag.country} size='small' sx={{ fontSize: '0.62rem', height: 18 }} />}
                  <Chip label={`${agEventCount(ag.id)} event${agEventCount(ag.id) !== 1 ? 's' : ''}`} size='small' variant='outlined' sx={{ fontSize: '0.62rem', height: 18 }} />
                </Box>
                {ag.contactPerson && (
                  <Typography variant='caption' color='text.secondary' sx={{ display: 'block' }}>
                    <i className='ri-user-line' style={{ marginRight: 4 }} />{ag.contactPerson}
                  </Typography>
                )}
                {ag.referenceNumber && (
                  <Typography variant='caption' color='text.secondary' sx={{ display: 'block' }}>
                    <i className='ri-hashtag' style={{ marginRight: 4 }} />Ref: {ag.referenceNumber}
                  </Typography>
                )}
                {(ag.phone || ag.email) && (
                  <Typography variant='caption' color='text.secondary' sx={{ display: 'block' }}>
                    {[ag.phone, ag.email].filter(Boolean).join(' · ')}
                  </Typography>
                )}
              </CardContent>
              <Divider />
              <CardActions sx={{ px: 1.5, py: 0.75 }}>
                <Button size='small' startIcon={<i className='ri-add-circle-line' />}
                  onClick={() => openAddEvent(ag.id, ag.name)} sx={{ fontSize: '0.7rem' }}>
                  Add Compliance Event
                </Button>
              </CardActions>
            </Card>
          ))}
        </Box>
      )}

      {/* ── Agency dialog ── */}
      <Dialog open={agencyDialog.open} onClose={() => setAgencyDialog({ open: false, editId: null })} maxWidth='sm' fullWidth>
        <DialogTitle>{agencyDialog.editId ? 'Edit Agency' : 'Add Agency'}</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 fullWidth required size='small' label='Agency Name' value={agencyDraft.name}
              onChange={e => setAgencyDraft(d => ({ ...d, name: e.target.value }))} />
            <TextField select fullWidth size='small' label='Type' value={agencyDraft.agencyType}
              onChange={e => setAgencyDraft(d => ({ ...d, agencyType: e.target.value as AgencyType }))}>
              {AGENCY_TYPES.map(t => <MenuItem key={t.value} value={t.value}>{t.label}</MenuItem>)}
            </TextField>
          </Box>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' label='Country' value={agencyDraft.country ?? ''}
              onChange={e => setAgencyDraft(d => ({ ...d, country: e.target.value }))} />
            <TextField fullWidth size='small' label='Contact Person' value={agencyDraft.contactPerson ?? ''}
              onChange={e => setAgencyDraft(d => ({ ...d, contactPerson: e.target.value }))} />
          </Box>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' label='Phone' value={agencyDraft.phone ?? ''}
              onChange={e => setAgencyDraft(d => ({ ...d, phone: e.target.value }))} />
            <TextField fullWidth size='small' label='Email' value={agencyDraft.email ?? ''}
              onChange={e => setAgencyDraft(d => ({ ...d, email: e.target.value }))} />
          </Box>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' label='Website' value={agencyDraft.website ?? ''}
              onChange={e => setAgencyDraft(d => ({ ...d, website: e.target.value }))} />
            <TextField fullWidth size='small' label='Client Reference No.' value={agencyDraft.referenceNumber ?? ''}
              onChange={e => setAgencyDraft(d => ({ ...d, referenceNumber: e.target.value }))}
              placeholder='e.g. TM.7 file no., BOI app no.' />
          </Box>
          <TextField fullWidth size='small' label='Notes' multiline rows={2} value={agencyDraft.notes ?? ''}
            onChange={e => setAgencyDraft(d => ({ ...d, notes: e.target.value }))} />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setAgencyDialog({ open: false, editId: null })} disabled={saving}>Cancel</Button>
          <Button variant='contained' onClick={saveAgency} disabled={saving || !agencyDraft.name.trim()}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            {saving ? 'Saving…' : agencyDialog.editId ? 'Save Changes' : 'Add Agency'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* ── Event dialog ── */}
      <Dialog open={eventDialog.open} onClose={() => setEventDialog({ open: false, editId: null })} maxWidth='sm' fullWidth>
        <DialogTitle>{eventDialog.editId ? 'Edit Compliance Event' : 'Add Compliance Event'}</DialogTitle>
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '12px !important' }}>
          {err && <Alert severity='error'>{err}</Alert>}
          <TextField fullWidth required size='small' label='Event Title' value={eventDraft.title}
            onChange={e => setEventDraft(d => ({ ...d, title: e.target.value }))}
            placeholder='e.g. TM.7 Visa Extension Submission' />
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField select fullWidth size='small' label='Agency' value={eventDraft.agencyId}
              onChange={e => {
                const ag = agencies.find(a => a.id === e.target.value)
                setEventDraft(d => ({ ...d, agencyId: e.target.value, agencyName: ag?.name ?? '' }))
              }}>
              {agencies.map(a => <MenuItem key={a.id} value={a.id}>{a.name}</MenuItem>)}
            </TextField>
            <TextField select fullWidth size='small' label='Event Type' value={eventDraft.eventType}
              onChange={e => setEventDraft(d => ({ ...d, eventType: e.target.value as EventType }))}>
              {EVENT_TYPES.map(t => <MenuItem key={t.value} value={t.value}>{t.label}</MenuItem>)}
            </TextField>
          </Box>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' type='date' label='Date' InputLabelProps={{ shrink: true }} value={eventDraft.date}
              onChange={e => setEventDraft(d => ({ ...d, date: e.target.value }))} />
            <TextField select fullWidth size='small' label='Status' value={eventDraft.status}
              onChange={e => setEventDraft(d => ({ ...d, status: e.target.value as EventStatus }))}>
              {EVENT_STATUSES.map(s => <MenuItem key={s.value} value={s.value}>{s.label}</MenuItem>)}
            </TextField>
          </Box>
          <TextField fullWidth size='small' label='Reference Number' value={eventDraft.referenceNumber ?? ''}
            onChange={e => setEventDraft(d => ({ ...d, referenceNumber: e.target.value }))} />
          <TextField fullWidth size='small' label='Notes' multiline rows={2} value={eventDraft.notes ?? ''}
            onChange={e => setEventDraft(d => ({ ...d, notes: e.target.value }))} />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setEventDialog({ open: false, editId: null })} disabled={saving}>Cancel</Button>
          <Button variant='contained' onClick={saveEvent} disabled={saving || !eventDraft.title.trim()}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            {saving ? 'Saving…' : eventDialog.editId ? 'Save Changes' : 'Add Event'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}

// ─── Compliance Tab ────────────────────────────────────────────────────────────

export function ComplianceTab({ folder, onUpdate }: { folder: ClientFolder; onUpdate: (f: ClientFolder) => void }) {
  const agencies: FolderAgency[] = folder.folderAgencies ?? []
  const events: ComplianceEvent[] = folder.complianceEvents ?? []

  const [eventDialog, setEventDialog] = useState(false)
  const [editId, setEditId] = useState<string | null>(null)
  const [draft, setDraft] = useState<Omit<ComplianceEvent, 'id'>>(emptyEvent())
  const [saving, setSaving] = useState(false)
  const [err, setErr] = useState<string | null>(null)
  const [highlightedId, setHighlightedId] = useState<string | null>(null)
  const tableRef = useRef<HTMLDivElement>(null)

  // When chart highlights an event, scroll the table row into view
  useEffect(() => {
    if (!highlightedId || !tableRef.current) return
    const row = tableRef.current.querySelector<HTMLElement>(`[data-event-id="${highlightedId}"]`)
    row?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
  }, [highlightedId])

  const patch = async (body: Record<string, any>) => {
    const res = await fetch(`/api/clients/${folder._id}`, {
      method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
    })
    if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? 'Save failed')
    onUpdate(await res.json())
  }

  const openAdd = () => { setDraft(emptyEvent()); setEditId(null); setErr(null); setEventDialog(true) }
  const openEdit = (id: string) => {
    const e = events.find(e => e.id === id)!
    setDraft({ title: e.title, agencyId: e.agencyId, agencyName: e.agencyName,
      eventType: e.eventType, date: e.date.slice(0, 10), status: e.status,
      matterId: e.matterId ?? '', matterTitle: e.matterTitle ?? '',
      referenceNumber: e.referenceNumber ?? '', notes: e.notes ?? '' })
    setEditId(id); setErr(null); setEventDialog(true)
  }
  const save = async () => {
    if (!draft.title.trim()) { setErr('Title required'); return }
    if (!draft.agencyId) { setErr('Select an agency'); return }
    setSaving(true); setErr(null)
    try {
      const agency = agencies.find(a => a.id === draft.agencyId)
      const withName = { ...draft, agencyName: agency?.name ?? draft.agencyName }
      const next = editId
        ? events.map(e => e.id === editId ? { ...withName, id: editId } : e)
        : [...events, { ...withName, id: crypto.randomUUID() }]
      await patch({ complianceEvents: next })
      setEventDialog(false)
    } catch (e: any) { setErr(e.message) } finally { setSaving(false) }
  }
  const remove = async (id: string) => patch({ complianceEvents: events.filter(e => e.id !== id) })

  const sorted = [...events].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
  const upcoming = sorted.filter(e => e.status === 'upcoming' || e.status === 'in_progress' || e.status === 'overdue')
  const past = sorted.filter(e => e.status === 'completed' || e.status === 'cancelled')

  if (agencies.length === 0) {
    return (
      <Box sx={{ textAlign: 'center', py: 8, color: 'text.disabled' }}>
        <i className='ri-organization-chart' style={{ fontSize: '3rem' }} />
        <Typography variant='h6' sx={{ mt: 1, fontWeight: 600, color: 'text.secondary' }}>No Agencies Yet</Typography>
        <Typography variant='body2' sx={{ mt: 0.5 }}>Add agencies in the Parties tab first, then return here to track compliance events.</Typography>
      </Box>
    )
  }

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2.5 }}>

      {/* ── Fishbone chart ── */}
      <Box sx={{ bgcolor: 'background.paper', border: '1px solid', borderColor: 'divider', borderRadius: 2, overflow: 'hidden' }}>
        <Box sx={{ px: 2, py: 1.5, borderBottom: '1px solid', borderColor: 'divider', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Typography variant='subtitle2' sx={{ fontWeight: 700 }}>
            <i className='ri-node-tree' style={{ marginRight: 6, color: '#0D9394' }} />
            Compliance Timeline
          </Typography>
          <Button size='small' startIcon={<i className='ri-add-line' />} onClick={openAdd} sx={{ fontSize: '0.72rem' }}>
            Add Event
          </Button>
        </Box>
        <FishboneChart agencies={agencies} events={events} onEdit={ev => openEdit(ev.id)}
          highlightedId={highlightedId} onHighlight={setHighlightedId} />
      </Box>

      {/* ── Upcoming / overdue events ── */}
      {upcoming.length > 0 && (
        <Box ref={tableRef}>
          <Typography variant='subtitle2' sx={{ fontWeight: 700, mb: 1 }}>Upcoming & Active</Typography>
          <Table size='small'>
            <TableHead>
              <TableRow sx={{ bgcolor: 'action.hover' }}>
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>Event</TableCell>
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>Agency</TableCell>
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>Type</TableCell>
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>Date</TableCell>
                <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>Status</TableCell>
                <TableCell width={72} />
              </TableRow>
            </TableHead>
            <TableBody>
              {upcoming.map(ev => (
                <TableRow key={ev.id} hover data-event-id={ev.id}
                  onClick={() => setHighlightedId(ev.id === highlightedId ? null : ev.id)}
                  sx={{ cursor: 'pointer', bgcolor: ev.id === highlightedId ? `${statusColor(ev.status)}18` : undefined,
                    outline: ev.id === highlightedId ? `2px solid ${statusColor(ev.status)}66` : undefined,
                    outlineOffset: '-2px', transition: 'background-color 0.15s' }}>
                  <TableCell>
                    <Typography variant='body2' sx={{ fontWeight: 500 }}>{ev.title}</Typography>
                    {ev.referenceNumber && <Typography variant='caption' color='text.secondary'>Ref: {ev.referenceNumber}</Typography>}
                  </TableCell>
                  <TableCell><Typography variant='caption'>{ev.agencyName}</Typography></TableCell>
                  <TableCell><Typography variant='caption' color='text.secondary'>{EVENT_TYPES.find(t => t.value === ev.eventType)?.label}</Typography></TableCell>
                  <TableCell><Typography variant='body2'>{new Date(ev.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}</Typography></TableCell>
                  <TableCell>
                    <Chip label={ev.status.replace('_', ' ')} size='small'
                      sx={{ bgcolor: statusColor(ev.status) + '22', color: statusColor(ev.status), fontSize: '0.65rem', height: 18, fontWeight: 600, textTransform: 'capitalize' }} />
                  </TableCell>
                  <TableCell align='right' sx={{ pr: 1, whiteSpace: 'nowrap' }}>
                    <Tooltip title='Edit'><IconButton size='small' onClick={() => openEdit(ev.id)}><i className='ri-edit-line' style={{ fontSize: '0.8rem' }} /></IconButton></Tooltip>
                    <Tooltip title='Delete'><IconButton size='small' onClick={() => remove(ev.id)}><i className='ri-delete-bin-line' style={{ fontSize: '0.8rem', color: '#FF4C51' }} /></IconButton></Tooltip>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Box>
      )}

      {/* ── Past events (collapsed by default) ── */}
      {past.length > 0 && (
        <Box>
          <Typography variant='subtitle2' sx={{ fontWeight: 700, mb: 1, color: 'text.secondary' }}>
            Past Events ({past.length})
          </Typography>
          <Table size='small'>
            <TableBody>
              {past.map(ev => (
                <TableRow key={ev.id} hover data-event-id={ev.id}
                  onClick={() => setHighlightedId(ev.id === highlightedId ? null : ev.id)}
                  sx={{ cursor: 'pointer', opacity: ev.id === highlightedId ? 1 : 0.65,
                    bgcolor: ev.id === highlightedId ? `${statusColor(ev.status)}18` : undefined,
                    outline: ev.id === highlightedId ? `2px solid ${statusColor(ev.status)}66` : undefined,
                    outlineOffset: '-2px', transition: 'all 0.15s' }}>
                  <TableCell><Typography variant='body2'>{ev.title}</Typography></TableCell>
                  <TableCell><Typography variant='caption' color='text.secondary'>{ev.agencyName}</Typography></TableCell>
                  <TableCell><Typography variant='caption' color='text.secondary'>{new Date(ev.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}</Typography></TableCell>
                  <TableCell>
                    <Chip label={ev.status} size='small'
                      sx={{ bgcolor: statusColor(ev.status) + '22', color: statusColor(ev.status), fontSize: '0.65rem', height: 18, fontWeight: 600 }} />
                  </TableCell>
                  <TableCell align='right' sx={{ pr: 1, whiteSpace: 'nowrap' }}>
                    <Tooltip title='Edit'><IconButton size='small' onClick={() => openEdit(ev.id)}><i className='ri-edit-line' style={{ fontSize: '0.8rem' }} /></IconButton></Tooltip>
                    <Tooltip title='Delete'><IconButton size='small' onClick={() => remove(ev.id)}><i className='ri-delete-bin-line' style={{ fontSize: '0.8rem', color: '#FF4C51' }} /></IconButton></Tooltip>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Box>
      )}

      {events.length === 0 && (
        <Box sx={{ textAlign: 'center', py: 4, color: 'text.disabled' }}>
          <Typography variant='body2'>No compliance events yet — click "Add Event" to track a deadline, submission, or appointment.</Typography>
        </Box>
      )}

      {/* ── Event dialog ── */}
      <Dialog open={eventDialog} onClose={() => setEventDialog(false)} maxWidth='sm' fullWidth>
        <DialogTitle>{editId ? 'Edit Compliance Event' : 'Add Compliance Event'}</DialogTitle>
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: '12px !important' }}>
          {err && <Alert severity='error'>{err}</Alert>}
          <TextField fullWidth required size='small' label='Event Title' value={draft.title}
            onChange={e => setDraft(d => ({ ...d, title: e.target.value }))} />
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField select fullWidth size='small' label='Agency' value={draft.agencyId}
              onChange={e => {
                const ag = agencies.find(a => a.id === e.target.value)
                setDraft(d => ({ ...d, agencyId: e.target.value, agencyName: ag?.name ?? '' }))
              }}>
              {agencies.map(a => <MenuItem key={a.id} value={a.id}>{a.name}</MenuItem>)}
            </TextField>
            <TextField select fullWidth size='small' label='Event Type' value={draft.eventType}
              onChange={e => setDraft(d => ({ ...d, eventType: e.target.value as EventType }))}>
              {EVENT_TYPES.map(t => <MenuItem key={t.value} value={t.value}>{t.label}</MenuItem>)}
            </TextField>
          </Box>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' type='date' label='Date' InputLabelProps={{ shrink: true }} value={draft.date}
              onChange={e => setDraft(d => ({ ...d, date: e.target.value }))} />
            <TextField select fullWidth size='small' label='Status' value={draft.status}
              onChange={e => setDraft(d => ({ ...d, status: e.target.value as EventStatus }))}>
              {EVENT_STATUSES.map(s => <MenuItem key={s.value} value={s.value}>{s.label}</MenuItem>)}
            </TextField>
          </Box>
          <TextField fullWidth size='small' label='Reference Number' value={draft.referenceNumber ?? ''}
            onChange={e => setDraft(d => ({ ...d, referenceNumber: e.target.value }))} />
          <TextField fullWidth size='small' label='Notes' multiline rows={2} value={draft.notes ?? ''}
            onChange={e => setDraft(d => ({ ...d, notes: e.target.value }))} />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setEventDialog(false)} disabled={saving}>Cancel</Button>
          <Button variant='contained' onClick={save} disabled={saving || !draft.title.trim()}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            {saving ? 'Saving…' : editId ? 'Save Changes' : 'Add Event'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}
