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

/**
 * CompanyRawMaterialsSection — the "Raw Materials" tab on Edit Company (legacy
 * listcompanyproduct.php). One inline-CRUD grid comparing a CC product with a competitor's, each
 * side carrying principal / product / volume / price / unit. Application cascades off Division;
 * CC and Competitor products each cascade off their own principal. The grid only shows rows with
 * active history (server INNER join, faithful to legacy).
 */

const TH = 'whitespace-nowrap bg-secondary/50 px-3 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-3 py-3 align-middle text-[12.5px] text-foreground first:pl-5 last:pr-5';
const GHOST = 'inline-grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-primary';
const dash = <span className="text-muted-foreground/60">—</span>;

const BLANK = {
    Status: 'Existing', DivisionID: '', ApplicationID: '', ColorIndex: '',
    CCPrincipalID: '', CCBarangID: '', CCVolume: '', CCVolumeSatuanID: '', CCPrice: '', CCPriceSatuanID: '',
    CompetitorDisctributor: '', CompetitorPrincipalID: '', CompetitorPrincipalName: '', CompetitorBarangID: '',
    CompetitorBarangName: '', CompetitorVolume: '', CompetitorVolumeSatuanID: '', CompetitorPrice: '', CompetitorPriceSatuanID: '',
    Remark: '',
};

const HISTORY_COLUMNS = [
    { key: 'tanggal', label: 'Tanggal' }, { key: 'user', label: 'Nama' }, { key: 'status', label: 'Status' },
    { key: 'division', label: 'Division' }, { key: 'application', label: 'Application' },
    { key: 'colorIndex', label: 'Color Index' }, { key: 'ccVolume', label: 'CC Vol' }, { key: 'ccPrice', label: 'CC Price' },
    { key: 'remark', label: 'Remark' },
];

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

export default function CompanyRawMaterialsSection({ companyId = null, rows = [], options = {}, readOnly = false, onSaved }) {
    const { show: showToast } = useToast();
    const http = useHttp({});
    const divisions = options.divisions ?? [];
    const applications = options.applications ?? [];
    const principals = options.principals ?? [];
    const satuans = options.satuans ?? [];

    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState(null);
    const [confirmRow, setConfirmRow] = useState(null);
    const [deleting, setDeleting] = useState(false);
    const [historyRow, setHistoryRow] = useState(null);
    const [ccProducts, setCcProducts] = useState([]);
    const [compProducts, setCompProducts] = useState([]);
    const form = useForm(BLANK);

    const groupDivId = divisions.find((d) => d.id === Number(form.data.DivisionID))?.groupDivisionId ?? null;
    const appOptions = groupDivId !== null ? applications.filter((a) => a.groupDivisionId === groupDivId) : [];

    const fetchProducts = async (principalId) => (principalId ? http.get(route('companies.potential-sales.products', [companyId, principalId])) : []);

    const openAdd = () => { setEditing(null); form.setData(BLANK); setCcProducts([]); setCompProducts([]); form.clearErrors(); setOpen(true); };
    const openEdit = async (r) => {
        setEditing(r);
        form.setData({
            Status: r.status ?? 'Existing', DivisionID: r.DivisionID ?? '', ApplicationID: r.ApplicationID ?? '', ColorIndex: r.colorIndex ?? '',
            CCPrincipalID: r.CCPrincipalID ?? '', CCBarangID: r.CCBarangID ?? '', CCVolume: r.ccVolume ?? '', CCVolumeSatuanID: r.CCVolumeSatuanID ?? '', CCPrice: r.ccPrice ?? '', CCPriceSatuanID: r.CCPriceSatuanID ?? '',
            CompetitorDisctributor: r.competitorDistributor ?? '', CompetitorPrincipalID: r.CompetitorPrincipalID ?? '', CompetitorPrincipalName: r.compPrincipalText ?? '',
            CompetitorBarangID: r.CompetitorBarangID ?? '', CompetitorBarangName: r.compProductText ?? '', CompetitorVolume: r.compVolume ?? '', CompetitorVolumeSatuanID: r.CompetitorVolumeSatuanID ?? '',
            CompetitorPrice: r.compPrice ?? '', CompetitorPriceSatuanID: r.CompetitorPriceSatuanID ?? '', Remark: r.remark ?? '',
        });
        form.clearErrors();
        setCcProducts(await fetchProducts(r.CCPrincipalID));
        setCompProducts(await fetchProducts(r.CompetitorPrincipalID));
        setOpen(true);
    };

    const onDivisionChange = (e) => { form.setData('DivisionID', e.target.value); form.setData('ApplicationID', ''); };
    const onCcPrincipal = async (e) => { form.setData('CCPrincipalID', e.target.value); form.setData('CCBarangID', ''); setCcProducts(await fetchProducts(e.target.value)); };
    const onCompPrincipal = async (e) => { form.setData('CompetitorPrincipalID', e.target.value); form.setData('CompetitorBarangID', ''); setCompProducts(await fetchProducts(e.target.value)); };

    const save = () => {
        const url = editing ? route('companies.raw-materials.update', [companyId, editing.id]) : route('companies.raw-materials.store', companyId);
        form.post(url, {
            preserveScroll: true,
            onSuccess: () => { setOpen(false); form.reset(); onSaved?.(); },
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };
    const remove = () => {
        setDeleting(true);
        router.delete(route('companies.raw-materials.destroy', [companyId, confirmRow.id]), {
            preserveScroll: true,
            onSuccess: () => { onSaved?.(); },
            onError: () => showToast('Delete failed.', 'error'),
            onFinish: () => { setDeleting(false); setConfirmRow(null); },
        });
    };

    // Legacy 2-row header: identity columns, then a CC group and a Competitor group.
    const groupCols = ['Principal', 'Product', 'Volume', 'Price'];

    return (
        <div className="flex flex-col gap-3 p-1">
            <div className="flex items-center justify-between">
                <span className="text-xs text-muted-foreground tabular-nums"><b className="font-semibold text-foreground">{rows.length}</b> raw materials</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
                    </button>
                )}
            </div>

            <div className="overflow-x-auto rounded-lg border border-border">
                <table className="w-full border-collapse">
                    <thead>
                        <tr>
                            <th rowSpan={2} className={TH}>Distributor</th>
                            <th rowSpan={2} className={TH}>Existing / Approval</th>
                            <th rowSpan={2} className={TH}>Division</th>
                            <th rowSpan={2} className={TH}>Application</th>
                            <th rowSpan={2} className={TH}>Color Index</th>
                            <th colSpan={4} className={`${TH} border-l border-border text-center`}>Colorindo (CC)</th>
                            <th colSpan={4} className={`${TH} border-l border-border text-center`}>Competitor</th>
                            <th rowSpan={2} className={`${TH} border-l border-border`}>Remark</th>
                            {!readOnly && <th rowSpan={2} className={TH}>Action</th>}
                        </tr>
                        <tr>
                            {groupCols.map((c) => <th key={`cc-${c}`} className={`${TH} ${c === 'Principal' ? 'border-l border-border' : ''}`}>{c}</th>)}
                            {groupCols.map((c) => <th key={`co-${c}`} className={`${TH} ${c === 'Principal' ? 'border-l border-border' : ''}`}>{c}</th>)}
                        </tr>
                    </thead>
                    <tbody>
                        {rows.length === 0 ? (
                            <tr><td colSpan={readOnly ? 14 : 15} className="px-4 py-8 text-center text-[13px] italic text-muted-foreground">Belum ada data.</td></tr>
                        ) : rows.map((r) => (
                            <tr key={r.id} className="transition-colors hover:bg-secondary/60 [&>td]:border-b [&>td]:border-border last:[&>td]:border-b-0">
                                <td className={TD}>{r.competitorDistributor || dash}</td>
                                <td className={TD}>
                                    <div className="flex items-center gap-1.5">
                                        <span>{r.status || dash}</span>
                                        <StatusBadge tone={r.approval === 'Approved' ? 'success' : 'neutral'}>{r.approval}</StatusBadge>
                                    </div>
                                </td>
                                <td className={TD}>{r.division || dash}</td>
                                <td className={TD}>{r.application || dash}</td>
                                <td className={TD}>{r.colorIndex || dash}</td>
                                <td className={`${TD} border-l border-border`}>{r.ccPrincipal || dash}</td>
                                <td className={TD}>{r.ccProduct || dash}</td>
                                <td className={`${TD} tabular-nums`}>{r.ccVolumeDisplay || dash}</td>
                                <td className={`${TD} tabular-nums`}>{r.ccPriceDisplay || dash}</td>
                                <td className={`${TD} border-l border-border`}>{r.compPrincipal || dash}</td>
                                <td className={TD}>{r.compProduct || dash}</td>
                                <td className={`${TD} tabular-nums`}>{r.compVolumeDisplay || dash}</td>
                                <td className={`${TD} tabular-nums`}>{r.compPriceDisplay || dash}</td>
                                <td className={`${TD} border-l border-border`}><span className="block max-w-[180px] truncate" title={r.remark}>{r.remark || dash}</span></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}><Pencil className="size-3.5" /></button>
                                            <button type="button" title="History" aria-label="History" onClick={() => setHistoryRow(r)} className={GHOST}><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>

            {/* Add / Edit dialog — CC + Competitor sections */}
            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent className="bg-card sm:max-w-3xl">
                    <DialogHeader><DialogTitle>{editing ? 'Edit' : 'Add'} Raw Material</DialogTitle>
                        <DialogDescription className="text-xs">Application mengikuti Division; Product mengikuti Principal masing-masing.</DialogDescription></DialogHeader>
                    <div className="max-h-[68vh] overflow-y-auto pr-1">
                        <div className="grid grid-cols-2 gap-3 py-1 md:grid-cols-4">
                            <FloatingField label="Existing / Status" value={form.data.Status} onChange={(e) => form.setData('Status', e.target.value)} />
                            <div><FloatingField as="select" label="Division" value={form.data.DivisionID} onChange={onDivisionChange}><option value="">—</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="Application" value={form.data.ApplicationID} onChange={(e) => form.setData('ApplicationID', e.target.value)} disabled={!form.data.DivisionID}><option value="">—</option>{appOptions.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}</FloatingField><FieldError message={form.errors.ApplicationID} /></div>
                            <FloatingField label="Color Index" value={form.data.ColorIndex} onChange={(e) => form.setData('ColorIndex', e.target.value)} />
                        </div>

                        <fieldset className="mt-2 rounded-lg border border-border p-3">
                            <legend className="px-1 text-[11px] font-bold uppercase tracking-wide text-primary">Colorindo (CC)</legend>
                            <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
                                <div><FloatingField as="select" label="Principal" value={form.data.CCPrincipalID} onChange={onCcPrincipal}><option value="">—</option>{principals.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</FloatingField><FieldError message={form.errors.CCPrincipalID} /></div>
                                <div className="md:col-span-2"><FloatingField as="select" label="Product" value={form.data.CCBarangID} onChange={(e) => form.setData('CCBarangID', e.target.value)} disabled={!form.data.CCPrincipalID}><option value="">—</option>{ccProducts.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}</FloatingField><FieldError message={form.errors.CCBarangID} /></div>
                                <FloatingField type="number" step="any" label="Volume" value={form.data.CCVolume} onChange={(e) => form.setData('CCVolume', e.target.value)} />
                                <FloatingField as="select" label="Vol Unit" value={form.data.CCVolumeSatuanID} onChange={(e) => form.setData('CCVolumeSatuanID', e.target.value)}><option value="">—</option>{satuans.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}</FloatingField>
                                <div className="grid grid-cols-2 gap-2">
                                    <FloatingField type="number" step="any" label="Price" value={form.data.CCPrice} onChange={(e) => form.setData('CCPrice', e.target.value)} />
                                    <FloatingField as="select" label="Unit" value={form.data.CCPriceSatuanID} onChange={(e) => form.setData('CCPriceSatuanID', e.target.value)}><option value="">—</option>{satuans.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}</FloatingField>
                                </div>
                            </div>
                        </fieldset>

                        <fieldset className="mt-3 rounded-lg border border-border p-3">
                            <legend className="px-1 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">Competitor</legend>
                            <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
                                <FloatingField label="Distributor" value={form.data.CompetitorDisctributor} onChange={(e) => form.setData('CompetitorDisctributor', e.target.value)} />
                                <FloatingField as="select" label="Principal" value={form.data.CompetitorPrincipalID} onChange={onCompPrincipal}><option value="">—</option>{principals.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</FloatingField>
                                <FloatingField label="Principal (free text)" value={form.data.CompetitorPrincipalName} onChange={(e) => form.setData('CompetitorPrincipalName', e.target.value)} />
                                <FloatingField as="select" label="Product" value={form.data.CompetitorBarangID} onChange={(e) => form.setData('CompetitorBarangID', e.target.value)} disabled={!form.data.CompetitorPrincipalID}><option value="">—</option>{compProducts.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}</FloatingField>
                                <FloatingField label="Product (free text)" value={form.data.CompetitorBarangName} onChange={(e) => form.setData('CompetitorBarangName', e.target.value)} className="md:col-span-2" />
                                <FloatingField type="number" step="any" label="Volume" value={form.data.CompetitorVolume} onChange={(e) => form.setData('CompetitorVolume', e.target.value)} />
                                <FloatingField as="select" label="Vol Unit" value={form.data.CompetitorVolumeSatuanID} onChange={(e) => form.setData('CompetitorVolumeSatuanID', e.target.value)}><option value="">—</option>{satuans.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}</FloatingField>
                                <div className="grid grid-cols-2 gap-2">
                                    <FloatingField type="number" step="any" label="Price" value={form.data.CompetitorPrice} onChange={(e) => form.setData('CompetitorPrice', e.target.value)} />
                                    {/* Fixed: own unit, not the CC one (legacy bug). */}
                                    <FloatingField as="select" label="Unit" value={form.data.CompetitorPriceSatuanID} onChange={(e) => form.setData('CompetitorPriceSatuanID', e.target.value)}><option value="">—</option>{satuans.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}</FloatingField>
                                </div>
                            </div>
                        </fieldset>

                        <FloatingField as="textarea" label="Remark" value={form.data.Remark} onChange={(e) => form.setData('Remark', e.target.value)} className="mt-3" />
                    </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' : 'Add')}</Button>
                        <Button type="button" variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog open={confirmRow !== null} onOpenChange={(v) => !v && setConfirmRow(null)}>
                <DialogContent className="bg-card sm:max-w-md">
                    <DialogHeader><DialogTitle>Hapus Raw Material</DialogTitle>
                        <DialogDescription className="text-xs">Hapus entry <b className="text-foreground">{confirmRow?.ccProduct || confirmRow?.colorIndex}</b>? 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>

            <TabHistoryDialog
                url={historyRow ? route('companies.raw-materials.history', [companyId, historyRow.id]) : null}
                title={historyRow ? `History — ${historyRow.ccProduct || historyRow.colorIndex}` : 'History'}
                onClose={() => setHistoryRow(null)} columns={HISTORY_COLUMNS}
            />
        </div>
    );
}
