import { useMemo, useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import { 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 { WebsiteField } from '@/Components/MenuCompanies/WebsiteField';
import { MultinationalToggle } from '@/Components/MenuCompanies/MultinationalToggle';
import { CodeTagInput } from '@/Components/MenuCompanies/CodeTagInput';

// Insert Company — core-field subset (proto Pages/Proto/Companies/Create.jsx). Uncollected
// NOT NULL columns (uploads/NPWP/codes) are defaulted server-side; file uploads + child
// tabs (contacts/products/addresses) are a deferred follow-up. Layout follows the proto:
// collapsible section cards with sub-section headers + Pills.

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

export default function CompaniesCreate({ options = {}, currentUserId = null, isAdmin = 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);

    const form = useForm({
        CompanyName: '',
        UserIDSales: currentUserId ?? null,
        BranchID: null,
        DivisionID: null,
        IndustryID: null,
        CompanyCategoryIDs: [],
        ProductCategoryIDs: [],
        CustomerProductCategoryIDs: [],
        IsMultinational: false,
        CompanyTelephone: '',
        CompanyFax: '',
        CompanyWebsite: '',
        CompanyAddress: '',
        ZipCode: '',
        CustomerEst: '',
        CustomerSince: '',
        CompanyOwner: '',
        CompanyGroup: '',
        OfficePremises: '',
        FactoryPremises: '',
        OrderWithPO: false,
        HighestValueAchieved: null,
        TermNCondQuotation: '',
        TermNCondSample: '',
        Remark: '',
        // AST Company Code — any creator may set it on insert (legacy listcompanyinsert +
        // listcompanyallinsert). Stored comma-separated; NS/Oracle is not a create field.
        ASTCompanyCode: '',
    });

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

    // Sales (account owner): admin (/companies/all) may choose any salesperson (legacy admin
    // insert); everyone else gets the read-only creator (legacy readonly InsertSales).
    const salesName = salesUsers.find((u) => u.id === form.data.UserIDSales)?.name ?? '';

    // 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', []);
    };

    // Required fields, named the way they read on screen — the same set StoreCompanyRequest
    // enforces. Sales is NOT here: it is nullable and defaults to the creator.
    // Replaces a hardcoded `requiredTotal = 8`, which could not know that Company Category is
    // only required for some divisions and so counted a field the user might never owe.
    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 StoreCompanyRequest::divisionRequiresCategory() — the
            // groupdivision.IsCompCategoryMandatory flag, shipped per division as `categoryMandatory`.
            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: requiredTotal, filledCount: requiredFilled, showErr, reportAttempt } = useRequiredFields(requiredSpec, form.data);
    const [requiredOpen, setRequiredOpen] = useState(false);
    // Bumped only by "Isi Sekarang", so closing 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.
        setCollapse1(false);
        setCollapse2(false);
        setJumpAt((n) => n + 1);
    };

    const submit = (e) => {
        e?.preventDefault();
        // Client-side gate for EMPTY required fields only; formats, lengths, charset and FK
        // existence stay the server's call, so the two can never disagree.
        if (missing.length > 0) {
            reportAttempt();
            setRequiredOpen(true);

            return;
        }
        form.post(route('companies.store'), {
            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('companies.index')} className="text-muted-foreground no-underline hover:text-primary">Companies</Link>
                        <span aria-hidden="true">›</span>
                        <span className="text-foreground">Insert Company</span>
                    </p>
                    <h1 className="m-0 text-xl font-bold leading-tight text-card-foreground">Insert Company</h1>
                    <div className="mt-2.5 flex flex-wrap gap-2">
                        <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'}`}>Form progress: {requiredFilled}/{requiredTotal}</span>
                    </div>
                </div>
                <div className="flex flex-wrap justify-end gap-2">
                    <Link href={route('companies.index')} 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">Cancel</Link>
                    <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 Company'}
                    </Button>
                </div>
            </header>

            {/* noValidate: the two Save buttons disagreed. 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. Same guard as Edit.jsx. */}
            <form onSubmit={submit} noValidate>
                <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}>

                            {/* 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>
                                    {isAdmin ? (
                                        <FloatingField as="select" label="Sales" value={form.data.UserIDSales ?? ''} onChange={fkSelect('UserIDSales')}>
                                            <option value="">Select Sales</option>
                                            {salesUsers.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
                                        </FloatingField>
                                    ) : (
                                        <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>
                        </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}>

                            {/* 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>
                                        {/* company.CustomerEst is varchar(4), so anything longer than a
                                            year is a 422 — one that used to land on a field with no
                                            message slot at all. */}
                                        <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>
                                    <CodeTagInput label="AST Company Code" value={form.data.ASTCompanyCode} onChange={(v) => form.setData('ASTCompanyCode', v)} placeholder="Tambah kode…" />
                                    <FieldError message={form.errors.ASTCompanyCode} />
                                </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>
                            </div>
                        </div>
                    </article>
                </section>

                <div className="mt-6 flex items-center justify-between gap-4 border-t border-input pb-2 pt-4">
                    <div className="flex flex-wrap gap-2.5">
                        <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 Company'}
                        </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>
                    <Link href={route('companies.index')} 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">Cancel</Link>
                </div>
            </form>

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

CompaniesCreate.layout = [AppLayout];
