'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardHeader from '@mui/material/CardHeader'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import Avatar from '@mui/material/Avatar'
import Divider from '@mui/material/Divider'
import Tab from '@mui/material/Tab'
import Tabs from '@mui/material/Tabs'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import TextField from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
import Alert from '@mui/material/Alert'
import Tooltip from '@mui/material/Tooltip'
import IconButton from '@mui/material/IconButton'
import type { ClientFolder, ClientStatus, FolderTeamMember, FolderParty } from './types'
import { ADDRESS_COUNTRIES } from './AddressEntryField'
import { useT } from '@/contexts/LangContext'
import DocumentsTab from './DocumentsTab'
import MattersTab from './MattersTab'
import ClientBillingView from './ClientBillingView'
import CommunicationsTab from './CommunicationsTab'
import { AgenciesSection, ComplianceTab } from './ComplianceFishbone'

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

const STATUS_CONFIG: Record<ClientStatus, { color: string; bg: string; icon: string }> = {
  prospect:       { color: '#7C6AF7', bg: '#EEF2FF', icon: 'ri-user-search-line' },
  conflict_check: { color: '#FFB400', bg: '#FFF5DB', icon: 'ri-shield-search-line' },
  active:         { color: '#0D9394', bg: '#E8F7F7', icon: 'ri-checkbox-circle-line' },
  closed:         { color: '#6B7280', bg: '#F0F0F0', icon: 'ri-archive-line' },
  rejected:       { color: '#FF4C51', bg: '#FFECEC', icon: 'ri-close-circle-line' },
}

const TEAM_ROLE_SECTIONS: Record<FolderTeamMember['role'], 'internal' | 'external'> = {
  responsible_attorney: 'internal',
  originating_attorney: 'internal',
  associate_attorney:   'internal',
  paralegal:            'internal',
  secretary:            'internal',
  translator:           'internal',
  external_counsel:     'external',
  other:                'internal',
}

const TEAM_ROLE_VALUES: FolderTeamMember['role'][] = [
  'responsible_attorney', 'originating_attorney', 'associate_attorney',
  'paralegal', 'secretary', 'translator', 'external_counsel', 'other',
]

const PARTY_TYPE_SECTIONS: Record<FolderParty['type'], 'opposing' | 'judicial'> = {
  opposing_party:     'opposing',
  opposing_counsel:   'opposing',
  judge:              'judicial',
  prosecutor:         'judicial',
  government_counsel: 'judicial',
  court_officer:      'judicial',
  government_agency:  'judicial',
  other:              'opposing',
}

const PARTY_TYPE_VALUES: FolderParty['type'][] = [
  'opposing_party', 'opposing_counsel', 'judge', 'prosecutor',
  'government_counsel', 'court_officer', 'government_agency', 'other',
]

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

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

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

function initials(name: string) {
  return name.split(/[\s,]+/).filter(Boolean).slice(0, 2).map(w => w[0]).join('').toUpperCase()
}

function countryFlag(code: string) {
  return ADDRESS_COUNTRIES.find(c => c.code === code)?.flag ?? ''
}
function countryName(code: string) {
  return ADDRESS_COUNTRIES.find(c => c.code === code)?.name ?? code
}

// ─── Shared UI ───────────────────────────────────────────────────────────────

function InfoRow({ label, value, mono }: { label: string; value?: string | null; mono?: boolean }) {
  return (
    <Box sx={{ display: 'flex', py: 0.75, borderBottom: '1px solid', borderColor: 'divider' }}>
      <Typography variant='caption' color='text.disabled' sx={{ width: 155, flexShrink: 0 }}>{label}</Typography>
      <Typography variant='body2' sx={{ fontFamily: mono ? 'monospace' : undefined }}>{value || '—'}</Typography>
    </Box>
  )
}

function SectionCard({ title, icon, action, children }: { title: string; icon: string; action?: React.ReactNode; children: React.ReactNode }) {
  return (
    <Card>
      <CardHeader title={title} titleTypographyProps={{ variant: 'subtitle2' }}
        avatar={<i className={icon} style={{ color: '#0D9394', fontSize: '1rem' }} />}
        action={action} sx={{ pb: 0.5 }} />
      <CardContent sx={{ pt: 0 }}>{children}</CardContent>
    </Card>
  )
}

// ─── Address Blocks ───────────────────────────────────────────────────────────

function AddressBlocks({ addresses }: { addresses: any[] }) {
  const t = useT()
  if (!addresses?.length) return null

  const TYPE_LABELS: Record<string, string> = {
    primary: t.clientDetail.addrPrimary,
    mailing: t.clientDetail.addrMailing,
    billing: t.clientDetail.addrBilling,
    home:    t.clientDetail.addrHome,
    foreign: t.clientDetail.addrForeign,
    other:   t.clientDetail.addrOther,
  }

  return (
    <SectionCard title={t.clientDetail.sectionAddresses} icon='ri-map-pin-line'>
      <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2, pt: 0.5 }}>
        {addresses.map((a: any, i: number) => (
          <Box key={i} sx={{
            border: '1px solid', borderColor: 'divider', borderRadius: 1,
            p: 1.5, minWidth: 200, flex: '1 1 200px', maxWidth: 280,
            bgcolor: i === 0 ? 'action.hover' : 'transparent',
          }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 1 }}>
              <Chip label={TYPE_LABELS[a.type] ?? a.type} size='small'
                sx={{ height: 18, fontSize: '0.62rem', fontWeight: 700,
                  bgcolor: i === 0 ? '#E8F7F7' : '#F3F4F6',
                  color: i === 0 ? '#0D9394' : '#6B7280' }} />
              <span style={{ fontSize: '1rem' }}>{countryFlag(a.country)}</span>
            </Box>
            <Typography variant='body2' sx={{ lineHeight: 1.7 }}>
              {a.line1}
              {a.line2 && <><br />{a.line2}</>}
              {(a.city || a.state) && <><br />{[a.city, a.state].filter(Boolean).join(', ')}</>}
              {a.postal && ` ${a.postal}`}
              <br />
              <Typography component='span' variant='caption' color='text.secondary'>
                {countryName(a.country)}
              </Typography>
            </Typography>
          </Box>
        ))}
      </Box>
    </SectionCard>
  )
}

// ─── Overview Tab ─────────────────────────────────────────────────────────────

function OverviewTab({ folder }: { folder: ClientFolder }) {
  const t = useT()
  const isIndividual = folder.clientType === 'individual'

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

      {/* Top row: identity + contact side-by-side */}
      <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2 }}>
        <SectionCard title={isIndividual ? t.clientDetail.sectionPersonal : t.clientDetail.sectionCompany}
          icon={isIndividual ? 'ri-id-card-line' : 'ri-building-line'}>
          {isIndividual ? (
            <>
              <InfoRow label={t.clientForm.firstName}    value={folder.firstName} />
              <InfoRow label={t.clientForm.lastName}     value={folder.lastName} />
              <InfoRow label={t.clientForm.nationality}  value={folder.nationality} />
              <InfoRow label={(folder as any).idType ?? t.clientForm.passportNumber} value={folder.passportNumber} mono />
              <InfoRow label={t.clientForm.dateOfBirth}  value={fmtDate(folder.dateOfBirth)} />
              <InfoRow label={t.clientForm.visaType}     value={folder.visaType} />
              {(folder as any).visaNumber && <InfoRow label={t.clientForm.visaNumber} value={(folder as any).visaNumber} mono />}
              <InfoRow label={t.clientForm.visaExpiry}   value={fmtDate(folder.visaExpiry)} />
            </>
          ) : (
            <>
              <InfoRow label={t.clientForm.companyName}         value={folder.companyName} />
              <InfoRow label={t.clientForm.registrationNumber}  value={folder.registrationNumber} mono />
              <InfoRow label={t.clientForm.boiStatus}           value={folder.boiStatus} />
              {folder.directors?.length ? <InfoRow label='Directors' value={folder.directors.join(', ')} /> : null}
            </>
          )}
        </SectionCard>

        <SectionCard title={t.clientDetail.sectionContact} icon='ri-contacts-line'>
          {(folder.phones?.length ? folder.phones : folder.phone ? [{ dialCode: '', number: folder.phone, type: 'mobile', countryCode: '' }] : []).map((p: any, i: number) => (
            <InfoRow key={i} label={i === 0 ? t.clientForm.phoneLabel : `${t.clientForm.phoneLabel} ${i + 1}`}
              value={`${p.dialCode} ${p.number}`.trim() + (p.type !== 'mobile' ? ` (${p.type})` : '')} />
          ))}
          {(folder.emails?.length ? folder.emails : folder.email ? [{ address: folder.email, type: 'primary' }] : []).map((e: any, i: number) => (
            <InfoRow key={i} label={i === 0 ? t.clientForm.emailLabel : `${t.clientForm.emailLabel} ${i + 1}`}
              value={e.address + (e.type !== 'primary' ? ` (${e.type})` : '')} />
          ))}
          {folder.lineId && <InfoRow label={t.clientForm.lineId}  value={folder.lineId} />}
          {folder.region  && <InfoRow label={t.clientDetail.labelRegion} value={folder.region} />}
        </SectionCard>
      </Box>

      {/* Address standard blocks — full width */}
      {(folder as any).addresses?.length > 0 && (
        <AddressBlocks addresses={(folder as any).addresses} />
      )}

      {/* Bottom row: engagement + notes side-by-side when notes exist */}
      {folder.notes ? (
        <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2 }}>
          <SectionCard title={t.clientDetail.sectionEngagement} icon='ri-user-star-line'>
            <InfoRow label={t.clientDetail.labelResponsibleAtty} value={folder.responsibleAttorney} />
            <InfoRow label={t.clientDetail.labelOriginatingAtty} value={folder.originatingAttorney} />
            <InfoRow label={t.clientDetail.labelEngagement}      value={fmtDate(folder.engagementDate)} />
            <InfoRow label={t.clientDetail.labelEngagementLetter} value={folder.engagementLetterRef} />
            {folder.status === 'closed' && <>
              <InfoRow label={t.clientDetail.labelClosedDate}   value={fmtDate(folder.closedDate)} />
              <InfoRow label={t.clientDetail.labelClosedReason} value={folder.closedReason} />
            </>}
          </SectionCard>
          <SectionCard title={t.clientDetail.sectionNotes} icon='ri-sticky-note-line'>
            <Typography variant='body2' color='text.secondary' sx={{ whiteSpace: 'pre-wrap', pt: 0.5 }}>{folder.notes}</Typography>
          </SectionCard>
        </Box>
      ) : (
        <SectionCard title={t.clientDetail.sectionEngagement} icon='ri-user-star-line'>
          <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0 }}>
            <Box>
              <InfoRow label={t.clientDetail.labelResponsibleAtty} value={folder.responsibleAttorney} />
              <InfoRow label={t.clientDetail.labelOriginatingAtty} value={folder.originatingAttorney} />
            </Box>
            <Box>
              <InfoRow label={t.clientDetail.labelEngagement}      value={fmtDate(folder.engagementDate)} />
              <InfoRow label={t.clientDetail.labelEngagementLetter} value={folder.engagementLetterRef} />
            </Box>
          </Box>
          {folder.status === 'closed' && (
            <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, mt: 0.5 }}>
              <InfoRow label={t.clientDetail.labelClosedDate}   value={fmtDate(folder.closedDate)} />
              <InfoRow label={t.clientDetail.labelClosedReason} value={folder.closedReason} />
            </Box>
          )}
        </SectionCard>
      )}

    </Box>
  )
}

// ─── Team Tab ─────────────────────────────────────────────────────────────────

function TeamTab({ folder, onUpdate }: { folder: ClientFolder; onUpdate: (f: ClientFolder) => void }) {
  const t = useT()
  const [dialog, setDialog] = useState<{ open: boolean; editIdx: number | null }>({ open: false, editIdx: null })
  const [saving, setSaving] = useState(false)
  const [err, setErr]       = useState<string | null>(null)
  const empty = (): FolderTeamMember => ({ name: '', role: 'paralegal', firm: '', email: '', phone: '', notes: '' })
  const [draft, setDraft]   = useState<FolderTeamMember>(empty())

  const rawTeam: FolderTeamMember[] = (folder as any).folderTeam ?? []
  const displayTeam = rawTeam.length > 0 ? rawTeam : [
    { name: folder.responsibleAttorney, role: 'responsible_attorney' as const },
    ...(folder.originatingAttorney !== folder.responsibleAttorney
      ? [{ name: folder.originatingAttorney, role: 'originating_attorney' as const }]
      : []),
  ]

  const open    = (defaultRole?: FolderTeamMember['role']) => { setDraft({ ...empty(), ...(defaultRole ? { role: defaultRole } : {}) }); setErr(null); setDialog({ open: true, editIdx: null }) }
  const openEdit = (i: number) => { setDraft({ ...displayTeam[i] }); setErr(null); setDialog({ open: true, editIdx: i }) }
  const close   = () => setDialog({ open: false, editIdx: null })

  const save = async () => {
    if (!draft.name.trim()) { setErr(t.common.required); return }
    setSaving(true); setErr(null)
    const next = [...displayTeam]
    if (dialog.editIdx !== null) next[dialog.editIdx] = draft; else next.push(draft)
    try {
      const res = await fetch(`/api/clients/${folder._id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ folderTeam: next }) })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? t.documentsTab.errSaveFailed)
      onUpdate(await res.json()); close()
    } catch (e: any) { setErr(e.message) } finally { setSaving(false) }
  }

  const remove = async (i: number) => {
    const next = displayTeam.filter((_, idx) => idx !== i)
    const res = await fetch(`/api/clients/${folder._id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ folderTeam: next }) })
    if (res.ok) onUpdate(await res.json())
  }

  const roleLabel = (r: string) => t.clientDetail.teamRoles[r as keyof typeof t.clientDetail.teamRoles] ?? r
  const internal  = displayTeam.filter(m => TEAM_ROLE_SECTIONS[m.role] !== 'external')
  const external  = displayTeam.filter(m => TEAM_ROLE_SECTIONS[m.role] === 'external')

  const MemberTable = ({ members, offset }: { members: FolderTeamMember[]; offset: number }) =>
    members.length === 0
      ? <Typography variant='body2' color='text.disabled' sx={{ py: 3, textAlign: 'center' }}>{t.clientDetail.noneOnRecord}</Typography>
      : <Box sx={{ overflowX: 'auto' }}>
          <Table size='small' sx={{ minWidth: 520 }}>
            <TableHead><TableRow sx={{ bgcolor: 'action.hover' }}>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colName}</TableCell>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colRole}</TableCell>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colFirm}</TableCell>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colContact}</TableCell>
              <TableCell width={72} />
            </TableRow></TableHead>
            <TableBody>
              {members.map((m, i) => (
                <TableRow key={i} hover>
                  <TableCell><Typography variant='body2' sx={{ fontWeight: 500 }}>{m.name}</Typography></TableCell>
                  <TableCell><Chip label={roleLabel(m.role)} size='small' sx={{ bgcolor: '#E8F7F7', color: '#0D9394', fontSize: '0.65rem', height: 18, fontWeight: 600 }} /></TableCell>
                  <TableCell><Typography variant='caption' color='text.secondary'>{m.firm || '—'}</Typography></TableCell>
                  <TableCell><Typography variant='caption' color='text.secondary'>{[m.email, m.phone].filter(Boolean).join(' · ') || '—'}</Typography></TableCell>
                  <TableCell align='right' sx={{ whiteSpace: 'nowrap', pr: 1 }}>
                    <Tooltip title={t.common.edit}><IconButton size='small' onClick={() => openEdit(offset + i)}><i className='ri-edit-line' style={{ fontSize: '0.85rem' }} /></IconButton></Tooltip>
                    <Tooltip title={t.common.delete}><IconButton size='small' onClick={() => remove(offset + i)}><i className='ri-delete-bin-line' style={{ fontSize: '0.85rem', color: '#FF4C51' }} /></IconButton></Tooltip>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Box>

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <SectionCard title={t.clientDetail.sectionInternalTeam} icon='ri-team-line'
        action={<Button size='small' startIcon={<i className='ri-add-line' />} onClick={() => open()} sx={{ fontSize: '0.72rem' }}>{t.clientDetail.addMember}</Button>}>
        <MemberTable members={internal} offset={0} />
      </SectionCard>
      <SectionCard title={t.clientDetail.sectionExternalCounsel} icon='ri-building-4-line'
        action={<Button size='small' startIcon={<i className='ri-add-line' />} onClick={() => open('external_counsel')} sx={{ fontSize: '0.72rem' }}>{t.clientDetail.addExternal}</Button>}>
        <MemberTable members={external} offset={internal.length} />
      </SectionCard>

      <Dialog open={dialog.open} onClose={close} maxWidth='sm' fullWidth>
        <DialogTitle>{dialog.editIdx !== null ? t.clientDetail.editMemberTitle : t.clientDetail.addMemberTitle}</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={t.clientDetail.colName} value={draft.name} onChange={e => setDraft(d => ({ ...d, name: e.target.value }))} />
            <TextField select fullWidth size='small' label={t.clientDetail.colRole} value={draft.role} onChange={e => setDraft(d => ({ ...d, role: e.target.value as FolderTeamMember['role'] }))}>
              {TEAM_ROLE_VALUES.map(r => <MenuItem key={r} value={r}>{t.clientDetail.teamRoles[r]}</MenuItem>)}
            </TextField>
          </Box>
          <TextField fullWidth size='small' label={t.clientDetail.labelFirmOrg} value={draft.firm ?? ''} onChange={e => setDraft(d => ({ ...d, firm: e.target.value }))} />
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' label={t.clientForm.emailLabel} value={draft.email ?? ''} onChange={e => setDraft(d => ({ ...d, email: e.target.value }))} />
            <TextField fullWidth size='small' label={t.clientForm.phoneLabel} value={draft.phone ?? ''} onChange={e => setDraft(d => ({ ...d, phone: e.target.value }))} />
          </Box>
          <TextField fullWidth size='small' label={t.clientDetail.labelNotes} multiline rows={2} value={draft.notes ?? ''} onChange={e => setDraft(d => ({ ...d, notes: e.target.value }))} />
        </DialogContent>
        <DialogActions>
          <Button onClick={close} disabled={saving}>{t.common.cancel}</Button>
          <Button variant='contained' onClick={save} disabled={saving} sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>{saving ? t.common.saving : t.common.save}</Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}

// ─── Parties Tab ──────────────────────────────────────────────────────────────

function PartiesTab({ folder, onUpdate }: { folder: ClientFolder; onUpdate: (f: ClientFolder) => void }) {
  const t = useT()
  const [dialog, setDialog] = useState<{ open: boolean; editIdx: number | null }>({ open: false, editIdx: null })
  const [saving, setSaving] = useState(false)
  const [err, setErr]       = useState<string | null>(null)
  const empty = (): FolderParty => ({ name: '', type: 'opposing_counsel', organization: '', role: '', email: '', phone: '', barNumber: '', notes: '' })
  const [draft, setDraft]   = useState<FolderParty>(empty())

  const parties: FolderParty[] = (folder as any).folderParties ?? []

  const open    = (defaultType?: FolderParty['type']) => { setDraft({ ...empty(), ...(defaultType ? { type: defaultType } : {}) }); setErr(null); setDialog({ open: true, editIdx: null }) }
  const openEdit = (i: number) => { setDraft({ ...parties[i] }); setErr(null); setDialog({ open: true, editIdx: i }) }
  const close   = () => setDialog({ open: false, editIdx: null })

  const save = async () => {
    if (!draft.name.trim()) { setErr(t.common.required); return }
    setSaving(true); setErr(null)
    const next = [...parties]
    if (dialog.editIdx !== null) next[dialog.editIdx] = draft; else next.push(draft)
    try {
      const res = await fetch(`/api/clients/${folder._id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ folderParties: next }) })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? t.documentsTab.errSaveFailed)
      onUpdate(await res.json()); close()
    } catch (e: any) { setErr(e.message) } finally { setSaving(false) }
  }

  const remove = async (i: number) => {
    const next = parties.filter((_, idx) => idx !== i)
    const res = await fetch(`/api/clients/${folder._id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ folderParties: next }) })
    if (res.ok) onUpdate(await res.json())
  }

  const typeLabel = (v: string) => t.clientDetail.partyTypes[v as keyof typeof t.clientDetail.partyTypes] ?? v
  const opposing  = parties.filter(p => PARTY_TYPE_SECTIONS[p.type] === 'opposing')
  const judicial  = parties.filter(p => PARTY_TYPE_SECTIONS[p.type] === 'judicial')

  const PartyTable = ({ plist, offset, empty: emptyMsg }: { plist: FolderParty[]; offset: number; empty: string }) =>
    plist.length === 0
      ? <Typography variant='body2' color='text.disabled' sx={{ py: 3, textAlign: 'center' }}>{emptyMsg}</Typography>
      : <Box sx={{ overflowX: 'auto' }}>
          <Table size='small' sx={{ minWidth: 560 }}>
            <TableHead><TableRow sx={{ bgcolor: 'action.hover' }}>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colName}</TableCell>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colType}</TableCell>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colOrganization}</TableCell>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colRoleBar}</TableCell>
              <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem' }}>{t.clientDetail.colContact}</TableCell>
              <TableCell width={72} />
            </TableRow></TableHead>
            <TableBody>
              {plist.map((p, i) => (
                <TableRow key={i} hover>
                  <TableCell><Typography variant='body2' sx={{ fontWeight: 500 }}>{p.name}</Typography></TableCell>
                  <TableCell><Chip label={typeLabel(p.type)} size='small' sx={{ bgcolor: '#FFF5DB', color: '#FFB400', fontSize: '0.65rem', height: 18, fontWeight: 600 }} /></TableCell>
                  <TableCell><Typography variant='caption' color='text.secondary'>{p.organization || '—'}</Typography></TableCell>
                  <TableCell><Typography variant='caption' color='text.secondary'>{[p.role, p.barNumber ? `Bar: ${p.barNumber}` : ''].filter(Boolean).join(' · ') || '—'}</Typography></TableCell>
                  <TableCell><Typography variant='caption' color='text.secondary'>{[p.email, p.phone].filter(Boolean).join(' · ') || '—'}</Typography></TableCell>
                  <TableCell align='right' sx={{ whiteSpace: 'nowrap', pr: 1 }}>
                    <Tooltip title={t.common.edit}><IconButton size='small' onClick={() => openEdit(offset + i)}><i className='ri-edit-line' style={{ fontSize: '0.85rem' }} /></IconButton></Tooltip>
                    <Tooltip title={t.common.delete}><IconButton size='small' onClick={() => remove(offset + i)}><i className='ri-delete-bin-line' style={{ fontSize: '0.85rem', color: '#FF4C51' }} /></IconButton></Tooltip>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Box>

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <SectionCard title={t.clientDetail.sectionOpposing} icon='ri-sword-line'
        action={<Button size='small' startIcon={<i className='ri-add-line' />} onClick={() => open('opposing_counsel')} sx={{ fontSize: '0.72rem' }}>{t.clientDetail.addOpposing}</Button>}>
        <PartyTable plist={opposing} offset={0} empty={t.clientDetail.noOpposing} />
      </SectionCard>
      <SectionCard title={t.clientDetail.sectionJudicial} icon='ri-government-line'
        action={<Button size='small' startIcon={<i className='ri-add-line' />} onClick={() => open('judge')} sx={{ fontSize: '0.72rem' }}>{t.clientDetail.addParty}</Button>}>
        <PartyTable plist={judicial} offset={opposing.length} empty={t.clientDetail.noJudicial} />
      </SectionCard>

      <SectionCard title={t.clientDetail.sectionAgencies} icon='ri-bank-line'>
        <AgenciesSection folder={folder} onUpdate={onUpdate} />
      </SectionCard>

      <Dialog open={dialog.open} onClose={close} maxWidth='sm' fullWidth>
        <DialogTitle>{dialog.editIdx !== null ? t.clientDetail.editPartyTitle : t.clientDetail.addPartyTitle}</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={t.clientDetail.colName} value={draft.name} onChange={e => setDraft(d => ({ ...d, name: e.target.value }))} />
            <TextField select fullWidth size='small' label={t.clientDetail.colType} value={draft.type} onChange={e => setDraft(d => ({ ...d, type: e.target.value as FolderParty['type'] }))}>
              {PARTY_TYPE_VALUES.map(v => <MenuItem key={v} value={v}>{t.clientDetail.partyTypes[v]}</MenuItem>)}
            </TextField>
          </Box>
          <TextField fullWidth size='small' label={t.clientDetail.labelOrgFirmCourt} value={draft.organization ?? ''} onChange={e => setDraft(d => ({ ...d, organization: e.target.value }))} />
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' label={t.clientDetail.labelRolePosition} value={draft.role ?? ''} onChange={e => setDraft(d => ({ ...d, role: e.target.value }))} />
            <TextField fullWidth size='small' label={t.clientDetail.labelBarLicense} value={draft.barNumber ?? ''} onChange={e => setDraft(d => ({ ...d, barNumber: e.target.value }))} />
          </Box>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField fullWidth size='small' label={t.clientForm.emailLabel} value={draft.email ?? ''} onChange={e => setDraft(d => ({ ...d, email: e.target.value }))} />
            <TextField fullWidth size='small' label={t.clientForm.phoneLabel} value={draft.phone ?? ''} onChange={e => setDraft(d => ({ ...d, phone: e.target.value }))} />
          </Box>
          <TextField fullWidth size='small' label={t.clientDetail.labelNotes} multiline rows={2} value={draft.notes ?? ''} onChange={e => setDraft(d => ({ ...d, notes: e.target.value }))} />
        </DialogContent>
        <DialogActions>
          <Button onClick={close} disabled={saving}>{t.common.cancel}</Button>
          <Button variant='contained' onClick={save} disabled={saving} sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>{saving ? t.common.saving : t.common.save}</Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}

// ─── Admin Card (right panel) ─────────────────────────────────────────────────

function AdminCard({ folder, lang, onAction, onUploadDoc }: {
  folder: ClientFolder
  lang: string
  onAction: (action: 'convert' | 'activate' | 'close') => void
  onUploadDoc: () => void
}) {
  const t = useT()
  const router = useRouter()
  const st  = STATUS_CONFIG[folder.status]
  const statusLabel = folder.status === 'conflict_check' ? t.status.conflictCheck : t.status[folder.status as keyof typeof t.status] ?? folder.status
  const low = folder.status === 'active' && folder.retainerBalance < folder.retainerThreshold

  return (
    <Card sx={{ position: 'sticky', top: 80 }}>
      <CardContent sx={{ p: 2 }}>

        {/* Status */}
        <Box sx={{ mb: 2 }}>
          <Chip label={statusLabel} icon={<i className={st.icon} style={{ fontSize: '0.85rem' }} />}
            sx={{ bgcolor: st.bg, color: st.color, fontWeight: 700, fontSize: '0.78rem', height: 28, width: '100%',
              '& .MuiChip-label': { flex: 1, textAlign: 'center' } }} />
        </Box>

        {/* Key info */}
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.25, mb: 2 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', py: 0.5, borderBottom: '1px solid', borderColor: 'divider' }}>
            <Typography variant='caption' color='text.disabled'>{t.clientDetail.labelFolder}</Typography>
            <Typography variant='caption' sx={{ fontFamily: 'monospace', fontWeight: 600 }}>{folder.folderNumber}</Typography>
          </Box>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', py: 0.5, borderBottom: '1px solid', borderColor: 'divider' }}>
            <Typography variant='caption' color='text.disabled'>{t.clientDetail.labelResponsible}</Typography>
            <Typography variant='caption' sx={{ fontWeight: 500, textAlign: 'right', maxWidth: 140 }}>{folder.responsibleAttorney}</Typography>
          </Box>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', py: 0.5, borderBottom: '1px solid', borderColor: 'divider' }}>
            <Typography variant='caption' color='text.disabled'>{t.clientDetail.labelOriginating}</Typography>
            <Typography variant='caption' sx={{ fontWeight: 500, textAlign: 'right', maxWidth: 140 }}>{folder.originatingAttorney}</Typography>
          </Box>
          {folder.region && (
            <Box sx={{ display: 'flex', justifyContent: 'space-between', py: 0.5, borderBottom: '1px solid', borderColor: 'divider' }}>
              <Typography variant='caption' color='text.disabled'>{t.clientDetail.labelRegion}</Typography>
              <Typography variant='caption' sx={{ fontWeight: 500 }}>{folder.region}</Typography>
            </Box>
          )}
        </Box>

        <Divider sx={{ my: 1.5 }} />

        {/* Retainer summary */}
        <Box sx={{ mb: 2 }}>
          <Typography variant='caption' color='text.disabled' sx={{ display: 'block', mb: 0.5 }}>{t.clientDetail.labelRetainerBalance}</Typography>
          <Typography variant='h5' sx={{ fontWeight: 700, color: low ? '#FF4C51' : 'text.primary', lineHeight: 1 }}>
            {new Intl.NumberFormat('en-TH', { maximumFractionDigits: 0 }).format(folder.retainerBalance)}
            <Typography component='span' variant='caption' color='text.disabled' sx={{ ml: 0.5 }}>{folder.currency}</Typography>
          </Typography>
          {low && <Chip label={t.clientDetail.belowThreshold} size='small' sx={{ mt: 0.5, bgcolor: '#FFECEC', color: '#FF4C51', fontSize: '0.62rem', height: 18, fontWeight: 600 }} />}
          <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 1 }}>
            <Typography variant='caption' color='text.disabled'>{t.clientDetail.labelThreshold}</Typography>
            <Typography variant='caption'>{new Intl.NumberFormat('en-TH', { maximumFractionDigits: 0 }).format(folder.retainerThreshold)} {folder.currency}</Typography>
          </Box>
        </Box>

        <Button fullWidth size='small' variant='outlined' startIcon={<i className='ri-bill-line' />}
          onClick={() => router.push(`/${lang}/clients/${folder._id}/billing`)}
          sx={{ mb: 1, fontSize: '0.75rem' }}>
          {t.clientDetail.billingLedger}
        </Button>

        <Button fullWidth size='small' variant='outlined' startIcon={<i className='ri-settings-3-line' />}
          onClick={() => router.push(`/${lang}/clients/${folder._id}/billing/settings`)}
          sx={{ mb: 1, fontSize: '0.75rem' }}>
          {t.clientDetail.billingSettings}
        </Button>

        <Button fullWidth size='small' variant='outlined' startIcon={<i className='ri-upload-2-line' />}
          onClick={onUploadDoc}
          sx={{ mb: 1.5, fontSize: '0.75rem' }}>
          {t.clientDetail.uploadDocument}
        </Button>

        <Divider sx={{ my: 1.5 }} />

        {/* Actions */}
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
          <Button fullWidth size='small' variant='outlined' startIcon={<i className='ri-edit-line' />}
            onClick={() => router.push(`/${lang}/clients/${folder._id}/edit`)}
            sx={{ fontSize: '0.75rem' }}>
            {t.clientDetail.editClientBtn}
          </Button>
          {folder.status === 'conflict_check' && (
            <Button fullWidth size='small' variant='contained'
              startIcon={<i className='ri-checkbox-circle-line' />}
              sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' }, fontSize: '0.75rem' }}
              onClick={() => onAction('activate')}>
              {t.clientDetail.activate}
            </Button>
          )}
          {folder.status === 'active' && (
            <Button fullWidth size='small' variant='outlined' color='error'
              startIcon={<i className='ri-archive-line' />}
              onClick={() => onAction('close')} sx={{ fontSize: '0.75rem' }}>
              {t.clientDetail.closeFileBtn}
            </Button>
          )}
        </Box>

      </CardContent>
    </Card>
  )
}

// ─── Main component ───────────────────────────────────────────────────────────

export default function ClientDetailView({ folder: initial, lang }: { folder: ClientFolder; lang: string }) {
  const t = useT()
  const [folder, setFolder]           = useState(initial)
  const [tab, setTab]                 = useState(0)
  const [actionDialog, setActionDialog] = useState<'convert' | 'activate' | 'close' | null>(null)
  const [actionInput, setActionInput]   = useState('')
  const [actionError, setActionError]   = useState<string | null>(null)
  const [actioning, setActioning]       = useState(false)
  const [triggerUpload, setTriggerUpload] = useState(false)

  const handleAction = async () => {
    setActionError(null); setActioning(true)
    try {
      const body =
        actionDialog === 'activate' ? { engagementLetterRef: actionInput } :
        actionDialog === 'convert'  ? { engagementLetterRef: actionInput } :
        { outcome: actionInput }
      const res = await fetch(`/api/clients/${folder._id}/${actionDialog}`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? `Failed (${res.status})`)
      setFolder(await res.json()); setActionDialog(null); setActionInput('')
    } catch (e: any) { setActionError(e.message) }
    finally { setActioning(false) }
  }

  const clientSince = folder.engagementDate ?? folder.createdAt
  const TABS = [
    t.clientDetail.tabOverview,
    t.clientDetail.tabMatters,
    t.clientDetail.tabBilling,
    t.clientDetail.tabCommunications,
    t.clientDetail.tabTeam,
    t.clientDetail.tabParties,
    t.clientDetail.tabCompliance,
    t.clientDetail.tabDocuments,
  ]

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

      {/* ── Header ── */}
      <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
        <Avatar sx={{ width: 48, height: 48, bgcolor: '#0D939422', color: '#0D9394', fontWeight: 700, fontSize: '1rem', flexShrink: 0 }}>
          {initials(folder.displayName)}
        </Avatar>
        <Box>
          <Typography variant='h4' sx={{ fontWeight: 700, lineHeight: 1.2 }}>{folder.displayName}</Typography>
          <Typography variant='body2' color='text.secondary'>
            {folder.clientType === 'individual' ? t.clientList.individual : t.clientList.corporate}
            {(() => { const e = folder.emails?.[0]?.address ?? folder.email; return e ? ` · ${e}` : null })()}
            {clientSince && (
              <Box component='span' sx={{ ml: 1.5, pl: 1.5, borderLeft: '1px solid', borderColor: 'divider' }}>
                <i className='ri-calendar-check-line' style={{ marginRight: 4, fontSize: '0.8rem' }} />
                {t.clientDetail.clientSince} {fmtDate(clientSince)}
              </Box>
            )}
          </Typography>
        </Box>
      </Box>

      <Divider />

      <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ minHeight: 36, mt: -1 }}>
        {TABS.map((label, i) => (
          <Tab key={i} label={label} sx={{ minHeight: 36, fontSize: '0.85rem' }} />
        ))}
      </Tabs>

      {/* ── Two-column body: tab content + admin card ── */}
      <Box sx={{ display: 'flex', gap: 3, alignItems: 'flex-start' }}>

        {/* Main column */}
        <Box sx={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>

        {tab === 0 && <OverviewTab folder={folder} />}
        {tab === 1 && <MattersTab clientFolder={folder} />}
        {tab === 2 && <ClientBillingView folder={folder} lang={lang} embedded />}
        {tab === 3 && <CommunicationsTab folder={folder} />}
        {tab === 4 && <TeamTab folder={folder} onUpdate={setFolder} />}
        {tab === 5 && <PartiesTab folder={folder} onUpdate={setFolder} />}
        {tab === 6 && <ComplianceTab folder={folder} onUpdate={setFolder} />}
        {tab === 7 && (
          <DocumentsTab
            folder={folder}
            onUpdate={setFolder}
            openUpload={triggerUpload}
            onUploadClose={() => setTriggerUpload(false)}
          />
        )}
      </Box>

        {/* ── Admin card ── */}
        <Box sx={{ width: 260, flexShrink: 0 }}>
          <AdminCard folder={folder} lang={lang}
            onAction={act => { setActionInput(''); setActionError(null); setActionDialog(act) }}
            onUploadDoc={() => { setTab(4); setTriggerUpload(true) }} />
        </Box>

      </Box>{/* end two-column body */}

      {/* Activate dialog */}
      <Dialog open={actionDialog === 'activate'} onClose={() => setActionDialog(null)} maxWidth='xs' fullWidth>
        <DialogTitle>{t.clientDetail.activateTitle}</DialogTitle>
        <DialogContent>
          <Typography variant='body2' color='text.secondary' sx={{ mb: 2 }}>
            {t.clientDetail.activateConfirm}
          </Typography>
          {actionError && <Alert severity='error' sx={{ mb: 2 }}>{actionError}</Alert>}
          <TextField fullWidth label={t.clientDetail.labelEngagementLetterRef} size='small' autoFocus
            value={actionInput} onChange={e => setActionInput(e.target.value)} placeholder='e.g. EL-2025-0042' />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setActionDialog(null)} disabled={actioning}>{t.common.cancel}</Button>
          <Button variant='contained' onClick={handleAction} disabled={actioning || !actionInput}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}>
            {actioning ? t.clientDetail.activating : t.clientDetail.activate}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Close dialog */}
      <Dialog open={actionDialog === 'close'} onClose={() => setActionDialog(null)} maxWidth='xs' fullWidth>
        <DialogTitle>{t.clientDetail.closeFileTitle}</DialogTitle>
        <DialogContent>
          <Typography variant='body2' color='text.secondary' sx={{ mb: 2 }}>
            {t.clientDetail.closeConfirm}
          </Typography>
          {actionError && <Alert severity='error' sx={{ mb: 2 }}>{actionError}</Alert>}
          <TextField fullWidth label={t.clientDetail.outcomeReason} size='small' autoFocus multiline rows={3}
            value={actionInput} onChange={e => setActionInput(e.target.value)}
            placeholder='e.g. Matter resolved, client satisfied. No outstanding balances.' />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setActionDialog(null)} disabled={actioning}>{t.common.cancel}</Button>
          <Button variant='contained' color='error' onClick={handleAction} disabled={actioning || !actionInput}>
            {actioning ? t.clientDetail.closing : t.clientDetail.closeFileBtn}
          </Button>
        </DialogActions>
      </Dialog>

    </Box>
  )
}
