import { useState } from 'react';
import { router, useForm } from '@inertiajs/react';
import { Plus, Pencil, Trash2, IdCard, History, Loader2, Upload } from 'lucide-react';
import { Button } from '@/Components/ui/button';
import { Switch } from '@/Components/ui/switch';
import { useToast } from '@/Components/Toast';
import { FloatingField } from '@/Components/Proto/UI/FloatingField';
import { StatusBadge } from '@/Components/Proto/UI/StatusBadge';
import TabHistoryDialog from '@/Components/MenuCompanies/TabHistoryDialog';
import {
    Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription,
} from '@/Components/ui/dialog';

// Design-system table cell/head classes (same shell as CompanyTabPanels.DummyTable).
const TH = 'whitespace-nowrap bg-secondary/50 px-4 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground first:pl-5 last:pr-5';
const TD = 'whitespace-nowrap px-4 py-3 align-middle text-[13px] text-foreground first:pl-5 last:pr-5';
// Ghost icon action (reference: Company Context table on Create Visit Plan).
const GHOST_BTN = 'inline-grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-primary';
// Faint em-dash for empty cells.
const dash = <span className="text-muted-foreground/60">—</span>;

/**
 * CompanyCpSection — Company Contact Person / Address book, the "Address" tab on Edit
 * Company. Faithful port of legacy `listcompanycp1.php` (with bank) / `listcompanycp1nobank.php`
 * (without) / `listcompanycp1view.php` (read-only) — the three variants collapse into the
 * `showBank` + `readOnly` props here.
 *
 * Rows are read from the page's `contacts` prop; writes go to CompanyCpController through
 * their OWN endpoints. This section renders inside the company <form>, so every control is
 * type="button" and nothing here rides along with the company submit.
 */

// Salutation had no lookup table in legacy — it is a free-ish varchar(20). Same shortlist.
const SALUTATIONS = ['Mr.', 'Mrs.', 'Ms.', 'Bapak', 'Ibu'];

const BLANK = {
    AddressType: null, CompanyCPName: '', CompanyCPSalutation: '', CompanyCPDeptName: '',
    CompanyCPPosition: '', CompanyCPAddress: '', CompanyCPKecamatan: '', CompanyCPProvinsi: '',
    CompanyCPKodePos: '', CompanyCPTelephone: '', CompanyCPHandphone: '', CompanyCPEmail: '',
    IsVisit: false, BankName: '', AccountName: '', AccountNo: '', BankRelation: '', card: null,
};

// Labels verbatim from listcompanycp1.php's <th> set. 'Card' + 'IsVisit' are dropped in the
// read-only variant (legacy listcompanycp1view.php has neither), so they live in a separate group.
const BASE_COLUMNS = [
    '#', 'Address Type', 'CompanyCP Name', 'Salut.', 'DeptName', 'Position', 'Address', 'District',
    'Province', 'Zip Code', 'Telephone', 'Handphone', 'Email',
];
const EDIT_ONLY_COLUMNS = ['Card', 'IsVisit'];
const BANK_COLUMNS = ['Bank Name', 'Account Name', 'Account No', 'Bank Relation'];

// History popup columns (legacy listcompanycphistorypopup.php: Tanggal | Nama | Status |
// AddressType | CPName | Salut. | DeptName).
const HISTORY_COLUMNS = [
    { key: 'tanggal', label: 'Tanggal' },
    { key: 'user', label: 'Nama' },
    { key: 'status', label: 'Status' },
    { key: 'addressType', label: 'Address Type' },
    { key: 'name', label: 'CP Name' },
    { key: 'salutation', label: 'Salut.' },
    { key: 'dept', label: 'DeptName' },
];

function FieldError({ message }) {
    return message ? <p className="mt-1 text-xs text-destructive">{message}</p> : null;
}

// Labelled group inside the contact dialog: a hairline caption over a 2-col field grid
// (1 col on narrow screens). Keeps 17 inputs from reading as one undifferentiated wall.
function FieldGroup({ title, children }) {
    return (
        <section>
            <h3 className="m-0 mb-2.5 flex items-center gap-2 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
                {title}
                <span aria-hidden="true" className="h-px flex-1 bg-border" />
            </h3>
            <div className="grid grid-cols-1 gap-3.5 sm:grid-cols-2">{children}</div>
        </section>
    );
}

export default function CompanyCpSection({
    companyId = null, contacts = [], addressTypes = [], readOnly = false, showBank = false,
    onSaved,
}) {
    const { show: showToast } = useToast();
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState(null);   // row being edited, or null for "add"
    const [confirmRow, setConfirmRow] = useState(null);
    const [deleting, setDeleting] = useState(false);
    const [historyRow, setHistoryRow] = useState(null);   // contact whose history is open

    const form = useForm(BLANK);

    // Read-only mirrors legacy listcompanycp1view.php (13 cols): no Card, IsVisit, bank, Action.
    const columns = [
        ...BASE_COLUMNS,
        ...(readOnly ? [] : EDIT_ONLY_COLUMNS),
        ...(showBank && ! readOnly ? BANK_COLUMNS : []),
        ...(readOnly ? [] : ['Action']),
    ];

    const set = (field) => (e) => form.setData(field, e.target.value);

    const openAdd = () => {
        setEditing(null);
        form.setData(BLANK);
        form.clearErrors();
        setOpen(true);
    };

    const openEdit = (row) => {
        setEditing(row);
        form.setData({
            AddressType: row.AddressType ?? null,
            CompanyCPName: row.CompanyCPName ?? '',
            CompanyCPSalutation: row.CompanyCPSalutation ?? '',
            CompanyCPDeptName: row.CompanyCPDeptName ?? '',
            CompanyCPPosition: row.CompanyCPPosition ?? '',
            CompanyCPAddress: row.CompanyCPAddress ?? '',
            CompanyCPKecamatan: row.CompanyCPKecamatan ?? '',
            CompanyCPProvinsi: row.CompanyCPProvinsi ?? '',
            CompanyCPKodePos: row.CompanyCPKodePos ?? '',
            CompanyCPTelephone: row.CompanyCPTelephone ?? '',
            CompanyCPHandphone: row.CompanyCPHandphone ?? '',
            CompanyCPEmail: row.CompanyCPEmail ?? '',
            IsVisit: Number(row.IsVisit) === 1,
            BankName: row.BankName ?? '',
            AccountName: row.AccountName ?? '',
            AccountNo: row.AccountNo ?? '',
            BankRelation: row.BankRelation ?? '',
            card: null,   // leave empty to keep the existing card
        });
        form.clearErrors();
        setOpen(true);
    };

    // Inertia switches to multipart automatically once `card` holds a File.
    const save = () => {
        const url = editing
            ? route('companies.contacts.update', [companyId, editing.id])
            : route('companies.contacts.store', companyId);

        form.post(url, {
            preserveScroll: true,
            onSuccess: () => {
                setOpen(false);
                form.reset();
                // The row list lives in the tab's fetched payload, not in page props, so the
                // pane has to be re-fetched — a page reload alone would leave it stale.
                onSaved?.();
            },
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    const remove = () => {
        setDeleting(true);
        router.delete(route('companies.contacts.destroy', [companyId, confirmRow.id]), {
            preserveScroll: true,
            onSuccess: () => { onSaved?.(); },
            onError: () => showToast('Could not delete the contact person.', 'error'),
            onFinish: () => { setDeleting(false); setConfirmRow(null); },
        });
    };

    return (
        <div className="flex flex-col">
            <div className="-mx-3 -my-3">
                {/* Toolbar strip — count left, action right; the gray thead band below closes it off. */}
                <div className="flex items-center justify-between gap-3 px-5 py-2.5">
                    <span className="text-xs text-muted-foreground tabular-nums">
                        <b className="font-semibold text-foreground">{contacts.length}</b> contact persons
                    </span>
                    {!readOnly && (
                        <button type="button" onClick={openAdd}
                            className="inline-flex h-8 items-center gap-1.5 rounded-full border border-input bg-card px-3.5 text-[12px] font-semibold text-foreground transition-colors hover:border-primary hover:text-primary">
                            <Plus className="size-3.5" /> Add Contact Person
                        </button>
                    )}
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full border-collapse">
                        <thead>
                            <tr>
                                {columns.map((c) => (
                                    <th key={c} className={`${TH} ${c === '#' ? 'w-10 text-center' : ''}`}>{c}</th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {contacts.length === 0 ? (
                                <tr>
                                    <td colSpan={columns.length} className="px-4 py-10 text-center text-[13px] italic text-muted-foreground">
                                        Belum ada contact person untuk company ini.
                                    </td>
                                </tr>
                            ) : (
                                contacts.map((r, i) => (
                                    <tr key={r.id} className="transition-colors hover:bg-secondary/60 [&>td]:border-b [&>td]:border-border last:[&>td]:border-b-0">
                                        <td className="w-10 whitespace-nowrap px-4 py-3 text-center align-middle text-[13px] tabular-nums text-muted-foreground first:pl-5">{i + 1}</td>
                                        <td className={TD}>
                                            {/* Neutral badge only — legacy renders the type as plain
                                                text; an earlier `startsWith('Invoic')` emphasis was a
                                                fragile match (hit id 2 but not id 6 "Alias Invoicing"). */}
                                            {r.AddressTypeName ? <StatusBadge tone="neutral">{r.AddressTypeName}</StatusBadge> : dash}
                                        </td>
                                        <td className={`${TD} font-semibold`}>{r.CompanyCPName || dash}</td>
                                        <td className={TD}>{r.CompanyCPSalutation || dash}</td>
                                        <td className={TD}>{r.CompanyCPDeptName || dash}</td>
                                        <td className={TD}>{r.CompanyCPPosition || dash}</td>
                                        <td className={TD}><span className="block max-w-[240px] truncate" title={r.CompanyCPAddress}>{r.CompanyCPAddress || dash}</span></td>
                                        <td className={TD}>{r.CompanyCPKecamatan || dash}</td>
                                        <td className={TD}>{r.CompanyCPProvinsi || dash}</td>
                                        <td className={`${TD} tabular-nums`}>{r.CompanyCPKodePos || dash}</td>
                                        <td className={`${TD} tabular-nums`}>{r.CompanyCPTelephone || dash}</td>
                                        <td className={`${TD} tabular-nums`}>{r.CompanyCPHandphone || dash}</td>
                                        <td className={TD}>{r.CompanyCPEmail || dash}</td>
                                        {/* Card + IsVisit only in the editable variant (legacy read-only view omits both). */}
                                        {!readOnly && <>
                                            <td className={TD}>
                                                {r.hasCard ? (
                                                    <a href={route('companies.contacts.card', [companyId, r.id])}
                                                        className="inline-flex items-center gap-1 text-primary hover:underline">
                                                        <IdCard className="size-3.5" /> View
                                                    </a>
                                                ) : dash}
                                            </td>
                                            <td className={TD}>
                                                <StatusBadge tone={Number(r.IsVisit) === 1 ? 'success' : 'neutral'}>{Number(r.IsVisit) === 1 ? 'Yes' : 'No'}</StatusBadge>
                                            </td>
                                        </>}
                                        {showBank && ! readOnly && <>
                                            <td className={TD}>{r.BankName || dash}</td>
                                            <td className={TD}>{r.AccountName || dash}</td>
                                            <td className={`${TD} tabular-nums`}>{r.AccountNo || dash}</td>
                                            <td className={TD}>{r.BankRelation || dash}</td>
                                        </>}
                                        {!readOnly && (
                                            <td className={TD}>
                                                <div className="flex items-center gap-0.5">
                                                    <button type="button" title="Edit" aria-label="Edit" onClick={() => openEdit(r)} className={GHOST_BTN}>
                                                        <Pencil className="size-3.5" />
                                                    </button>
                                                    <button type="button" title="History" aria-label="History" onClick={() => setHistoryRow(r)} className={GHOST_BTN}>
                                                        <History className="size-3.5" />
                                                    </button>
                                                    <button type="button" title="Delete" aria-label="Delete" onClick={() => setConfirmRow(r)}
                                                        className="inline-grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive">
                                                        <Trash2 className="size-3.5" />
                                                    </button>
                                                </div>
                                            </td>
                                        )}
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Add / Edit dialog — Radix portals it out of the company <form>, so no nested form. */}
            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent className="bg-card sm:max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>{editing ? 'Edit Contact Person' : 'Add Contact Person'}</DialogTitle>
                        <DialogDescription className="text-xs">
                            Address Type, Contact Name, dan Address wajib diisi.
                        </DialogDescription>
                    </DialogHeader>

                    {/* 17 fields in one flat grid read as a wall of boxes. They are grouped into
                        labelled sections instead, and the scroll area carries its own top/bottom
                        rule so content never looks clipped where the footer starts. */}
                    <div className="-mx-6 max-h-[62vh] overflow-y-auto border-y border-border px-6 py-4">
                        <div className="flex flex-col gap-5">
                            <FieldGroup title="Kontak">
                                <div>
                                    <FloatingField as="select" label="Address Type *" value={form.data.AddressType ?? ''}
                                        onChange={(e) => form.setData('AddressType', e.target.value ? Number(e.target.value) : null)}>
                                        <option value="">Select Address Type</option>
                                        {addressTypes.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
                                    </FloatingField>
                                    <FieldError message={form.errors.AddressType} />
                                </div>
                                <div>
                                    <FloatingField as="select" label="Salutation" value={form.data.CompanyCPSalutation} onChange={set('CompanyCPSalutation')}>
                                        <option value="">Select Salutation</option>
                                        {SALUTATIONS.map((s) => <option key={s} value={s}>{s}</option>)}
                                    </FloatingField>
                                    <FieldError message={form.errors.CompanyCPSalutation} />
                                </div>
                                <div className="sm:col-span-2">
                                    <FloatingField label="Contact Name *" value={form.data.CompanyCPName} onChange={set('CompanyCPName')} />
                                    <FieldError message={form.errors.CompanyCPName} />
                                </div>
                                <div>
                                    <FloatingField label="Dept Name" value={form.data.CompanyCPDeptName} onChange={set('CompanyCPDeptName')} />
                                    <FieldError message={form.errors.CompanyCPDeptName} />
                                </div>
                                <div>
                                    <FloatingField label="Position" value={form.data.CompanyCPPosition} onChange={set('CompanyCPPosition')} />
                                    <FieldError message={form.errors.CompanyCPPosition} />
                                </div>
                            </FieldGroup>

                            <FieldGroup title="Alamat">
                                <div className="sm:col-span-2">
                                    <FloatingField as="textarea" label="Address *" value={form.data.CompanyCPAddress} onChange={set('CompanyCPAddress')} />
                                    <FieldError message={form.errors.CompanyCPAddress} />
                                </div>
                                <div>
                                    <FloatingField label="District (Kecamatan)" value={form.data.CompanyCPKecamatan} onChange={set('CompanyCPKecamatan')} />
                                    <FieldError message={form.errors.CompanyCPKecamatan} />
                                </div>
                                <div>
                                    <FloatingField label="Province (Provinsi)" value={form.data.CompanyCPProvinsi} onChange={set('CompanyCPProvinsi')} />
                                    <FieldError message={form.errors.CompanyCPProvinsi} />
                                </div>
                                <div>
                                    <FloatingField label="Zip Code" value={form.data.CompanyCPKodePos} onChange={set('CompanyCPKodePos')} />
                                    <FieldError message={form.errors.CompanyCPKodePos} />
                                </div>
                                <div>
                                    <FloatingField label="Telephone" value={form.data.CompanyCPTelephone} onChange={set('CompanyCPTelephone')} />
                                    <FieldError message={form.errors.CompanyCPTelephone} />
                                </div>
                                <div>
                                    <FloatingField label="Handphone" value={form.data.CompanyCPHandphone} onChange={set('CompanyCPHandphone')} />
                                    <FieldError message={form.errors.CompanyCPHandphone} />
                                </div>
                                <div>
                                    <FloatingField type="email" label="Email" value={form.data.CompanyCPEmail} onChange={set('CompanyCPEmail')} />
                                    <FieldError message={form.errors.CompanyCPEmail} />
                                </div>
                            </FieldGroup>

                            {showBank && (
                                <FieldGroup title="Bank">
                                    <div>
                                        <FloatingField label="Bank Name" value={form.data.BankName} onChange={set('BankName')} />
                                        <FieldError message={form.errors.BankName} />
                                    </div>
                                    <div>
                                        <FloatingField label="Account Name" value={form.data.AccountName} onChange={set('AccountName')} />
                                        <FieldError message={form.errors.AccountName} />
                                    </div>
                                    <div>
                                        <FloatingField label="Account No" value={form.data.AccountNo} onChange={set('AccountNo')} />
                                        <FieldError message={form.errors.AccountNo} />
                                    </div>
                                    <div>
                                        <FloatingField label="Bank Relation" value={form.data.BankRelation} onChange={set('BankRelation')} />
                                        <FieldError message={form.errors.BankRelation} />
                                    </div>
                                </FieldGroup>
                            )}

                            <FieldGroup title="Lampiran & Opsi">
                                <div className="sm:col-span-2">
                                    {/* Native file inputs render a browser-default "Choose File" button that
                                        ignores the design system — the real input is hidden and a styled
                                        <label> drives it. */}
                                    <span className="mb-1.5 block text-[11px] font-semibold text-muted-foreground">
                                        Business Card <span className="font-normal">(PDF / gambar, maks 1MB)</span>
                                    </span>
                                    <label className="flex cursor-pointer items-center gap-3 rounded-lg border border-dashed border-input bg-secondary/20 px-3.5 py-3 transition-colors hover:border-primary hover:bg-accent/40">
                                        <span className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg border border-input bg-card px-3 text-[12px] font-bold text-foreground">
                                            <Upload className="size-3.5" /> Pilih file
                                        </span>
                                        <span className="min-w-0 flex-1 truncate text-[12px] text-muted-foreground">
                                            {form.data.card?.name
                                                || (editing?.hasCard ? 'Kartu tersimpan — biarkan kosong untuk mempertahankannya' : 'Belum ada file dipilih')}
                                        </span>
                                        <input type="file" accept="application/pdf,image/*" className="sr-only"
                                            onChange={(e) => form.setData('card', e.target.files?.[0] ?? null)} />
                                    </label>
                                    <FieldError message={form.errors.card} />
                                </div>

                                <label className="flex min-h-11 cursor-pointer items-center justify-between gap-4 rounded-lg border border-input bg-secondary/40 px-3.5 py-2 sm:col-span-2">
                                    <span className="text-xs font-bold text-card-foreground">Mark as Visit contact (IsVisit)</span>
                                    <Switch checked={form.data.IsVisit} onCheckedChange={(v) => form.setData('IsVisit', v)} />
                                </label>
                            </FieldGroup>
                        </div>
                    </div>

                    <DialogFooter>
                        <Button type="button" onClick={save} disabled={form.processing} className="font-bold">
                            {form.processing
                                ? <><Loader2 className="mr-2 size-4 animate-spin" />Menyimpan...</>
                                : (editing ? 'Save Changes' : 'Add Contact')}
                        </Button>
                        <Button type="button" variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Delete confirmation — split footer (cancel left, destructive right). */}
            <Dialog open={confirmRow !== null} onOpenChange={(v) => !v && setConfirmRow(null)}>
                <DialogContent className="bg-card sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle>Hapus Contact Person</DialogTitle>
                        <DialogDescription className="text-xs">
                            Hapus <b className="text-foreground">{confirmRow?.CompanyCPName}</b> dari company ini?
                            Data lama tetap tersimpan di history.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter className="sm:justify-start">
                        <Button type="button" variant="outline" onClick={() => setConfirmRow(null)}>Batal</Button>
                        <Button type="button" variant="destructive" onClick={remove} disabled={deleting} className="font-bold">
                            {deleting ? <><Loader2 className="mr-2 size-4 animate-spin" />Menghapus...</> : 'Hapus'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Per-contact audit trail (companycpassignment) — legacy listcompanycphistorypopup.php. */}
            <TabHistoryDialog
                url={historyRow ? route('companies.contacts.history', [companyId, historyRow.id]) : null}
                title={historyRow ? `History — ${historyRow.CompanyCPName}` : 'History'}
                onClose={() => setHistoryRow(null)}
                columns={HISTORY_COLUMNS}
            />
        </div>
    );
}