import React, {FormEvent, useEffect, useMemo, useState} from 'react';
import {Link, usePage} from '@inertiajs/react';
import axios from 'axios';
import AppPageHeader from '@/components/AppPageHeader';
import MainLayout from '@/layouts/MainLayout';
import Modal from '@/components/ui/modal/Modal';
import {makeDeleteRequest, makeGetRequest, makePostRequest, makePutRequest} from '@/lib/request';
import {notify} from '@/lib/notify';
import EvidenceWorkspace from '@/Pages/Litigation/partials/EvidenceWorkspace';
import WitnessWorkspace from '@/Pages/Litigation/partials/WitnessWorkspace';
import DocketWorkspace from '@/Pages/Litigation/partials/DocketWorkspace';
import TimelineWorkspace from '@/Pages/Litigation/partials/TimelineWorkspace';

type Tab = 'overview' | 'timeline' | 'docket' | 'pleadings' | 'hearings' | 'decisions' | 'service' | 'evidence' | 'witnesses' | 'documents' | 'tasks';

const tabs: Array<{key: Tab; label: string; icon: string}> = [
    {key: 'overview', label: 'Overview', icon: 'fa fa-dashboard'},
    {key: 'timeline', label: 'Timeline', icon: 'fa fa-history'},
    {key: 'docket', label: 'Court docket', icon: 'fa fa-calendar-check-o'},
    {key: 'pleadings', label: 'Pleadings & applications', icon: 'fa fa-file-text-o'},
    {key: 'hearings', label: 'Hearings & proceedings', icon: 'fa fa-gavel'},
    {key: 'decisions', label: 'Orders & rulings', icon: 'fa fa-balance-scale'},
    {key: 'service', label: 'Service of process', icon: 'fa fa-envelope-open-o'},
    {key: 'evidence', label: 'Evidence & exhibits', icon: 'fa fa-archive'},
    {key: 'witnesses', label: 'Witnesses', icon: 'fa fa-users'},
    {key: 'documents', label: 'Documents & e-filing', icon: 'fa fa-files-o'},
    {key: 'tasks', label: 'Tasks & deadlines', icon: 'fa fa-tasks'},
];

export default function Show({litigationId, canUpdate}: {litigationId: number; canUpdate: boolean}): JSX.Element {
    const {auth} = usePage<{auth: {user: any}}>().props;
    const token = auth?.user?.token ?? auth?.user?.api_token;
    const permissions: string[] = auth?.user?.user_permissions ?? [];
    const canReadEvidence = permissions.includes('evidence_read');
    const canReadWitnesses = permissions.includes('witness_read');
    const canReadDocket = permissions.includes('docket_read');
    const [record, setRecord] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [active, setActive] = useState<Tab>(() => {
        if (typeof window === 'undefined') return 'overview';
        const requested = new URLSearchParams(window.location.search).get('tab') as Tab | null;
        return requested && tabs.some(tab => tab.key === requested) ? requested : 'overview';
    });
    const [showForm, setShowForm] = useState(false);
    const [editingRecord, setEditingRecord] = useState<any | null>(null);
    const [showCaseForm, setShowCaseForm] = useState(false);
    const [closingCase, setClosingCase] = useState(false);

    async function load() {
        setLoading(true);
        try {
            const response = await makeGetRequest(`/api/litigation/${litigationId}`, {token});
            setRecord(response.data?.result ?? response.data);
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Unable to load litigation workspace');
        } finally { setLoading(false); }
    }

    useEffect(() => { load(); }, [litigationId, token]);
    const documents = record?.matter?.documents ?? [];
    const team = useMemo(() => {
        const users = [record?.matter?.attorney, ...(record?.matter?.team_members?.map((member: any) => member.user) ?? [])].filter(Boolean);
        return users.filter((user: any, index: number) => users.findIndex((candidate: any) => candidate.id === user.id) === index);
    }, [record]);

    function editRecord(item: any) {
        setEditingRecord(item);
        setShowForm(true);
    }

    async function deleteRecord(item: any) {
        const endpoint = recordEndpoint(active);
        if (!endpoint || !confirm(`Delete this ${recordName(active)}?`)) return;
        try {
            await makeDeleteRequest(`/api/litigation/${record.id}/${endpoint}/${item.id}`, {token});
            notify.toastSuccessMessage(`${label(recordName(active))} deleted`);
            await load();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || `Unable to delete ${recordName(active)}`);
        }
    }

    async function closeCase() {
        if (!confirm('Close this litigation case? The linked matter will remain unchanged.')) return;
        setClosingCase(true);
        try {
            await makePutRequest(`/api/litigation/${record.id}`, {status: 'closed'}, {token});
            notify.toastSuccessMessage('Litigation case closed');
            await load();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Unable to close litigation case');
        } finally { setClosingCase(false); }
    }

    if (loading) return <MainLayout><AppPageHeader title="Litigation workspace" subtitle="Loading" /><div className="box box-body text-center py-16">Loading…</div></MainLayout>;
    if (!record) return <MainLayout><AppPageHeader title="Litigation workspace" subtitle="Unavailable" /><div className="box box-body">Litigation record not found.</div></MainLayout>;

    return <MainLayout>
        <AppPageHeader title={record.case_title} subtitle={`${record.case_number} · ${record.court}`} />
        {canUpdate ? <div className="mb-4 flex flex-wrap justify-end gap-2" aria-label="Litigation case actions"><button type="button" className="ti-btn ti-btn-primary" onClick={() => setShowCaseForm(true)}><i className="fa fa-pencil me-2" />Edit litigation</button>{record.status !== 'closed' ? <button type="button" className="ti-btn ti-btn-danger" onClick={closeCase} disabled={closingCase}><i className={`fa ${closingCase ? 'fa-spinner fa-spin' : 'fa-lock'} me-2`} />{closingCase ? 'Closing...' : 'Close litigation'}</button> : null}</div> : null}
        <div className="mb-5 flex flex-wrap items-center justify-between gap-3 rounded-xl bg-primary px-5 py-4 text-white">
            <div><div className="text-sm opacity-80">Linked matter</div><Link className="font-semibold text-white underline" href={`/matters/${record.client_matter_id}`}>{record.matter?.reference_number} — {record.matter?.client?.name}</Link></div>
            <div className="flex flex-wrap items-center gap-5 text-sm"><div><span className="opacity-70">Type</span><div className="font-semibold">{record.case_type}</div></div><div><span className="opacity-70">Status</span><div className="font-semibold">{label(record.status)}</div></div><div><span className="opacity-70">Filed</span><div className="font-semibold">{date(record.filing_date)}</div></div></div>
        </div>
        <div className="box">
            <div className="border-b overflow-x-auto"><nav className="flex min-w-max px-3">{tabs.filter(tab => (tab.key !== 'evidence' || canReadEvidence) && (tab.key !== 'witnesses' || canReadWitnesses) && (tab.key !== 'docket' || canReadDocket)).map(tab => <button key={tab.key} onClick={() => { setActive(tab.key); setShowForm(false); setEditingRecord(null); }} className={`px-4 py-4 text-sm font-medium border-b-2 ${active === tab.key ? 'border-primary text-primary' : 'border-transparent text-gray-500'}`}><i className={`${tab.icon} me-2`} />{tab.label}</button>)}</nav></div>
            <div className="box-body">
                <div className="mb-5 flex items-center justify-between"><h4 className="text-lg font-semibold">{tabs.find(tab => tab.key === active)?.label}</h4>{canUpdate && ['pleadings', 'hearings', 'decisions', 'service'].includes(active) ? <button type="button" className="ti-btn ti-btn-primary" onClick={() => { setEditingRecord(null); setShowForm(true); }}><i className="fa fa-plus me-2" />Add record</button> : null}</div>
                {active === 'overview' ? <Overview record={record} /> : null}
                {active === 'timeline' ? <TimelineWorkspace record={record} team={team} token={token} /> : null}
                {active === 'docket' ? <DocketWorkspace record={record} documents={documents} team={team} token={token} /> : null}
                {active === 'pleadings' ? <Pleadings items={record.pleadings ?? []} canManage={canUpdate} onEdit={editRecord} onDelete={deleteRecord} /> : null}
                {active === 'hearings' ? <Hearings items={record.proceedings ?? []} canManage={canUpdate} onEdit={editRecord} onDelete={deleteRecord} /> : null}
                {active === 'decisions' ? <Decisions items={record.decisions ?? []} canManage={canUpdate} onEdit={editRecord} onDelete={deleteRecord} /> : null}
                {active === 'service' ? <ServiceItems items={record.service_processes ?? []} canManage={canUpdate} onEdit={editRecord} onDelete={deleteRecord} /> : null}
                {active === 'evidence' ? <EvidenceWorkspace record={record} documents={documents} team={team} token={token} /> : null}
                {active === 'witnesses' ? <WitnessWorkspace record={record} documents={documents} team={team} token={token} /> : null}
                {active === 'documents' ? <Documents documents={documents} filings={record.matter?.e_filings ?? []} token={token} /> : null}
                {active === 'tasks' ? <Tasks items={record.matter?.tasks ?? []} /> : null}
            </div>
        </div>
        {showForm ? <RecordModal tab={active} record={record} editing={editingRecord} documents={documents} team={team} token={token} onClose={() => { setShowForm(false); setEditingRecord(null); }} onSaved={() => { setShowForm(false); setEditingRecord(null); load(); }} /> : null}
        {showCaseForm ? <CaseEditModal record={record} token={token} onClose={() => setShowCaseForm(false)} onSaved={() => { setShowCaseForm(false); load(); }} /> : null}
    </MainLayout>;
}

function CaseEditModal({record, token, onClose, onSaved}: any): JSX.Element {
    const [form, setForm] = useState({
        court: record.court ?? '', case_number: record.case_number ?? '', case_title: record.case_title ?? '',
        case_type: record.case_type ?? '', filing_date: dateInput(record.filing_date), status: record.status ?? 'active', notes: record.notes ?? '',
    });
    const [submitting, setSubmitting] = useState(false);
    async function submit(event: FormEvent) {
        event.preventDefault();
        setSubmitting(true);
        try {
            await makePutRequest(`/api/litigation/${record.id}`, {...form, filing_date: form.filing_date || null}, {token});
            notify.toastSuccessMessage('Litigation case updated');
            onSaved();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Unable to update litigation case');
        } finally { setSubmitting(false); }
    }
    const input = (key: keyof typeof form, type = 'text') => <input required={['court', 'case_number', 'case_title', 'case_type'].includes(key)} type={type} className="ti-form-input" value={form[key]} onChange={event => setForm({...form, [key]: event.target.value})} />;
    return <Modal open={true} onClose={onClose} title="Edit litigation case" maxWidthClassName="max-w-3xl" bodyClassName="max-h-[75vh] overflow-y-auto"
                  footer={<><button type="button" className="ti-btn ti-btn-light" onClick={onClose} disabled={submitting}>Cancel</button><button type="submit" form="litigation-case-form" className="ti-btn ti-btn-primary" disabled={submitting}>{submitting ? 'Saving...' : 'Update case'}</button></>}>
        <form id="litigation-case-form" onSubmit={submit} className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <Field label="Court or tribunal">{input('court')}</Field><Field label="Case number">{input('case_number')}</Field>
            <Field label="Case title">{input('case_title')}</Field><Field label="Case type or category">{input('case_type')}</Field>
            <Field label="Filing date">{input('filing_date', 'date')}</Field><Field label="Litigation status"><select required className="ti-form-input" value={form.status} onChange={event => setForm({...form, status: event.target.value})}>{['pre_filing', 'active', 'stayed', 'appealed', 'concluded', 'closed'].map(value => <option key={value} value={value}>{label(value)}</option>)}</select></Field>
            <div className="sm:col-span-2"><Field label="Notes"><textarea rows={4} className="ti-form-input" value={form.notes} onChange={event => setForm({...form, notes: event.target.value})} /></Field></div>
        </form>
    </Modal>;
}

function Overview({record}: {record: any}): JSX.Element {
    const parties = [{name: record.matter?.client?.name, role: 'Client'}, ...(record.matter?.opposing_parties ?? []).map((party: any) => ({name: party.opposing_party, role: 'Opposing party'})), ...(record.parties ?? [])];
    return <div className="grid grid-cols-1 gap-5 lg:grid-cols-3">
        <div className="box border col-span-1 lg:col-span-2"><div className="box-header"><h5 className="box-title">Case details</h5></div><div className="box-body grid grid-cols-2 gap-5 text-sm"><Detail label="Court or tribunal" value={record.court} /><Detail label="Case number" value={record.case_number} /><Detail label="Case title" value={record.case_title} /><Detail label="Category" value={record.case_type} /><Detail label="Filing date" value={date(record.filing_date)} /><Detail label="Litigation status" value={label(record.status)} /><div className="col-span-2"><Detail label="Notes" value={record.notes || 'No notes recorded.'} /></div></div></div>
        <div className="box border"><div className="box-header"><h5 className="box-title">At a glance</h5></div><div className="box-body space-y-3"><Metric label="Pleadings" value={record.pleadings?.length ?? 0} /><Metric label="Hearings" value={record.proceedings?.length ?? 0} /><Metric label="Decisions" value={record.decisions?.length ?? 0} /><Metric label="Service records" value={record.service_processes?.length ?? 0} /><Metric label="Evidence" value={record.evidence_records_count ?? 0} />{record.witnesses_count !== undefined ? <Metric label="Witnesses" value={record.witnesses_count} /> : null}<Metric label="Open tasks" value={(record.matter?.tasks ?? []).filter((task: any) => !['completed', 'cancelled'].includes(task.status)).length} /></div></div>
        <div className="box border lg:col-span-2"><div className="box-header"><h5 className="box-title">Parties</h5></div><div className="box-body divide-y">{parties.map((party: any, index: number) => <div key={`${party.name}-${index}`} className="flex justify-between py-3 first:pt-0"><span className="font-medium">{party.name}</span><span className="text-gray-500">{label(party.role)}</span></div>)}</div></div>
        <div className="box border"><div className="box-header"><h5 className="box-title">Assigned legal team</h5></div><div className="box-body space-y-3"><div><div className="font-medium">{record.matter?.attorney?.name}</div><div className="text-xs text-gray-500">Responsible attorney</div></div>{(record.matter?.team_members ?? []).map((member: any) => <div key={member.id}><div className="font-medium">{member.user?.name}</div><div className="text-xs text-gray-500">{member.role}</div></div>)}</div></div>
    </div>;
}

type RecordListProps = {items: any[]; canManage: boolean; onEdit: (item: any) => void; onDelete: (item: any) => void};

function Pleadings({items, canManage, onEdit, onDelete}: RecordListProps): JSX.Element {
    const headers = ['Type', 'Date', 'Status', 'Court reference', 'Document', 'Responsible lawyer'];
    if (canManage) headers.push('Actions');
    return <Table empty="No pleadings or applications recorded." headers={headers} rows={items.map(item => {
        const row: any[] = [label(item.document_type), date(item.filing_or_preparation_date), label(item.filing_status), item.court_reference || '—', item.document?.title || '—', item.responsible_lawyer?.name || '—'];
        if (canManage) row.push(<RecordActions key={`pleading-${item.id}`} item={item} onEdit={onEdit} onDelete={onDelete} />);
        return row;
    })} />;
}

function Hearings({items, canManage, onEdit, onDelete}: RecordListProps): JSX.Element {
    return <div className="space-y-4">{items.length === 0 ? <Empty text="No hearings or proceedings recorded." /> : items.map(item => <div key={item.id} className="rounded-lg border p-4">
        <div className="flex flex-wrap justify-between gap-3"><div><h5 className="font-semibold">{item.calendar_event?.title}</h5><p className="text-sm text-gray-500">{label(item.hearing_type)} · {dateTime(item.calendar_event?.starts_at)} · {item.calendar_event?.location}</p></div><div className="flex items-center gap-2"><span className="badge bg-primary/10 text-primary">{label(item.hearing_status)}</span>{canManage ? <RecordActions item={item} onEdit={onEdit} onDelete={onDelete} /> : null}</div></div>
        {item.proceedings_notes ? <p className="mt-3 text-sm"><strong>Proceedings:</strong> {item.proceedings_notes}</p> : null}{item.outcome ? <p className="mt-2 text-sm"><strong>Outcome:</strong> {item.outcome}</p> : null}{item.subsequent_directions ? <p className="mt-2 text-sm"><strong>Directions:</strong> {item.subsequent_directions}</p> : null}
        {(item.witness_appearances ?? []).length ? <div className="mt-4 border-t pt-3"><h6 className="mb-2 text-sm font-semibold">Scheduled witnesses</h6><div className="grid grid-cols-1 gap-2 md:grid-cols-2">{item.witness_appearances.map((appearance: any) => <div key={appearance.id} className="rounded bg-gray-50 p-2 text-sm dark:bg-bodybg"><div className="flex items-center justify-between gap-2"><strong>{appearance.witness?.profile?.full_name}</strong><span className="badge bg-primary/10 text-primary">{label(appearance.appearance_status)}</span></div><div className="mt-1 text-xs text-gray-500">{dateTime(appearance.expected_appearance_at)} · {appearance.participation_type || 'Participation not specified'}{appearance.has_availability_conflict ? <span className="ms-2 text-danger">Availability conflict</span> : null}</div></div>)}</div></div> : null}
        {(item.witness_examinations ?? []).length ? <div className="mt-4 border-t pt-3"><h6 className="mb-2 text-sm font-semibold">Examination records</h6><div className="space-y-2">{item.witness_examinations.map((examination: any) => <div key={examination.id} className="rounded bg-gray-50 p-2 text-sm dark:bg-bodybg"><strong>{examination.witness?.profile?.full_name}</strong> · {label(examination.examination_type)}<div className="text-xs text-gray-500">{dateTime(examination.examination_date)} · {examination.examining_lawyer?.name ?? 'Examining lawyer not recorded'} · {label(examination.status)}</div></div>)}</div></div> : null}
    </div>)}</div>;
}

function Decisions({items, canManage, onEdit, onDelete}: RecordListProps): JSX.Element {
    return <div className="space-y-4">{items.length === 0 ? <Empty text="No court orders, rulings, or judgments recorded." /> : items.map(item => <div key={item.id} className="rounded-lg border p-4"><div className="flex flex-wrap items-center justify-between gap-3"><h5 className="font-semibold">{label(item.decision_type)}</h5><div className="flex items-center gap-2"><span className="text-sm text-gray-500">{date(item.decision_date)}</span>{canManage ? <RecordActions item={item} onEdit={onEdit} onDelete={onDelete} /> : null}</div></div><p className="mt-3 text-sm">{item.summary}</p>{item.compliance_requirements ? <div className="mt-3 rounded bg-warning/10 p-3 text-sm"><strong>Compliance:</strong> {item.compliance_requirements} {item.compliance_due_date ? `(due ${date(item.compliance_due_date)})` : ''}{item.compliance_task ? <span className="ms-2 badge bg-warning/20 text-warning">Task created</span> : null}</div> : null}</div>)}</div>;
}

function ServiceItems({items, canManage, onEdit, onDelete}: RecordListProps): JSX.Element {
    const headers = ['Document', 'Party served', 'Status', 'Required by', 'Served', 'Method', 'Proof'];
    if (canManage) headers.push('Actions');
    return <Table empty="No service-of-process history recorded." headers={headers} rows={items.map(item => {
        const row: any[] = [item.document?.title, `${item.party_name}${item.party_role ? ` (${item.party_role})` : ''}`, label(item.service_status), date(item.required_by), dateTime(item.served_at), item.service_method || '—', item.proof_document?.title || '—'];
        if (canManage) row.push(<RecordActions key={`service-${item.id}`} item={item} onEdit={onEdit} onDelete={onDelete} />);
        return row;
    })} />;
}

function RecordActions({item, onEdit, onDelete}: {item: any; onEdit: (item: any) => void; onDelete: (item: any) => void}): JSX.Element {
    return <div className="flex justify-end gap-1"><button type="button" className="h-8 w-8 rounded-full p-0 ti-btn ti-btn-soft-primary" title="Edit" onClick={() => onEdit(item)}><i className="fa fa-pencil" /></button><button type="button" className="h-8 w-8 rounded-full p-0 ti-btn ti-btn-soft-danger" title="Delete" onClick={() => onDelete(item)}><i className="fa fa-trash" /></button></div>;
}
function Documents({documents, filings, token}: {documents: any[]; filings: any[]; token?: string}): JSX.Element {
    const [openingDocument, setOpeningDocument] = useState<number | null>(null);

    async function viewDocument(item: any) {
        if (!item.current_version?.id || openingDocument) return;
        const previewWindow = window.open('', '_blank');
        setOpeningDocument(item.id);
        try {
            const response = await axios.get(`/api/documents/${item.id}/versions/${item.current_version.id}`, {
                responseType: 'blob',
                headers: token ? {Authorization: `Bearer ${token}`} : {},
            });
            const url = URL.createObjectURL(response.data);
            if (previewWindow) {
                previewWindow.opener = null;
                previewWindow.location.href = url;
            } else {
                const link = document.createElement('a');
                link.href = url;
                link.target = '_blank';
                link.rel = 'noopener noreferrer';
                link.click();
            }
            window.setTimeout(() => URL.revokeObjectURL(url), 60000);
        } catch (error: any) {
            previewWindow?.close();
            notify.toastErrorMessage(error?.response?.data?.message || 'Unable to open document');
        } finally {
            setOpeningDocument(null);
        }
    }

    return <div className="grid grid-cols-1 gap-5 lg:grid-cols-2"><div><h5 className="mb-3 font-semibold">Matter documents</h5><Table empty="No matter documents." headers={['Title', 'Type', 'Active version', 'Actions']} rows={documents.map(item => [item.title, label(item.document_type), documentVersion(item), <button key={`view-${item.id}`} type="button" onClick={() => viewDocument(item)} disabled={!item.current_version?.id || openingDocument === item.id} className="hs-tooltip-toggle h-8 w-8 rounded-full p-0 ti-btn ti-btn-soft-primary" title="View document"><i className={`fa ${openingDocument === item.id ? 'fa-spinner fa-spin' : 'fa-eye'}`} /></button>])} /></div><div><h5 className="mb-3 font-semibold">Court e-filings</h5><Table empty="No e-filings." headers={['Provider', 'Jurisdiction', 'Status', 'Confirmation']} rows={filings.map(item => [item.provider, item.jurisdiction, label(item.status), item.confirmation_number || '—'])} /></div></div>;
}
function Tasks({items}: {items: any[]}): JSX.Element { return <Table empty="No tasks or deadlines for this matter." headers={['Task', 'Type', 'Due', 'Status', 'Assigned to']} rows={items.map(item => [item.title, label(item.task_type), date(item.due_date), label(item.status), item.assigned_to?.name || '—'])} />; }

function RecordModal({tab, record, editing, documents, team, token, onClose, onSaved}: any): JSX.Element {
    const [form, setForm] = useState(() => recordFormDefaults(tab, record, editing));
    const [submitting, setSubmitting] = useState(false);
    const endpoint = recordEndpoint(tab);
    async function submit(event: FormEvent) {
        event.preventDefault();
        const payload = Object.fromEntries(Object.entries(form).map(([key, value]) => [key, value === '' ? null : ['document_id', 'proof_document_id', 'responsible_lawyer_id', 'assigned_to'].includes(key) && value ? Number(value) : value]));
        setSubmitting(true);
        try {
            const url = `/api/litigation/${record.id}/${endpoint}${editing ? `/${editing.id}` : ''}`;
            if (editing) await makePutRequest(url, payload, {token});
            else await makePostRequest(url, payload, {token});
            notify.toastSuccessMessage(`Litigation record ${editing ? 'updated' : 'added'}`);
            onSaved();
        } catch (error: any) {
            notify.toastErrorMessage(error?.response?.data?.message || 'Unable to save record');
        } finally { setSubmitting(false); }
    }
    const input = (key: string, type = 'text') => <input type={type} className="ti-form-input" value={form[key] ?? ''} onChange={event => setForm({...form, [key]: event.target.value})} />;
    const textarea = (key: string, rows = 3) => <textarea rows={rows} className="ti-form-input" value={form[key] ?? ''} onChange={event => setForm({...form, [key]: event.target.value})} />;
    const selectDocument = (key: string, required = false) => <select required={required} className="ti-form-input" value={form[key]} onChange={event => setForm({...form, [key]: event.target.value})}><option value="">None</option>{documents.map((document: any) => <option key={document.id} value={document.id}>{document.title}</option>)}</select>;
    const action = editing ? 'Edit' : 'Add';
    const modalTitle = tab === 'pleadings' ? `${action} pleading or application` : tab === 'hearings' ? `${action} hearing or proceeding` : tab === 'decisions' ? `${action} court order or ruling` : `${action} service-of-process record`;
    return <Modal open={true} onClose={onClose} title={modalTitle} maxWidthClassName="max-w-3xl" bodyClassName="max-h-[75vh] overflow-y-auto"
                  footer={<><button type="button" className="ti-btn ti-border" onClick={onClose} disabled={submitting}>Cancel</button><button type="submit" form="litigation-record-form" className="ti-btn ti-btn-primary" disabled={submitting}>{submitting ? 'Saving...' : editing ? 'Update record' : 'Save record'}</button></>}>
        <form id="litigation-record-form" onSubmit={submit} className="space-y-5"><div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            {tab === 'pleadings' ? <><Field label="Document type"><select className="ti-form-input" value={form.document_type} onChange={event => setForm({...form, document_type: event.target.value})}>{['plaint', 'petition', 'written_statement_of_defence', 'affidavit', 'notice_of_motion', 'application', 'written_submissions', 'other'].map(value => <option key={value} value={value}>{label(value)}</option>)}</select></Field><Field label="Preparation / filing date">{input('filing_or_preparation_date', 'date')}</Field><Field label="Filing status"><select className="ti-form-input" value={form.filing_status} onChange={event => setForm({...form, filing_status: event.target.value})}>{['draft', 'prepared', 'filed', 'accepted', 'rejected', 'withdrawn'].map(value => <option key={value} value={value}>{label(value)}</option>)}</select></Field><Field label="Existing document">{selectDocument('document_id')}</Field><Field label="Court reference">{input('court_reference')}</Field><Field label="Responsible lawyer"><select className="ti-form-input" value={form.responsible_lawyer_id} onChange={event => setForm({...form, responsible_lawyer_id: event.target.value})}><option value="">None</option>{team.map((user: any) => <option key={user.id} value={user.id}>{user.name}</option>)}</select></Field></> : null}
            {tab === 'pleadings' ? <div className="sm:col-span-2"><Field label="Notes">{textarea('notes')}</Field></div> : null}
            {tab === 'hearings' ? <><Field label="Hearing title">{input('title')}</Field><Field label="Hearing type">{input('hearing_type')}</Field><Field label="Starts at">{input('starts_at', 'datetime-local')}</Field><Field label="Ends at">{input('ends_at', 'datetime-local')}</Field><Field label="Court">{input('court')}</Field><Field label="Status"><select className="ti-form-input" value={form.hearing_status} onChange={event => setForm({...form, hearing_status: event.target.value})}>{['scheduled', 'adjourned', 'completed', 'cancelled'].map(value => <option key={value} value={value}>{label(value)}</option>)}</select></Field><div className="sm:col-span-2"><Field label="Proceedings notes">{textarea('proceedings_notes')}</Field></div><div className="sm:col-span-2"><Field label="Outcome">{textarea('outcome')}</Field></div><div className="sm:col-span-2"><Field label="Subsequent directions">{textarea('subsequent_directions')}</Field></div></> : null}
            {tab === 'decisions' ? <><Field label="Decision type"><select className="ti-form-input" value={form.decision_type} onChange={event => setForm({...form, decision_type: event.target.value})}>{['court_order', 'ruling', 'judgment', 'consent_order', 'other'].map(value => <option key={value} value={value}>{label(value)}</option>)}</select></Field><Field label="Decision date">{input('decision_date', 'date')}</Field><Field label="Associated document">{selectDocument('document_id')}</Field><Field label="Compliance due date">{input('compliance_due_date', 'date')}</Field><div className="sm:col-span-2"><Field label="Summary">{textarea('summary')}</Field></div><div className="sm:col-span-2"><Field label="Compliance requirements">{textarea('compliance_requirements')}</Field></div><Field label="Assign compliance task"><select className="ti-form-input" value={form.assigned_to} onChange={event => setForm({...form, assigned_to: event.target.value})}><option value="">Responsible attorney</option>{team.map((user: any) => <option key={user.id} value={user.id}>{user.name}</option>)}</select></Field></> : null}
            {tab === 'service' ? <><Field label="Document requiring service">{selectDocument('document_id', true)}</Field><Field label="Party to serve">{input('party_name')}</Field><Field label="Party role">{input('party_role')}</Field><Field label="Status"><select className="ti-form-input" value={form.service_status} onChange={event => setForm({...form, service_status: event.target.value})}>{['pending', 'attempted', 'served', 'failed', 'waived'].map(value => <option key={value} value={value}>{label(value)}</option>)}</select></Field><Field label="Required by">{input('required_by', 'date')}</Field><Field label="Served at">{input('served_at', 'datetime-local')}</Field><Field label="Method">{input('service_method')}</Field><Field label="Proof-of-service document">{selectDocument('proof_document_id')}</Field><div className="sm:col-span-2"><Field label="Details">{textarea('service_details')}</Field></div></> : null}
        </div></form>
    </Modal>;
}

function recordEndpoint(tab: Tab): string | null {
    if (tab === 'pleadings') return 'pleadings';
    if (tab === 'hearings') return 'proceedings';
    if (tab === 'decisions') return 'decisions';
    if (tab === 'service') return 'service-processes';
    return null;
}

function recordName(tab: Tab): string {
    if (tab === 'pleadings') return 'pleading or application';
    if (tab === 'hearings') return 'hearing or proceeding';
    if (tab === 'decisions') return 'court order or ruling';
    return 'service-of-process record';
}

function recordFormDefaults(tab: Tab, record: any, editing: any): any {
    if (tab === 'pleadings') return {
        document_type: editing?.document_type ?? 'plaint', filing_status: editing?.filing_status ?? 'draft',
        filing_or_preparation_date: dateInput(editing?.filing_or_preparation_date), document_id: editing?.document_id ?? '',
        court_reference: editing?.court_reference ?? '', responsible_lawyer_id: editing?.responsible_lawyer_id ?? '', notes: editing?.notes ?? '',
    };
    if (tab === 'hearings') return {
        title: editing?.calendar_event?.title ?? '', hearing_type: editing?.hearing_type ?? 'mention',
        starts_at: dateTimeInput(editing?.calendar_event?.starts_at), ends_at: dateTimeInput(editing?.calendar_event?.ends_at),
        court: editing?.calendar_event?.location ?? record.court, hearing_status: editing?.hearing_status ?? 'scheduled',
        proceedings_notes: editing?.proceedings_notes ?? '', outcome: editing?.outcome ?? '', subsequent_directions: editing?.subsequent_directions ?? '',
    };
    if (tab === 'decisions') return {
        decision_type: editing?.decision_type ?? 'court_order', decision_date: dateInput(editing?.decision_date),
        summary: editing?.summary ?? '', document_id: editing?.document_id ?? '',
        compliance_requirements: editing?.compliance_requirements ?? '', compliance_due_date: dateInput(editing?.compliance_due_date),
        assigned_to: editing?.compliance_task?.assigned_to ?? '',
    };
    return {
        document_id: editing?.document_id ?? '', proof_document_id: editing?.proof_document_id ?? '',
        party_name: editing?.party_name ?? '', party_role: editing?.party_role ?? '',
        service_status: editing?.service_status ?? 'pending', required_by: dateInput(editing?.required_by),
        served_at: dateTimeInput(editing?.served_at), service_method: editing?.service_method ?? '', service_details: editing?.service_details ?? '',
    };
}

function dateInput(value?: string): string { return value ? String(value).slice(0, 10) : ''; }
function dateTimeInput(value?: string): string {
    if (!value) return '';
    const parsed = new Date(value);
    return new Date(parsed.getTime() - parsed.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
}

function Table({headers, rows, empty}: {headers: string[]; rows: any[][]; empty: string}): JSX.Element { return <div className="table-responsive"><table className="table whitespace-nowrap min-w-full"><thead><tr>{headers.map(header => <th key={header}>{header}</th>)}</tr></thead><tbody>{rows.length ? rows.map((row, index) => <tr key={index}>{row.map((cell, cellIndex) => <td key={cellIndex}>{cell ?? '—'}</td>)}</tr>) : <tr><td colSpan={headers.length}><Empty text={empty} /></td></tr>}</tbody></table></div>; }
function Empty({text}: {text: string}): JSX.Element { return <div className="py-8 text-center text-gray-500">{text}</div>; }
function Detail({label: title, value}: {label: string; value: any}): JSX.Element { return <div><div className="text-xs uppercase tracking-wide text-gray-500">{title}</div><div className="mt-1 font-medium">{value || '—'}</div></div>; }
function Metric({label: title, value}: {label: string; value: number}): JSX.Element { return <div className="flex justify-between rounded-lg bg-gray-50 px-3 py-2 dark:bg-bodybg"><span>{title}</span><strong>{value}</strong></div>; }
function Field({label: title, children}: {label: string; children: React.ReactNode}): JSX.Element { return <label className="block"><span className="ti-form-label">{title}</span>{children}</label>; }
function label(value: string = ''): string { return value.replaceAll('_', ' ').replace(/\b\w/g, letter => letter.toUpperCase()); }
function date(value?: string): string { return value ? new Date(value).toLocaleDateString() : '—'; }
function dateTime(value?: string): string { return value ? new Date(value).toLocaleString() : '—'; }
function documentVersion(item: any): string {
    const currentVersion = item.current_version;
    if (!currentVersion) return '—';
    const version = typeof currentVersion === 'object' ? currentVersion.version : currentVersion;
    if (!version) return '—';
    const value = String(version);
    return value.toLowerCase().startsWith('v') ? value : `v${value}`;
}
