import { useMemo, useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import { ArrowLeft, ChevronUp, Loader2, FileText } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { useToast } from '@/Components/Toast';
import { RequiredFieldsDialog } from '@/Components/Form/RequiredFieldsDialog';
import { useJumpToFirstInvalid, useRequiredFields } from '@/lib/requiredFields';
import { FloatingField } from '@/Components/Proto/UI/FloatingField';
import { MultiSelect } from '@/Components/Proto/UI/MultiSelect';
import { Pill } from '@/Components/Proto/UI/Pill';
import { Button } from '@/Components/ui/button';
import CompanyTabs from '@/Components/MenuCompanies/CompanyTabs';
import { WebsiteField } from '@/Components/MenuCompanies/WebsiteField';
import { CodeTagInput } from '@/Components/MenuCompanies/CodeTagInput';
import { CreditLimitNS } from '@/Components/MenuCompanies/CreditLimitNS';
import { MultinationalToggle } from '@/Components/MenuCompanies/MultinationalToggle';

// Edit Company — same core-field subset as Create, prefilled, in the proto's collapsible
// section-card layout. Admin editors (/companies/all) additionally see the NS/AST code fields.

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

export default function CompaniesEdit({ company, options = {}, isAdmin = false, from = null, readOnly = false }) {
    const { show: showToast } = useToast();
    const branches = options.branches ?? [];
    const divisions = options.divisions ?? [];
    const industries = options.industries ?? [];
    const categories = options.categories ?? [];
    const productCategories = options.productCategories ?? [];
    const productApplications = options.productApplications ?? [];
    const salesUsers = options.salesUsers ?? [];
    const highestValues = options.highestValues ?? [];

    // Section collapse states (proto faithful).
    const [collapse1, setCollapse1] = useState(false);
    const [collapse2, setCollapse2] = useState(false);

    // Back → the View list this Edit was opened from (?from=<scope>); default to
    // the "mine" View (companies.index) if the context is missing/unknown.
    const FROM_ROUTE = {
        mine: 'companies.index', others: 'companies.others', all: 'companies.all',
        headDept: 'companies.head-dept', sm: 'companies.sm', cs: 'companies.cs',
    };
    const backRoute = FROM_ROUTE[from] ?? 'companies.index';

    const form = useForm({
        CompanyName: company.CompanyName ?? '',
        UserIDSales: company.UserIDSales ?? null,
        BranchID: company.BranchID ?? null,
        DivisionID: company.DivisionID ?? null,
        IndustryID: company.IndustryID ?? null,
        CompanyCategoryIDs: company.CompanyCategoryIDs ?? [],
        ProductCategoryIDs: company.ProductCategoryIDs ?? [],
        CustomerProductCategoryIDs: company.CustomerProductCategoryIDs ?? [],
        IsMultinational: Boolean(company.IsMultinational),
        CompanyTelephone: company.CompanyTelephone ?? '',
        CompanyFax: company.CompanyFax ?? '',
        CompanyWebsite: company.CompanyWebsite ?? '',
        CompanyAddress: company.CompanyAddress ?? '',
        ZipCode: company.ZipCode ?? '',
        CustomerEst: company.CustomerEst ?? '',
        CustomerSince: company.CustomerSince ?? '',
        CompanyOwner: company.CompanyOwner ?? '',
        CompanyGroup: company.CompanyGroup ?? '',
        OfficePremises: company.OfficePremises ?? '',
        FactoryPremises: company.FactoryPremises ?? '',
        OrderWithPO: Boolean(company.OrderWithPO),
        HighestValueAchieved: company.HighestValueAchieved || null,
        TermNCondQuotation: company.TermNCondQuotation ?? '',
        TermNCondSample: company.TermNCondSample ?? '',
        Remark: company.Remark ?? '',
        ASTCompanyCode: company.ASTCompanyCode ?? '',
        NSCustomerID: company.NSCustomerID ?? '',
    });

    const fkSelect = (field) => (e) => form.setData(field, e.target.value ? Number(e.target.value) : null);

    // Customer Product Category (application) is scoped to the chosen Division; changing the
    // Division re-filters the list and clears the selection (faithful to legacy showAppfromDiv).
    const customerProductCategoryOptions = productApplications.filter((a) => a.divisionId === form.data.DivisionID);
    // Company Category is scoped to the selected Division's group (legacy companycategory.GroupDivID);
    // empty when the division has no category group. Cleared on division change, like the legacy reload.
    const selectedGroupDivId = divisions.find((d) => d.id === form.data.DivisionID)?.groupDivId ?? null;
    const companyCategoryOptions = selectedGroupDivId ? categories.filter((c) => c.groupDivId === selectedGroupDivId) : [];
    const onDivisionChange = (e) => {
        form.setData('DivisionID', e.target.value ? Number(e.target.value) : null);
        form.setData('CompanyCategoryIDs', []);
        form.setData('CustomerProductCategoryIDs', []);
    };

    // Sales (account owner) is display-only here — legacy renders it readonly and just
    // round-trips company.UserIDSales on save (it is not reassigned from this form). The id
    // stays in form state so the (required) UpdateCompanyRequest rule is satisfied unchanged.
    const salesName = salesUsers.find((u) => u.id === form.data.UserIDSales)?.name ?? '';

    // Integration codes (AST/NS) are editable only when an admin opened Edit from the View
    // Company All menu (?from=all) — faithful to legacy: listcompanyeditall.php persists them
    // (inputs editable), listcompanyedit.php renders them `readonly`. update() re-derives the
    // same rule server-side, so a read-only context never writes (or clobbers) the codes.
    const canEditCodes = isAdmin && from === 'all';

    // Required fields, named the way they read on screen. Legacy's own rule set
    // (listcompanyedit.php:34) — mirrored by UpdateCompanyRequest. Sales is NOT here: it is
    // nullable and rendered read-only, so it can never be something the user must "fill in".
    const requiredSpec = useMemo(() => [
        { key: 'CompanyName', label: 'Company Name' },
        { key: 'BranchID', label: 'Branch' },
        { key: 'DivisionID', label: 'Division' },
        { key: 'IndustryID', label: 'Industry' },
        {
            key: 'CompanyCategoryIDs',
            label: 'Company Category',
            // Mirrors UpdateCompanyRequest::divisionRequiresCategory() — the
            // groupdivision.IsCompCategoryMandatory flag, shipped per division by formOptions()
            // as `categoryMandatory`. Without this the field would be demanded on every division.
            when: (d) => Boolean(divisions.find((x) => x.id === d.DivisionID)?.categoryMandatory),
        },
        { key: 'CompanyTelephone', label: 'Company Telephone' },
        { key: 'CompanyAddress', label: 'Company Address' },
        { key: 'CompanyOwner', label: 'Name of Company Owners' },
    ], [divisions]);

    const { missing, total, filledCount, showErr, reportAttempt } = useRequiredFields(requiredSpec, form.data);
    const [requiredOpen, setRequiredOpen] = useState(false);
    // Bumped only by "Isi Sekarang", so closing the dialog with Tutup leaves the page where it is.
    const [jumpAt, setJumpAt] = useState(0);
    useJumpToFirstInvalid(jumpAt);

    const jumpToFirstMissing = () => {
        setRequiredOpen(false);
        // Expand both sections first — a control inside a `hidden` section cannot be scrolled
        // to or focused, which is exactly how the browser's own validation used to fail silently.
        setCollapse1(false);
        setCollapse2(false);
        setJumpAt((n) => n + 1);
    };

    const submit = (e) => {
        e?.preventDefault();
        // Stop at the client only for EMPTY required fields — everything else (formats, lengths,
        // charset, FK existence) stays the server's call, so this can never disagree with it.
        if (missing.length > 0) {
            reportAttempt();
            setRequiredOpen(true);

            return;
        }
        form.put(route('companies.update', { company: company.id, from }), {
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    return (
        <section className="flex min-w-0 flex-col gap-4.5">
            <header className="flex items-center justify-between gap-4">
                <div>
                    <p className="m-0 mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                        <Link href={route(backRoute)} className="text-muted-foreground no-underline hover:text-primary">Companies</Link>
                        <span aria-hidden="true">›</span>
                        <span className="text-foreground">Edit Company</span>
                    </p>
                    <div className="flex items-center gap-2.5">
                        <h1 className="m-0 text-xl font-bold leading-tight text-card-foreground">Edit Company</h1>
                        {!readOnly && (
                            <span className={`inline-flex min-h-5 items-center rounded-full px-3 py-1 text-[10px] font-bold tracking-[0.02em] ${missing.length ? 'bg-danger-bg text-danger-text' : 'bg-accent text-primary'}`}>
                                {filledCount}/{total} required filled
                            </span>
                        )}
                    </div>
                </div>
                <div className="flex flex-wrap items-center justify-end gap-2">
                    <Link href={route(backRoute)} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary">
                        <ArrowLeft className="size-3.5" /> Back to List
                    </Link>
                    {readOnly ? (
                        <span className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-input bg-secondary/60 px-3.5 text-xs font-bold text-muted-foreground">Read-only</span>
                    ) : (
                        <>
                            <button type="button" onClick={() => form.reset()} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary">Reset</button>
                            <Button type="button" onClick={submit} disabled={form.processing} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105">
                                {form.processing ? <><Loader2 className="mr-1 size-4 animate-spin" />Menyimpan...</> : 'Save Changes'}
                            </Button>
                        </>
                    )}
                </div>
            </header>

            {/* noValidate: the two Save buttons used to disagree. The header one is type="button"
                and sits OUTSIDE this form, so it always reached the server; the footer one is
                type="submit", so the browser's own `required` check fired first and the request
                was never sent — no server errors, nothing for the field messages to show, and a
                collapsed section made it worse (Chrome cannot focus a hidden control, so it
                blocked the submit with no bubble at all and the button read as dead). One source
                of truth: the server validates, and both buttons take the same path. Create.jsx
                carries the identical comment and the identical attribute — keep the two in step. */}
            <form onSubmit={submit} noValidate>
                {/* READ-ONLY IS PER CARD BODY, NOT AROUND THE WHOLE FORM. A disabled
                    <fieldset> disables every descendant <button>, so the old blanket around
                    everything below also killed the two collapse toggles and all 22 Company
                    Records tab buttons + their reload/export — a CS viewer could not open a
                    single pane. Read-only must still be READABLE, and reading is exactly what
                    those buttons do. Scoping the blanket to the two card bodies gives up
                    nothing: every pane payload carries its own `readOnly` derived from the
                    same can('update', $company), and every pane write authorizes it again
                    server-side (CompanyCp/Npwp/Reference/Production/Product/…Controller).
                    Nothing a read-only viewer can reach submits this form either: both Save
                    buttons (header and footer) are rendered only when !readOnly, so the
                    <FieldError> slots below stay empty for a viewer who cannot POST. */}
                <section className="grid items-stretch gap-6 [grid-template-columns:minmax(0,1fr)_minmax(0,1fr)] max-[1180px]:grid-cols-1">

                    {/* ── Section 1: Identity & Classification ─────────────────── */}
                    <article className="flex flex-col overflow-visible rounded-xl border border-border bg-card shadow-sm">
                        <header className="grid min-h-16.5 grid-cols-[auto_1fr_auto] items-center gap-3 border-b border-border p-[18px_24px]">
                            <span className="inline-grid size-8 place-items-center rounded-md bg-accent text-[13px] font-bold tracking-[-0.01em] text-primary">1</span>
                            <div>
                                <h2 className="m-0 text-base font-semibold leading-tight tracking-[-0.005em] text-card-foreground">Identity &amp; Classification</h2>
                                <p className="mt-1 text-xs text-muted-foreground">Company identity &amp; business classification</p>
                            </div>
                            <button className="inline-grid size-7.5 place-items-center rounded-full border-0 bg-transparent font-extrabold text-muted-foreground transition-colors hover:bg-secondary hover:text-card-foreground" type="button" onClick={() => setCollapse1(!collapse1)} aria-label="Collapse identity">
                                <ChevronUp aria-hidden="true" className={`size-3.5 transition-transform${collapse1 ? ' rotate-180' : ''}`} />
                            </button>
                        </header>
                        <div className="flex-1 p-6" hidden={collapse1}>
                            <fieldset disabled={readOnly} className="contents">

                            {/* Primary Identity — 3 uniform rows, mirroring Contact & Address on
                                the right, so both section dividers sit level naturally. */}
                            <div className="[&>*+*]:mt-4">
                                <div className="mb-4 flex items-center justify-between gap-3">
                                    <h3 className="m-0 text-[13px] font-extrabold text-card-foreground">Primary Identity</h3>
                                    <Pill tone="info">Required</Pill>
                                </div>

                                <div>
                                    <FloatingField label="Company Name *" value={form.data.CompanyName} onChange={(e) => form.setData('CompanyName', e.target.value)} required invalid={showErr('CompanyName')} />
                                    <FieldError message={form.errors.CompanyName} />
                                </div>

                                <div>
                                    <FloatingField label="Sales" value={salesName} readOnly className="[&_input]:bg-secondary/60 [&_input]:cursor-not-allowed" />
                                    <FieldError message={form.errors.UserIDSales} />
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <FloatingField as="select" label="Branch *" value={form.data.BranchID ?? ''} onChange={fkSelect('BranchID')} invalid={showErr('BranchID')}>
                                            <option value="">Select Branch</option>
                                            {branches.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
                                        </FloatingField>
                                        <FieldError message={form.errors.BranchID} />
                                    </div>
                                    <div className="flex items-stretch">
                                        <MultinationalToggle checked={form.data.IsMultinational} onChange={(v) => form.setData('IsMultinational', v)} />
                                    </div>
                                </div>
                            </div>

                            {/* Business Classification */}
                            <div className="mt-6 border-t border-border pt-6 [&>*+*]:mt-4">
                                <div className="mb-4 flex items-center justify-between gap-3">
                                    <h3 className="m-0 text-[13px] font-extrabold text-card-foreground">Business Classification</h3>
                                    <Pill tone="info">Category</Pill>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <FloatingField as="select" label="Division *" value={form.data.DivisionID ?? ''} onChange={onDivisionChange} invalid={showErr('DivisionID')}>
                                            <option value="">Select Division</option>
                                            {divisions.map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}
                                        </FloatingField>
                                        <FieldError message={form.errors.DivisionID} />
                                    </div>
                                    <div>
                                        <FloatingField as="select" label="Industry *" value={form.data.IndustryID ?? ''} onChange={fkSelect('IndustryID')} invalid={showErr('IndustryID')}>
                                            <option value="">Select Industry</option>
                                            {industries.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
                                        </FloatingField>
                                        <FieldError message={form.errors.IndustryID} />
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <MultiSelect
                                            label="Company Category *"
                                            placeholder={form.data.DivisionID ? 'Select Category' : 'Select Division first'}
                                            options={companyCategoryOptions}
                                            value={form.data.CompanyCategoryIDs}
                                            onChange={(ids) => form.setData('CompanyCategoryIDs', ids)}
                                            invalid={showErr('CompanyCategoryIDs')}
                                        />
                                        <FieldError message={form.errors.CompanyCategoryIDs ?? form.errors['CompanyCategoryIDs.0']} />
                                    </div>
                                    <div>
                                        <MultiSelect
                                            label="Product Category"
                                            placeholder="Select Product Category"
                                            options={productCategories}
                                            value={form.data.ProductCategoryIDs}
                                            onChange={(ids) => form.setData('ProductCategoryIDs', ids)}
                                        />
                                        <FieldError message={form.errors.ProductCategoryIDs ?? form.errors['ProductCategoryIDs.0']} />
                                    </div>
                                </div>

                                <div>
                                    <MultiSelect
                                        label="Customer Product Category"
                                        placeholder={form.data.DivisionID ? 'Select Customer Product Category' : 'Select Division first'}
                                        options={customerProductCategoryOptions}
                                        value={form.data.CustomerProductCategoryIDs}
                                        onChange={(ids) => form.setData('CustomerProductCategoryIDs', ids)}
                                    />
                                    <FieldError message={form.errors.CustomerProductCategoryIDs ?? form.errors['CustomerProductCategoryIDs.0']} />
                                </div>
                            </div>

                            {/* Default Terms */}
                            <div className="mt-6 border-t border-border pt-6 [&>*+*]:mt-4">
                                <div className="mb-4 flex items-center justify-between gap-3">
                                    <h3 className="m-0 text-[13px] font-extrabold text-card-foreground">Default Terms</h3>
                                    <Pill tone="info">Defaults</Pill>
                                </div>
                                <label className="flex cursor-text items-center gap-3 rounded-lg border border-input p-2 focus-within:border-primary focus-within:ring-1 focus-within:ring-primary transition-colors bg-card">
                                    <div className="flex size-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
                                        <FileText className="size-4.5" />
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        <textarea
                                            rows={1}
                                            className="block w-full field-sizing-content resize-none border-0 outline-none bg-transparent p-0 text-[13px] font-medium leading-5 text-primary placeholder:text-primary focus:ring-0"
                                            placeholder="Term & Condition · Quotation"
                                            value={form.data.TermNCondQuotation}
                                            onChange={(e) => form.setData('TermNCondQuotation', e.target.value)}
                                        />
                                    </div>
                                </label>
                                <FieldError message={form.errors.TermNCondQuotation} />
                                <label className="flex cursor-text items-center gap-3 rounded-lg border border-input p-2 focus-within:border-primary focus-within:ring-1 focus-within:ring-primary transition-colors bg-card">
                                    <div className="flex size-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
                                        <FileText className="size-4.5" />
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        <textarea
                                            rows={1}
                                            className="block w-full field-sizing-content resize-none border-0 outline-none bg-transparent p-0 text-[13px] font-medium leading-5 text-primary placeholder:text-primary focus:ring-0"
                                            placeholder="Term & Condition · Sample"
                                            value={form.data.TermNCondSample}
                                            onChange={(e) => form.setData('TermNCondSample', e.target.value)}
                                        />
                                    </div>
                                </label>
                                <FieldError message={form.errors.TermNCondSample} />
                            </div>

                            {/* Integration Codes — legacy-faithful: always shown, but editable only
                                when an admin opens Edit from View Company All (?from=all). Otherwise
                                read-only (listcompanyedit.php renders these inputs `readonly`;
                                listcompanyeditall.php makes them editable and persists them). */}
                            <div className="mt-6 border-t border-border pt-6 [&>*+*]:mt-4">
                                <div className="mb-4 flex items-center justify-between gap-3">
                                    <h3 className="m-0 text-[13px] font-extrabold text-card-foreground">Integration Codes</h3>
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <CodeTagInput label="AST Company Code" value={form.data.ASTCompanyCode} onChange={(v) => form.setData('ASTCompanyCode', v)} placeholder={canEditCodes ? 'Tambah kode…' : ''} disabled={!canEditCodes} />
                                        <FieldError message={form.errors.ASTCompanyCode} />
                                    </div>
                                    <div>
                                        <CodeTagInput label="NS / Oracle Customer ID" value={form.data.NSCustomerID} onChange={(v) => form.setData('NSCustomerID', v)} placeholder={canEditCodes ? 'Tambah ID…' : ''} disabled={!canEditCodes} />
                                        <FieldError message={form.errors.NSCustomerID} />
                                    </div>
                                </div>
                            </div>
                            </fieldset>
                        </div>
                    </article>

                    {/* ── Section 2: Contact & Administrative ──────────────────── */}
                    <article className="flex flex-col overflow-visible rounded-xl border border-border bg-card shadow-sm">
                        <header className="grid min-h-16.5 grid-cols-[auto_1fr_auto] items-center gap-3 border-b border-border p-[18px_24px]">
                            <span className="inline-grid size-8 place-items-center rounded-md bg-accent text-[13px] font-bold tracking-[-0.01em] text-primary">2</span>
                            <div>
                                <h2 className="m-0 text-base font-semibold leading-tight tracking-[-0.005em] text-card-foreground">Contact &amp; Administrative</h2>
                                <p className="mt-1 text-xs text-muted-foreground">Communication, address &amp; records</p>
                            </div>
                            <button className="inline-grid size-7.5 place-items-center rounded-full border-0 bg-transparent font-extrabold text-muted-foreground transition-colors hover:bg-secondary hover:text-card-foreground" type="button" onClick={() => setCollapse2(!collapse2)} aria-label="Collapse contact">
                                <ChevronUp aria-hidden="true" className={`size-3.5 transition-transform${collapse2 ? ' rotate-180' : ''}`} />
                            </button>
                        </header>
                        <div className="flex-1 p-6" hidden={collapse2}>
                            <fieldset disabled={readOnly} className="contents">

                            {/* Contact & Address */}
                            <div className="[&>*+*]:mt-4">
                                <div className="mb-4 flex items-center justify-between gap-3">
                                    <h3 className="m-0 text-[13px] font-extrabold text-card-foreground">Contact &amp; Address</h3>
                                    <Pill tone="info">Contact</Pill>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <FloatingField label="Company Telephone *" value={form.data.CompanyTelephone} onChange={(e) => form.setData('CompanyTelephone', e.target.value)} required invalid={showErr('CompanyTelephone')} />
                                        <FieldError message={form.errors.CompanyTelephone} />
                                    </div>
                                    <div>
                                        <FloatingField label="Company Fax" value={form.data.CompanyFax} onChange={(e) => form.setData('CompanyFax', e.target.value)} />
                                        <FieldError message={form.errors.CompanyFax} />
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <WebsiteField value={form.data.CompanyWebsite} onChange={(e) => form.setData('CompanyWebsite', e.target.value)} />
                                        <FieldError message={form.errors.CompanyWebsite} />
                                    </div>
                                    <div>
                                        <FloatingField label="Zip Code" value={form.data.ZipCode} onChange={(e) => form.setData('ZipCode', e.target.value)} />
                                        <FieldError message={form.errors.ZipCode} />
                                    </div>
                                </div>

                                <div>
                                    <FloatingField as="textarea" rows={1} label="Company Address *" value={form.data.CompanyAddress} onChange={(e) => form.setData('CompanyAddress', e.target.value)} required invalid={showErr('CompanyAddress')} />
                                    <FieldError message={form.errors.CompanyAddress} />
                                </div>
                            </div>

                            {/* Business Records */}
                            <div className="mt-6 border-t border-border pt-6 [&>*+*]:mt-4">
                                <div className="mb-4 flex items-center justify-between gap-3">
                                    <h3 className="m-0 text-[13px] font-extrabold text-card-foreground">Business Records</h3>
                                    <Pill tone="info">Internal</Pill>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <FloatingField label="Established (YYYY)" value={form.data.CustomerEst} onChange={(e) => form.setData('CustomerEst', e.target.value)} />
                                        <FieldError message={form.errors.CustomerEst} />
                                    </div>
                                    <div>
                                        <FloatingField type="date" label="Customer Since" value={form.data.CustomerSince} onChange={(e) => form.setData('CustomerSince', e.target.value)} />
                                        <FieldError message={form.errors.CustomerSince} />
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <FloatingField label="Name of Company Owners *" value={form.data.CompanyOwner} onChange={(e) => form.setData('CompanyOwner', e.target.value)} required invalid={showErr('CompanyOwner')} />
                                        <FieldError message={form.errors.CompanyOwner} />
                                    </div>
                                    <div>
                                        <FloatingField label="Company Group" value={form.data.CompanyGroup} onChange={(e) => form.setData('CompanyGroup', e.target.value)} />
                                        <FieldError message={form.errors.CompanyGroup} />
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <FloatingField label="Office Premises" value={form.data.OfficePremises} onChange={(e) => form.setData('OfficePremises', e.target.value)} />
                                        <FieldError message={form.errors.OfficePremises} />
                                    </div>
                                    <div>
                                        <FloatingField label="Factory Premises" value={form.data.FactoryPremises} onChange={(e) => form.setData('FactoryPremises', e.target.value)} />
                                        <FieldError message={form.errors.FactoryPremises} />
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <FloatingField as="select" label="Highest Value Achieved" value={form.data.HighestValueAchieved ?? ''} onChange={fkSelect('HighestValueAchieved')}>
                                            <option value="">Select Value</option>
                                            {highestValues.map((h) => <option key={h.id} value={h.id}>{h.name}</option>)}
                                        </FloatingField>
                                        <FieldError message={form.errors.HighestValueAchieved} />
                                    </div>
                                    <button
                                        type="button"
                                        onClick={() => form.setData('OrderWithPO', !form.data.OrderWithPO)}
                                        className={`flex min-h-11 cursor-pointer items-center justify-between gap-4 rounded-md border px-3.5 py-2 text-left transition-colors ${form.data.OrderWithPO ? 'border-success/30 bg-success-bg/60' : 'border-input bg-secondary/40 hover:border-primary'}`}
                                    >
                                        <span className="text-xs font-bold text-card-foreground">Order with PO required</span>
                                        {/* mini switch — same size as MultinationalToggle's (h-4 w-7) */}
                                        <span className={`relative ml-auto h-4 w-7 shrink-0 rounded-full transition-colors ${form.data.OrderWithPO ? 'bg-success' : 'bg-input'}`} aria-hidden="true">
                                            <span className={`absolute left-0.5 top-0.5 size-3 rounded-full bg-white shadow-[0_1px_2px_rgb(0_0_0/0.15)] transition-transform ${form.data.OrderWithPO ? 'translate-x-3' : ''}`}></span>
                                        </span>
                                    </button>
                                </div>

                                <div>
                                    <FloatingField as="textarea" rows={2} label="Remark" value={form.data.Remark} onChange={(e) => form.setData('Remark', e.target.value)} />
                                    <FieldError message={form.errors.Remark} />
                                </div>

                                <CreditLimitNS companyId={company.id} nsCustomerId={form.data.NSCustomerID} />
                            </div>
                            </fieldset>
                        </div>
                    </article>
                </section>

                {/* Section 3: Company Records — faithful port of legacy listcompanyedit.php
                    vertical pill-tabs (no iframe). The Address tab is live (companycp);
                    the remaining panes are still dummy templates. */}
                {/* listcompanyheaddeptedit.php is the one Company Edit variant that omits the
                    Complain pane; the other three carry all 14. `from` is the originating
                    list scope, so it is what tells the two apart. */}
                <CompanyTabs companyId={company.id} preset={from === 'headDept' ? 'companyHead' : 'company'} />

                {!readOnly && (
                <div className="mt-6 flex flex-wrap items-center gap-2.5 border-t border-input pb-2 pt-4">
                    <Button type="submit" disabled={form.processing} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105">
                        {form.processing ? <><Loader2 className="mr-1 size-4 animate-spin" />Menyimpan...</> : 'Save Changes'}
                    </Button>
                    <button type="button" onClick={() => form.reset()} className="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary">Reset</button>
                </div>
                )}
            </form>

            <RequiredFieldsDialog
                open={requiredOpen}
                onOpenChange={setRequiredOpen}
                fields={missing}
                onFix={jumpToFirstMissing}
            />
        </section>
    );
}

CompaniesEdit.layout = [AppLayout];
