import { Link, router, useForm } from '@inertiajs/react';
import { useState } from 'react';
import { ArrowLeft, Loader2, Trash2 } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { FloatingField } from '@/Components/Proto/UI/FloatingField';
import { DeleteModal } from '@/Components/Table';
import { useToast } from '@/Components/Toast';

const CARD = 'rounded-2xl border border-border bg-card shadow-sm p-6';
const SECONDARY_BTN = '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';

/**
 * Edit Barang — legacy pengelolaan/product/listbarangedit.php (+ getrelasitablebarang.php).
 *
 * Two legacy behaviours that look odd but are intentional:
 *  - the submit button reads "Update and Restore Barang" on a soft-deleted row, because the
 *    legacy UPDATE always writes IsDeleted = 0. Editing a deleted product restores it.
 *  - Quantity is read-only here. Lots are owned by the Stock Sample module, not this form.
 */
export default function Edit({ product, lots = [], relations = [], blockers = [], options = {} }) {
    const { show: showToast } = useToast();
    const [confirmingDelete, setConfirmingDelete] = useState(false);

    const isDeleted = Boolean(product.IsDeleted);
    const canDelete = blockers.length === 0;

    const form = useForm({
        KodeBarang: product.KodeBarang ?? '',
        NamaBarang: product.NamaBarang ?? '',
        CategoryID: product.CategoryID ?? '',
        TypeID: product.TypeID ?? '',
        PrincipalID: product.PrincipalID ?? '',
        Remarks: product.Remarks ?? '',
    });

    const submit = (e) => {
        e.preventDefault();
        form.put(route('product-samples.update', product.ID), {
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    const confirmDelete = () => {
        router.delete(route('product-samples.destroy', product.ID), {
            preserveScroll: true,
            onFinish: () => setConfirmingDelete(false),
        });
    };

    const err = (k) => (form.errors[k]
        ? <p className="mt-1 text-[11px] font-semibold text-danger-text">{form.errors[k]}</p>
        : null);

    return (
        <section className="flex min-w-0 flex-col gap-5">
            <header className="flex items-start 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('product-samples.index')} className="text-muted-foreground no-underline hover:text-primary">Product Sample</Link>
                        <span aria-hidden="true">›</span>
                        <span className="text-primary">Edit Barang</span>
                    </p>
                    <h1 className="m-0 flex items-center gap-2.5 text-2xl font-extrabold leading-[1.2] tracking-tight text-foreground">
                        Edit Barang
                        {isDeleted && (
                            <span className="rounded-full bg-danger/10 px-2.5 py-0.5 text-[11px] font-semibold text-danger-text">Deleted</span>
                        )}
                    </h1>
                </div>
                <Link href={route('product-samples.index')} className={SECONDARY_BTN}><ArrowLeft className="size-3.5" /> Back</Link>
            </header>

            <form onSubmit={submit} className="flex flex-col gap-5">
                <article className={CARD}>
                    <div className="grid grid-cols-2 gap-x-5 gap-y-4 max-[700px]:grid-cols-1">
                        <div>
                            <FloatingField label="ID" type="text" readOnly alwaysFloat value={String(product.ID)} onChange={() => {}} />
                        </div>
                        <div>
                            <FloatingField label="Kode Barang" type="text"
                                value={form.data.KodeBarang}
                                onChange={(e) => form.setData('KodeBarang', e.target.value)} />
                            {err('KodeBarang')}
                        </div>
                        <div>
                            <FloatingField label="Nama Barang *" type="text"
                                value={form.data.NamaBarang}
                                onChange={(e) => form.setData('NamaBarang', e.target.value)} />
                            {err('NamaBarang')}
                        </div>
                        <div>
                            <FloatingField as="select" label="Category"
                                value={form.data.CategoryID ?? ''}
                                onChange={(e) => form.setData('CategoryID', e.target.value)}>
                                <option value="">Select Category</option>
                                {(options.categories || []).map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
                            </FloatingField>
                            {err('CategoryID')}
                        </div>
                        <div>
                            <FloatingField as="select" label="Type"
                                value={form.data.TypeID ?? ''}
                                onChange={(e) => form.setData('TypeID', e.target.value)}>
                                <option value="">Select Type</option>
                                {(options.types || []).map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
                            </FloatingField>
                            {err('TypeID')}
                        </div>
                        <div>
                            <FloatingField as="select" label="Principal"
                                value={form.data.PrincipalID ?? ''}
                                onChange={(e) => form.setData('PrincipalID', e.target.value)}>
                                <option value="">Select Principal</option>
                                {(options.principals || []).map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
                            </FloatingField>
                            {err('PrincipalID')}
                        </div>
                        <div className="col-span-2 max-[700px]:col-span-1">
                            <FloatingField as="textarea" label="Remarks"
                                value={form.data.Remarks}
                                onChange={(e) => form.setData('Remarks', e.target.value)} />
                            {err('Remarks')}
                        </div>
                    </div>

                    <div className="mt-5 border-t border-border/60 pt-4">
                        <h2 className="m-0 mb-2 text-xs font-bold uppercase tracking-wide text-muted-foreground">Quantity</h2>
                        {lots.length === 0 ? (
                            <p className="m-0 text-sm text-text-muted">—</p>
                        ) : (
                            <div className="flex flex-col gap-1.5 text-sm">
                                {lots.map((l, i) => (
                                    <div key={i} className="leading-snug">
                                        <span>- <strong className="font-bold text-text-heading">{l.lot || '—'}</strong> ({l.stock}{l.satuan ? ` ${l.satuan}` : ''})</span>
                                        {l.note ? <div className="text-primary">Keterangan : {l.note}</div> : null}
                                        {l.masuk ? <div className="text-primary">TanggalMasuk : {l.masuk}</div> : null}
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </article>

                {/* legacy getrelasitablebarang.php — "Item Table Relation" */}
                <article className={CARD}>
                    <h2 className="m-0 mb-3 text-sm font-bold text-text-heading">Item Table Relation</h2>
                    <div className="overflow-x-auto">
                        <table className="w-full border-separate border-spacing-0 text-[12px]">
                            <thead>
                                <tr>
                                    <th className="border-b border-border px-3 py-2 text-left text-[11px] font-bold uppercase tracking-wide text-muted-foreground first:pl-0">Nama Table</th>
                                    <th className="border-b border-border px-3 py-2 text-right text-[11px] font-bold uppercase tracking-wide text-muted-foreground last:pr-0">Quantity</th>
                                </tr>
                            </thead>
                            <tbody>
                                {relations.map((rel) => (
                                    <tr key={rel.key}>
                                        <td className="px-3 py-3 align-top first:pl-0">{rel.label}</td>
                                        <td className={`px-3 py-3 text-right tabular-nums align-top last:pr-0 ${rel.count > 0 ? 'font-bold text-text-heading' : 'text-text-muted'}`}>
                                            {rel.count}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    {!canDelete && (
                        // The panel above cannot always explain a refusal: legacy's delete gate
                        // checks companyproductassignment, which the panel never lists. So the
                        // blocking tables are named outright.
                        <p className="m-0 mt-3 rounded-lg bg-warning-bg px-3 py-2 text-[12px] font-semibold text-warning-text">
                            Tidak dapat dihapus — masih dipakai: {blockers.join(', ')}.
                        </p>
                    )}
                </article>

                <div className="flex items-center gap-3 border-t border-border/60 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-5 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-50">
                        {form.processing
                            ? <><Loader2 className="size-3.5 animate-spin" /> Menyimpan…</>
                            : (isDeleted ? 'Update and Restore Barang' : 'Update Barang')}
                    </button>
                    <Link href={route('product-samples.index')} className={SECONDARY_BTN}>Batal</Link>
                    {!isDeleted && (
                        <button
                            type="button"
                            onClick={() => setConfirmingDelete(true)}
                            disabled={!canDelete}
                            title={canDelete ? 'Delete Barang' : `Masih dipakai: ${blockers.join(', ')}`}
                            className="ml-auto inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-danger/40 bg-danger/5 px-4 text-xs font-bold text-danger-text transition-colors hover:bg-danger/15 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-danger/5"
                        >
                            <Trash2 className="size-3.5" /> Delete Barang
                        </button>
                    )}
                </div>
            </form>

            {confirmingDelete && (
                <DeleteModal
                    label={product.NamaBarang}
                    onCancel={() => setConfirmingDelete(false)}
                    onConfirm={confirmDelete}
                />
            )}
        </section>
    );
}

Edit.layout = [AppLayout];
