import { useForm, router, usePage } from '@inertiajs/react';
import { useState, useMemo, useRef } from 'react';
import ResourceIndex from '../../Components/ResourceIndex';
import RelationTable from '../../Components/RelationTable';
import Badge from '../../Components/Badge';
import { TextInput, SelectInput, TextArea, DateInput, SmartNumberInput } from '../../Components/Form';
import SlideOver, { DrawerFooter, useDrawerDirty, useDrawerCancel } from '../../Components/SlideOver';
import Button from '../../Components/Button';
import BarcodeInput from '../../Components/BarcodeInput';
import InvoicePreview from '../../Components/Sales/InvoicePreview';
import CustomerLookup from '../../Components/CustomerLookup';
import ComboBox from '../../Components/ComboBox';
import PurityInput from '../../Components/PurityInput';
import WeightInput from '../../Components/WeightInput';
import { formatDate, formatMoney, formatWeight } from '../../lib/format';
import { useDirtyForm } from '../../hooks/useDirtyForm';
import { useFormKeyboard } from '../../hooks/useFormKeyboard';
import { parseMoney, isValidMobile } from '../../lib/parse';

const WhatsAppIcon = (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 01.865-.501 48.172 48.172 0 003.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z" />
    </svg>
);
const ConvertIcon = (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
    </svg>
);
const ReturnStockIcon = (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M3 7.5L12 3l9 4.5M3 7.5l9 4.5m-9-4.5v9l9 4.5m0-9l9-4.5m-9 4.5v9m9-13.5v9l-9 4.5" />
    </svg>
);

const PAYMENT_MODES = [
    { value: 'cash', label: 'Cash' },
    { value: 'upi', label: 'UPI' },
    { value: 'card', label: 'Card' },
    { value: 'bank_transfer', label: 'Bank Transfer' },
    { value: 'cheque', label: 'Cheque' },
    { value: 'metal', label: 'Metal' },
    { value: 'adjustment', label: 'Adjustment' },
    { value: 'mixed', label: 'Mixed' },
];

const paymentModeLabel = (mode) => PAYMENT_MODES.find((m) => m.value === mode)?.label || mode;
const today = () => new Date().toISOString().split('T')[0];
const inputDate = (value) => value ? String(value).slice(0, 10) : today();

/**
 * Inline editor for sale line items — works in both create and edit modes.
 *
 * - In **edit mode** (sale prop has an id): each add/remove hits the server
 *   immediately via /sales/{sale}/items endpoints. Server is source of truth.
 * - In **create mode** (no sale id yet): items are kept in local state via
 *   localItems + onLocalChange props. They're submitted as part of the parent
 *   form's POST /sales payload, so the sale and its items are created together.
 */

/**
 * Keyboard-first auto-calc for sale line items:
 *   amount = weight × rate   (if weight+rate set, amount blank → compute)
 *   rate = amount / weight   (if weight+amount set, rate blank → compute)
 *   weight = amount / rate   (if rate+amount set, weight blank → compute)
 * The `justChanged` field is excluded from auto-fill so we never overwrite
 * what the user is actively typing.
 */
function recalcDraft(draft, justChanged) {
    const w = parseFloat(draft.weight);
    const r = parseFloat(draft.rate);
    const a = parseFloat(draft.amount);
    const has = { w: !Number.isNaN(w) && w > 0, r: !Number.isNaN(r) && r > 0, a: !Number.isNaN(a) && a > 0 };
    const next = { ...draft };

    if (justChanged !== 'amount' && has.w && has.r) {
        next.amount = String(Math.round(w * r * 100) / 100);
    } else if (justChanged !== 'rate' && has.w && has.a) {
        next.rate = String(Math.round((a / w) * 100) / 100);
    } else if (justChanged !== 'weight' && has.r && has.a) {
        next.weight = String(Math.round((a / r) * 1000) / 1000);
    }
    return next;
}

/** Pick today's rate (gold/silver) for a product, falling back to gold. */
function rateForProduct(product, rates) {
    const metal = String(product?.metal_type || '').toLowerCase();
    if (metal.includes('silver')) return Number(rates?.silver) || '';
    return Number(rates?.gold) || '';
}

function normalizeIndianMobile(mobile) {
    const clean = String(mobile || '').replace(/\D/g, '');
    if (!clean) return '';
    if (clean.length === 10) return `91${clean}`;
    if (clean.length === 12 && clean.startsWith('91')) return clean;
    return clean;
}

function distributeItemsForTotal(items, total) {
    const amount = Number(total) || 0;
    if (!items?.length || amount <= 0) return items || [];

    const currentTotal = items.reduce((sum, it) => sum + Number(it.amount || 0), 0);
    const totalWeight = items.reduce((sum, it) => sum + Number(it.weight || 0), 0);
    let running = 0;

    return items.map((item, index) => {
        const weight = Number(item.weight || 0);
        let itemAmount;

        if (index === items.length - 1) {
            itemAmount = Math.round((amount - running) * 100) / 100;
        } else {
            const basis = currentTotal > 0
                ? Number(item.amount || 0) / currentTotal
                : (totalWeight > 0 ? weight / totalWeight : 1 / items.length);
            itemAmount = Math.round(amount * basis * 100) / 100;
            running += itemAmount;
        }

        return {
            ...item,
            amount: String(itemAmount),
            rate: weight > 0 ? String(Math.round((itemAmount / weight) * 100) / 100) : item.rate,
        };
    });
}

function SaleItemsSection({ sale, availableProducts, localItems, onLocalChange }) {
    const { app } = usePage().props;
    const todayRates = app?.rates || {};
    const isLocal = !sale?.id;
    const [adding, setAdding] = useState(false);
    const [draft, setDraft] = useState({
        product_id: '',
        weight: '',
        purity: '',
        rate: todayRates.gold ? String(todayRates.gold) : '',
        amount: '',
    });
    const [submitting, setSubmitting] = useState(false);

    const products = availableProducts || [];
    const items = localItems || (isLocal ? [] : (sale?.items || []));

    const totalAmount = useMemo(
        () => items.reduce((sum, it) => sum + Number(it.amount || 0), 0),
        [items]
    );

    const findProduct = (id) => products.find(p => String(p.id) === String(id));

    const handleProductChange = (name, value) => {
        const product = findProduct(value);
        const detectedRate = product ? rateForProduct(product, todayRates) : '';
        setDraft(prev => {
            // Only auto-fill rate if current rate is empty OR still matches a default
            // (gold/silver) — preserves anything the user typed manually.
            const isDefault = !prev.rate
                || Number(prev.rate) === Number(todayRates.gold)
                || Number(prev.rate) === Number(todayRates.silver);
            return recalcDraft({
                ...prev,
                product_id: value,
                weight: product?.weight ?? prev.weight,
                purity: product?.purity ?? prev.purity,
                rate: detectedRate && isDefault ? String(detectedRate) : prev.rate,
            }, 'product_id');
        });
    };

    const handleDraftChange = (name, value) => {
        setDraft(prev => recalcDraft({ ...prev, [name]: value }, name));
    };

    // Handler for barcode-scanner / quick-find input — opens the add row pre-filled.
    const handleScan = (product) => {
        setAdding(true);
        const detectedRate = rateForProduct(product, todayRates);
        setDraft(prev => recalcDraft({
            ...prev,
            product_id: String(product.id),
            weight: product.weight ?? prev.weight,
            purity: product.purity ?? prev.purity,
            rate: detectedRate
                ? String(detectedRate)
                : prev.rate,
        }, 'product_id'));
    };

    const resetDraft = () => {
        const selectedProduct = findProduct(draft.product_id);
        const detectedRate = selectedProduct ? rateForProduct(selectedProduct, todayRates) : todayRates.gold;
        setDraft({
            product_id: '',
            weight: '',
            purity: '',
            rate: detectedRate ? String(detectedRate) : '',
            amount: '',
        });
        setAdding(false);
    };

    const handleAdd = () => {
        if (!draft.product_id || !draft.amount) return;

        if (isLocal) {
            // Push into local state — also denormalize a product reference for display
            const product = findProduct(draft.product_id);
            const newItem = {
                _localId: Date.now() + Math.random(),
                product_id: draft.product_id,
                product: product ? { product_code: product.product_code } : null,
                weight: draft.weight,
                purity: draft.purity,
                rate: draft.rate,
                amount: draft.amount,
            };
            onLocalChange([...(localItems || []), newItem]);
            resetDraft();
            return;
        }

        setSubmitting(true);
        router.post(`/sales/${sale.id}/items`, draft, {
            preserveScroll: true,
            onSuccess: resetDraft,
            onFinish: () => setSubmitting(false),
        });
    };

    const handleRemove = (item) => {
        if (!confirm('Remove this item from the sale?')) return;

        if (isLocal) {
            onLocalChange((localItems || []).filter(it => it._localId !== item._localId));
            return;
        }
        router.delete(`/sales/${sale.id}/items/${item.id}`, { preserveScroll: true });
    };

    return (
        <div className="rounded-xl border border-gray-100 bg-gray-50/40 overflow-hidden">
            {/* Section header */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between px-3 sm:px-4 py-3 border-b border-gray-100 bg-white gap-2 sm:gap-3">
                <div className="shrink-0">
                    <h3 className="text-sm font-semibold text-gray-800 tracking-tight">Sale Items</h3>
                    <p className="text-xs text-gray-500 mt-0.5 tabular-nums">
                        {items.length === 0 ? 'No items added yet' : `${items.length} item${items.length > 1 ? 's' : ''} · ${formatMoney(totalAmount)}`}
                    </p>
                </div>
                <div className="flex-1 sm:max-w-xs">
                    <BarcodeInput
                        products={products}
                        onScan={handleScan}
                        placeholder="Scan or type code…"
                    />
                </div>
                {!adding && (
                    <button
                        type="button"
                        onClick={() => setAdding(true)}
                        className="inline-flex items-center justify-center gap-1.5 px-3 py-2 sm:py-1.5 text-xs font-semibold text-primary-700 bg-primary-50 hover:bg-primary-100 rounded-lg border border-primary-200 transition-colors shrink-0"
                    >
                        <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
                        </svg>
                        Add Item
                    </button>
                )}
            </div>

            {/* Items table */}
            {items.length > 0 && (
                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead className="text-xs uppercase text-gray-400 bg-white border-b border-gray-100">
                            <tr>
                                <th className="px-3 sm:px-4 py-2 text-left font-semibold">Product</th>
                                <th className="px-3 sm:px-4 py-2 text-right font-semibold">Weight</th>
                                <th className="px-3 sm:px-4 py-2 text-right font-semibold hidden sm:table-cell">Purity</th>
                                <th className="px-3 sm:px-4 py-2 text-right font-semibold hidden sm:table-cell">Rate</th>
                                <th className="px-3 sm:px-4 py-2 text-right font-semibold">Amount</th>
                                <th className="px-2 sm:px-4 py-2 w-10"></th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100">
                            {items.map((item) => (
                                <tr key={item.id || item._localId} className="bg-white hover:bg-gray-50/60 transition-colors">
                                    <td className="px-3 sm:px-4 py-2.5 font-medium text-gray-800">{item.product?.product_code || `#${item.product_id}`}</td>
                                    <td className="px-3 sm:px-4 py-2.5 text-right text-gray-600 tabular-nums">{item.weight ? `${item.weight} g` : '-'}</td>
                                    <td className="px-3 sm:px-4 py-2.5 text-right text-gray-600 hidden sm:table-cell">{item.purity || '-'}</td>
                                    <td className="px-3 sm:px-4 py-2.5 text-right text-gray-600 hidden sm:table-cell">{item.rate ? `₹${Number(item.rate).toLocaleString('en-IN')}` : '-'}</td>
                                    <td className="px-3 sm:px-4 py-2.5 text-right font-semibold text-gray-800 tabular-nums">₹{Number(item.amount).toLocaleString('en-IN')}</td>
                                    <td className="px-2 sm:px-4 py-2.5 text-right">
                                        <button
                                            type="button"
                                            onClick={() => handleRemove(item)}
                                            className="inline-flex items-center justify-center w-8 h-8 rounded-full text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                                            title="Remove item"
                                        >
                                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                                            </svg>
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            {/* Add-item inline row — Tab through product → weight → purity → rate → amount → Save.
                Enter on amount submits; Esc cancels. Auto-calc fills the blank field. */}
            {adding && (
                <div
                    className="p-4 bg-white border-t border-gray-100"
                    onKeyDown={(e) => {
                        if (e.key === 'Enter' && (e.target.name === 'amount' || e.target.name === 'rate')) {
                            e.preventDefault();
                            if (draft.product_id && draft.amount) handleAdd();
                        } else if (e.key === 'Escape') {
                            e.preventDefault();
                            resetDraft();
                        }
                    }}
                >
                    <div className="grid grid-cols-1 sm:grid-cols-6 gap-3">
                        <div className="sm:col-span-2">
                            <ComboBox
                                label="Product"
                                name="product_id"
                                value={draft.product_id}
                                onChange={handleProductChange}
                                required
                                placeholder="Search code, barcode, HUID, category…"
                                recentKey="sale_product"
                                options={products.map(p => ({
                                    value: p.id,
                                    label: p.product_code,
                                    hint: [p.category?.name, p.huid, p.metal_type].filter(Boolean).join(' · '),
                                }))}
                            />
                        </div>
                        <WeightInput label="Weight" name="weight" value={draft.weight} onChange={handleDraftChange} />
                        <PurityInput label="Purity" name="purity" value={draft.purity} onChange={handleDraftChange} className="sm:col-span-2" />
                        <SmartNumberInput label="Rate/g" name="rate" value={draft.rate} onChange={handleDraftChange} prefix="₹" parser={parseMoney} />
                        <SmartNumberInput label="Amount" name="amount" value={draft.amount} onChange={handleDraftChange} prefix="₹" parser={parseMoney} required />
                    </div>
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mt-3">
                        <p className="hidden md:block text-[10px] text-gray-400 tabular-nums">
                            <kbd className="px-1 py-0.5 bg-gray-100 rounded">Tab</kbd> next · <kbd className="px-1 py-0.5 bg-gray-100 rounded">Enter</kbd> save · <kbd className="px-1 py-0.5 bg-gray-100 rounded">Esc</kbd> cancel · blank field auto-fills
                        </p>
                        <div className="flex items-center gap-2 justify-end">
                            <Button variant="secondary" type="button" onClick={resetDraft}>Cancel</Button>
                            <Button type="button" onClick={handleAdd} disabled={submitting || !draft.product_id || !draft.amount}>
                                {submitting ? 'Adding...' : 'Save Item'}
                            </Button>
                        </div>
                    </div>
                </div>
            )}

            {/* Empty state */}
            {items.length === 0 && !adding && (
                <div className="px-4 py-8 text-center">
                    <p className="text-xs text-gray-400">Click <span className="font-semibold text-gray-600">Add Item</span> to attach products to this sale.</p>
                </div>
            )}
        </div>
    );
}

function FormContent({ record, onClose, reopenAsNew, customers, onCustomerAdded, availableProducts }) {
    const isEdit = !!record;
    const formRef = useRef(null);
    const form = useForm({
        sale_type: record?.sale_type || 'gst',
        customer_id: record?.customer_id || '',
        customer_name:   record?.customer?.name       || '',
        customer_mobile: record?.customer?.mobile     || '',
        customer_gst:    record?.customer?.gst_number || '',
        customer_address: record?.customer?.address   || '',
        customer_gst_number: record?.customer_gst_number || '',
        sale_date: record?.sale_date || new Date().toISOString().split('T')[0],
        final_amount: record?.final_amount || '', taxable_value: record?.taxable_value || '',
        cgst: record?.cgst || '', sgst: record?.sgst || '',
        payment_mode: record?.payment_mode || 'cash', payment_type: record?.payment_type || 'full',
        paid_amount: record?.paid_amount || '', credit_amount: record?.credit_amount || '',
        notes: record?.notes || '',
        items: record?.items || [],
    });
    const { data, setData, post, put, processing, errors } = form;

    // Dirty-state for unsaved-changes guard
    const { isDirty, markClean } = useDirtyForm(data);
    useDrawerDirty(isDirty);
    const cancel = useDrawerCancel(onClose);

    const setLocalItems = (items) => {
        setData(prev => {
            const previousTotal = (prev.items || []).reduce((sum, it) => sum + Number(it.amount || 0), 0);
            const nextTotal = (items || []).reduce((sum, it) => sum + Number(it.amount || 0), 0);
            let next = { ...prev, items };

            if (!Number(prev.final_amount) || Number(prev.final_amount) === previousTotal) {
                next.final_amount = nextTotal ? String(round2(nextTotal)) : '';
                if (next.final_amount) next = applyTaxDerivation(next, 'final_amount');
            }

            return next;
        });
    };

    // Single permanent transform — strips local-only/denormalized item keys.
    form.transform((d) => ({
        ...d,
        items: (d.items || []).map(({ _localId, product, ...rest }) => rest),
    }));

    const submit = (andNew = false) => {
        const opts = { onSuccess: () => { markClean(); andNew ? reopenAsNew?.() : onClose(); } };
        if (isEdit) put(`/sales/${record.id}`, opts);
        else        post('/sales', opts);
    };
    const handleSubmit = (e) => { e.preventDefault(); submit(false); };
    useFormKeyboard(formRef, { onSubmit: () => submit(false), onCancel: onClose });

    // Reverse-calc over the tax triangle: taxable + CGST 1.5% + SGST 1.5% = final_amount.
    // Editing any of { final_amount, taxable_value, cgst, sgst } derives the other three —
    // the source field is NOT overwritten so user input is preserved verbatim.
    // For "On Approval" sales, no GST applies — taxable just mirrors the final amount.
    const round2 = (n) => Math.round(Number(n) * 100) / 100;
    const applyTaxDerivation = (d, source) => {
        const next = { ...d };
        const s = Number(d[source]);
        if (!s || s <= 0) return next;

        // On-approval sales: no GST
        if (d.sale_type !== 'gst') {
            if (source === 'final_amount')       { next.taxable_value = round2(s); next.cgst = 0; next.sgst = 0; }
            else if (source === 'taxable_value') { next.final_amount  = round2(s); next.cgst = 0; next.sgst = 0; }
            return next;
        }

        let taxable;
        if (source === 'final_amount')        taxable = s / 1.03;
        else if (source === 'taxable_value')  taxable = s;
        else if (source === 'cgst' || source === 'sgst') taxable = s / 0.015;
        else return next;

        const cgst    = round2(taxable * 0.015);
        const sgst    = round2(taxable * 0.015);
        const taxable2 = round2(taxable);
        const total   = round2(taxable2 + cgst + sgst);

        if (source !== 'taxable_value') next.taxable_value = taxable2;
        if (source !== 'cgst')          next.cgst          = cgst;
        if (source !== 'sgst')          next.sgst          = sgst;
        if (source !== 'final_amount')  next.final_amount  = total;
        return next;
    };

    const set = (n, v) => {
        setData(prev => {
            let d = { ...prev, [n]: v };
            // Re-run tax derivation when sale_type flips (switching GST ↔ on_approval
            // while an amount exists should update tax fields immediately).
            if (n === 'sale_type') {
                if (Number(d.final_amount) > 0) d = applyTaxDerivation(d, 'final_amount');
            } else if (['final_amount', 'taxable_value', 'cgst', 'sgst'].includes(n)) {
                d = applyTaxDerivation(d, n);
            }
            if (n === 'final_amount' && (d.items || []).length > 0) {
                d.items = distributeItemsForTotal(d.items, d.final_amount);
            }
            // Payment derivation: keep credit = total − paid when credit type selected
            if (d.payment_type === 'credit') {
                const total = Number(d.final_amount) || 0;
                const paid = Number(d.paid_amount) || 0;
                d.credit_amount = round2(Math.max(0, total - paid));
            } else if (d.payment_type === 'full') {
                d.paid_amount = d.final_amount;
                d.credit_amount = 0;
            }
            return d;
        });
    };

    // Customer lookup emits the full customer object on change
    const setCustomer = (next) => setData(prev => ({ ...prev, ...next }));

    const itemsPreview = data.items || [];
    const itemsTotal  = itemsPreview.reduce((sum, it) => sum + Number(it.amount || 0), 0);
    const itemsWeight = itemsPreview.reduce((sum, it) => sum + Number(it.weight || 0), 0);

    const sectionLabel = (text) => (
        <div className="flex items-center gap-2 mb-2">
            <span className="font-display italic text-xs text-primary-700">{text}</span>
            <span className="flex-1 h-px bg-gradient-to-r from-primary-200 to-transparent" />
        </div>
    );

    return (
        <form ref={formRef} onSubmit={handleSubmit} className="relative -m-4 sm:-m-6">
            <div className="bg-gradient-to-b from-[#FFFDF7] via-white to-white">
                {/* ─── BILL HEAD ─── */}
                <header className="relative px-4 sm:px-6 pt-4 pb-3 border-b border-primary-100/80">
                    <div aria-hidden className="absolute top-0 left-0 right-0 h-0.5 bg-gradient-to-r from-transparent via-primary-500 to-transparent opacity-70" />
                    <div aria-hidden className="absolute top-[3px] left-4 right-4 sm:left-6 sm:right-6 h-px bg-primary-200/60" />

                    <div className="flex items-start justify-between gap-3 sm:gap-4 flex-wrap">
                        <div className="flex items-center gap-2.5 min-w-0">
                            <span className="relative w-9 h-9 rounded-lg bg-gradient-to-br from-primary-400 via-primary-500 to-primary-700 flex items-center justify-center shadow-[0_4px_10px_-3px_rgba(212,163,26,0.5),inset_0_1px_0_rgba(255,255,255,0.4)] shrink-0">
                                <svg className="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 24 24">
                                    <path d="M12 2L4 8l8 14 8-14-8-6z" opacity="0.95" />
                                    <path d="M12 2L4 8h16l-8-6z" fill="white" opacity="0.25" />
                                </svg>
                            </span>
                            <div className="min-w-0">
                                <h1 className="font-display text-base sm:text-lg leading-none font-bold text-gray-900 tracking-tight truncate">Mahendra Jewellers</h1>
                                <p className="text-[0.625rem] text-primary-700 font-semibold uppercase tracking-[0.15em] mt-0.5">Fine Gold & Silver · Est. 1985</p>
                            </div>
                        </div>

                        <div className="text-right">
                            <div className="flex items-center justify-end gap-1.5 flex-wrap">
                                <span className={`inline-flex items-center px-2 py-px rounded text-[0.625rem] font-bold uppercase tracking-wider border ${data.sale_type === 'gst' ? 'bg-green-50 text-green-800 border-green-200' : 'bg-yellow-50 text-yellow-800 border-yellow-200'}`}>
                                    {data.sale_type === 'gst' ? 'GST' : 'On Approval'}
                                </span>
                                <span className="font-display text-base font-bold text-gray-900 tracking-tight leading-none">
                                    {isEdit ? record.bill_number : <span className="text-gray-300 italic text-xs">Auto-generated</span>}
                                </span>
                            </div>
                            <p className="text-[0.625rem] text-gray-400 mt-1 uppercase tracking-wider">
                                {formatDate(data.sale_date)}
                            </p>
                        </div>
                    </div>
                </header>

                {/* ─── BILL INFO + BILLED TO (merged row) ─── */}
                <section className="px-4 sm:px-6 pt-3 pb-3 border-b border-gray-100">
                    {sectionLabel('Bill & Customer')}
                    <div className="grid grid-cols-1 sm:grid-cols-6 gap-3 mb-3">
                        <div className="sm:col-span-3">
                            <SelectInput
                                label="Sale Type"
                                name="sale_type"
                                value={data.sale_type}
                                onChange={set}
                                required
                                options={[{ value: 'gst', label: 'GST Sale' }, { value: 'on_approval', label: 'On Approval' }]}
                            />
                        </div>
                        <div className="sm:col-span-3">
                            <DateInput
                                label="Sale Date"
                                name="sale_date"
                                value={data.sale_date}
                                onChange={set}
                                required
                                error={errors.sale_date}
                            />
                        </div>
                    </div>

                    <CustomerLookup
                        customers={customers}
                        value={{
                            customer_id: data.customer_id,
                            name:        data.customer_name,
                            mobile:      data.customer_mobile,
                            gst_number:  data.customer_gst,
                            address:     data.customer_address,
                        }}
                        onChange={(next) => setCustomer({
                            customer_id:      next.customer_id,
                            customer_name:    next.name,
                            customer_mobile:  next.mobile,
                            customer_gst:     next.gst_number,
                            customer_address: next.address,
                        })}
                        onCustomerAdded={onCustomerAdded}
                        errors={{
                            name:   errors.customer_name,
                            mobile: errors.customer_mobile,
                            gst_number: errors.customer_gst,
                        }}
                    />
                </section>

                {/* ─── LINE ITEMS ─── */}
                <section className="px-4 sm:px-6 pt-3 pb-3 border-b border-gray-100">
                    {sectionLabel('Items & Ornaments')}
                    {isEdit ? (
                        <SaleItemsSection
                            sale={record}
                            availableProducts={availableProducts}
                            localItems={data.items}
                            onLocalChange={setLocalItems}
                        />
                    ) : (
                        <SaleItemsSection
                            availableProducts={availableProducts}
                            localItems={data.items}
                            onLocalChange={setLocalItems}
                        />
                    )}
                </section>

                {/* ─── PAYMENT + TOTALS (two-col invoice footer) ─── */}
                <section className="px-4 sm:px-6 pt-3 pb-3">
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
                        {/* LEFT: Payment + Notes */}
                        <div className="lg:col-span-7 space-y-3">
                            <div>
                                {sectionLabel('Payment')}
                                <div className="grid grid-cols-2 gap-3">
                                    <SelectInput
                                        label="Mode"
                                        name="payment_mode"
                                        value={data.payment_mode}
                                        onChange={set}
                                        required
                                        options={PAYMENT_MODES}
                                    />
                                    <SelectInput
                                        label="Type"
                                        name="payment_type"
                                        value={data.payment_type}
                                        onChange={set}
                                        required
                                        options={[
                                            { value: 'full', label: 'Full Payment' },
                                            { value: 'credit', label: 'Credit' },
                                        ]}
                                    />
                                </div>
                                {data.payment_type === 'credit' && (
                                    <div className="mt-2 grid grid-cols-2 gap-2">
                                        <TextInput
                                            label="Paid Now"
                                            name="paid_amount"
                                            value={data.paid_amount}
                                            onChange={set}
                                            prefix="₹"
                                            type="number"
                                            placeholder="0"
                                        />
                                        <TextInput
                                            label="Credit Pending"
                                            name="credit_amount"
                                            value={data.credit_amount}
                                            onChange={set}
                                            prefix="₹"
                                            type="number"
                                            helper={Number(data.final_amount) > 0 && Number(data.paid_amount) > 0
                                                ? `Auto-calculated from total − paid`
                                                : undefined}
                                        />
                                    </div>
                                )}
                            </div>

                            <div>
                                {sectionLabel('Notes')}
                                <TextArea
                                    name="notes"
                                    value={data.notes}
                                    onChange={set}
                                    rows={2}
                                    placeholder="Any terms, conditions, or remarks..."
                                />
                            </div>
                        </div>

                        {/* RIGHT: Totals panel */}
                        <div className="lg:col-span-5">
                            <div className="relative bg-gradient-to-br from-primary-50/50 via-white to-primary-50/30 border border-primary-200/70 rounded-lg p-3.5 shadow-[0_4px_12px_-4px_rgba(212,163,26,0.2)]">
                                <div aria-hidden className="absolute top-0 left-0 w-4 h-4 border-t-2 border-l-2 border-primary-400 rounded-tl-lg" />
                                <div aria-hidden className="absolute top-0 right-0 w-4 h-4 border-t-2 border-r-2 border-primary-400 rounded-tr-lg" />
                                <div aria-hidden className="absolute bottom-0 left-0 w-4 h-4 border-b-2 border-l-2 border-primary-400 rounded-bl-lg" />
                                <div aria-hidden className="absolute bottom-0 right-0 w-4 h-4 border-b-2 border-r-2 border-primary-400 rounded-br-lg" />

                                <h4 className="font-display italic text-xs text-primary-700 mb-2">Bill Summary</h4>

                                <TextInput
                                    label="Final Amount (incl. GST)"
                                    name="final_amount"
                                    value={data.final_amount}
                                    onChange={set}
                                    required
                                    prefix="₹"
                                    type="number"
                                    error={errors.final_amount}
                                    helper="Edit any field below — the others back-calculate"
                                />

                                <div className="mt-2.5 pt-2.5 border-t border-dashed border-primary-200 space-y-1.5 text-xs">
                                    <div className="grid grid-cols-[1fr_auto] gap-2 items-center">
                                        <label className="text-gray-500">Taxable</label>
                                        <input
                                            type="number"
                                            step="0.01"
                                            name="taxable_value"
                                            value={data.taxable_value || ''}
                                            onChange={(e) => set('taxable_value', e.target.value)}
                                            placeholder="0.00"
                                            className="w-28 text-right tabular-nums font-semibold text-gray-800 bg-transparent border-b border-dashed border-primary-200 focus:border-primary-500 focus:ring-0 px-1"
                                        />
                                    </div>
                                    <div className="grid grid-cols-[1fr_auto] gap-2 items-center">
                                        <label className="text-gray-500">CGST (1.5%)</label>
                                        <input
                                            type="number"
                                            step="0.01"
                                            name="cgst"
                                            value={data.cgst || ''}
                                            onChange={(e) => set('cgst', e.target.value)}
                                            placeholder="0.00"
                                            className="w-28 text-right tabular-nums font-semibold text-gray-800 bg-transparent border-b border-dashed border-primary-200 focus:border-primary-500 focus:ring-0 px-1"
                                        />
                                    </div>
                                    <div className="grid grid-cols-[1fr_auto] gap-2 items-center">
                                        <label className="text-gray-500">SGST (1.5%)</label>
                                        <input
                                            type="number"
                                            step="0.01"
                                            name="sgst"
                                            value={data.sgst || ''}
                                            onChange={(e) => set('sgst', e.target.value)}
                                            placeholder="0.00"
                                            className="w-28 text-right tabular-nums font-semibold text-gray-800 bg-transparent border-b border-dashed border-primary-200 focus:border-primary-500 focus:ring-0 px-1"
                                        />
                                    </div>
                                    {itemsPreview.length > 0 && (
                                        <div className="pt-1.5 border-t border-dashed border-primary-100 space-y-1">
                                            <div className="flex items-center justify-between">
                                                <span className="text-gray-400 italic">Items total</span>
                                                <span className="text-gray-500 tabular-nums">₹{itemsTotal.toLocaleString('en-IN')}</span>
                                            </div>
                                            <div className="flex items-center justify-between">
                                                <span className="text-gray-400 italic">Total weight</span>
                                                <span className="text-gray-500 tabular-nums">{itemsWeight.toFixed(3)} g</span>
                                            </div>
                                        </div>
                                    )}
                                </div>

                                <div className="mt-2.5 pt-2.5 border-t-2 border-primary-400 flex items-center justify-between">
                                    <span className="font-display italic text-sm text-gray-700">Grand Total</span>
                                    <span className="font-display text-lg font-bold text-primary-800 tabular-nums">
                                        ₹{data.final_amount ? Number(data.final_amount).toLocaleString('en-IN') : '0'}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>

                {isEdit && (
                    <section className="px-4 sm:px-6 pt-1 pb-3">
                        <RelationTable
                            title="Payment History"
                            icon={
                                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                                </svg>
                            }
                            rows={record?.payments || []}
                            storeUrl={`/sales/${record.id}/payments`}
                            deleteUrl={(row) => `/sales/${record.id}/payments/${row.id}`}
                            defaultDraft={{
                                payment_date: new Date().toISOString().split('T')[0],
                                payment_mode: 'cash',
                                cash_amount: '',
                                metal_weight: '',
                                metal_purity: '',
                                reference_number: '',
                                notes: '',
                            }}
                            emptyMessage="No payments recorded yet."
                            columns={[
                                { key: 'payment_date', label: 'Date', render: r => formatDate(r.payment_date) },
                                { key: 'payment_mode', label: 'Mode', render: r => paymentModeLabel(r.payment_mode) },
                                { key: 'cash_amount', label: 'Cash', align: 'right', render: r => Number(r.cash_amount) ? `Rs.${Number(r.cash_amount).toLocaleString('en-IN')}` : <span className="text-gray-300">-</span> },
                                { key: 'metal_weight', label: 'Metal', align: 'right', mobileHidden: true, render: r => Number(r.metal_weight) ? `${Number(r.metal_weight).toLocaleString('en-IN')} g` : <span className="text-gray-300">-</span> },
                                { key: 'reference_number', label: 'Reference', mobileHidden: true, render: r => r.reference_number || <span className="text-gray-300">-</span> },
                            ]}
                            renderForm={({ draft, setDraft, errors: paymentErrors }) => {
                                const upd = (n, v) => setDraft(prev => ({ ...prev, [n]: v }));
                                const showCash = ['cash', 'upi', 'card', 'bank_transfer', 'cheque', 'adjustment', 'mixed'].includes(draft.payment_mode);
                                const showMetal = ['metal', 'mixed'].includes(draft.payment_mode);
                                const showRef = ['upi', 'card', 'bank_transfer', 'cheque', 'mixed'].includes(draft.payment_mode);
                                return (
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                        <DateInput label="Date" name="payment_date" value={draft.payment_date} onChange={upd} required error={paymentErrors.payment_date} />
                                        <SelectInput label="Mode" name="payment_mode" value={draft.payment_mode} onChange={upd} required options={PAYMENT_MODES} error={paymentErrors.payment_mode} />
                                        {showCash && <TextInput label="Amount" name="cash_amount" value={draft.cash_amount} onChange={upd} prefix="Rs." type="number" error={paymentErrors.cash_amount} />}
                                        {showMetal && <TextInput label="Metal Weight" name="metal_weight" value={draft.metal_weight} onChange={upd} suffix="g" type="number" error={paymentErrors.metal_weight} />}
                                        {showMetal && <TextInput label="Metal Purity" name="metal_purity" value={draft.metal_purity} onChange={upd} type="number" error={paymentErrors.metal_purity} />}
                                        {showRef && <TextInput label="Reference" name="reference_number" value={draft.reference_number} onChange={upd} error={paymentErrors.reference_number} />}
                                        <TextArea label="Notes" name="notes" value={draft.notes} onChange={upd} rows={1} className="sm:col-span-2" error={paymentErrors.notes} />
                                    </div>
                                );
                            }}
                        />
                    </section>
                )}

                {/* Decorative double-rule at bottom */}
                <div aria-hidden className="h-px bg-primary-200/60 mx-4 sm:mx-6" />
                <div aria-hidden className="h-0.5 bg-gradient-to-r from-transparent via-primary-500 to-transparent opacity-70 mt-[2px]" />
            </div>

            {/* ─── STICKY ACTION BAR ─── */}
            <div className="sticky bottom-0 bg-white/95 backdrop-blur-sm border-t border-gray-200 px-3 sm:px-6 py-2.5 flex flex-wrap items-center justify-end gap-2 sm:gap-3 shadow-[0_-4px_12px_-4px_rgba(17,24,39,0.08)]">
                <div className="mr-auto flex items-center gap-3 min-w-0">
                    <div className="flex items-baseline gap-2 flex-wrap">
                        <span className="text-[10px] font-semibold text-primary-700 uppercase tracking-[0.15em]">Total</span>
                        <span className="font-display text-lg sm:text-xl font-bold text-primary-800 tabular-nums">
                            ₹{Number(data.final_amount || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                        </span>
                    </div>
                    <span className="hidden md:inline text-[11px] text-gray-400">
                        <kbd className="px-1 py-0.5 bg-gray-100 rounded">⌘</kbd>+<kbd className="px-1 py-0.5 bg-gray-100 rounded">Enter</kbd> save
                        {isDirty && <span className="ml-2 text-primary-600 font-semibold">· unsaved</span>}
                    </span>
                </div>
                <Button variant="secondary" onClick={cancel} type="button">Cancel</Button>
                {!isEdit && (
                    <Button variant="secondary" type="button" onClick={() => submit(true)} disabled={processing}>
                        {processing ? '…' : 'Save & New'}
                    </Button>
                )}
                <Button type="submit" disabled={processing}>
                    {processing ? 'Saving…' : isEdit ? 'Update Bill' : 'Generate Bill'}
                </Button>
            </div>
        </form>
    );
}

const PreviewIcon = (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
    </svg>
);

const PaymentIcon = (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
    </svg>
);

function SalesPaymentsPanel({ sale }) {
    if (!sale) return null;

    return (
        <RelationTable
            title="Receipts"
            rows={sale.payments || []}
            storeUrl={`/sales/${sale.id}/payments`}
            deleteUrl={(row) => `/sales/${sale.id}/payments/${row.id}`}
            defaultDraft={{
                payment_date: today(),
                payment_mode: 'cash',
                cash_amount: '',
                metal_weight: '',
                metal_purity: '',
                reference_number: '',
                notes: '',
            }}
            emptyMessage="No receipts recorded yet."
            columns={[
                { key: 'payment_date', label: 'Date', render: r => formatDate(r.payment_date) },
                { key: 'payment_mode', label: 'Mode', render: r => paymentModeLabel(r.payment_mode) },
                { key: 'cash_amount', label: 'Cash', align: 'right', render: r => Number(r.cash_amount) ? `Rs.${Number(r.cash_amount).toLocaleString('en-IN')}` : <span className="text-gray-300">-</span> },
                { key: 'metal_weight', label: 'Metal', align: 'right', mobileHidden: true, render: r => Number(r.metal_weight) ? `${Number(r.metal_weight).toLocaleString('en-IN')} g` : <span className="text-gray-300">-</span> },
                { key: 'reference_number', label: 'Reference', mobileHidden: true, render: r => r.reference_number || <span className="text-gray-300">-</span> },
            ]}
            renderForm={({ draft, setDraft, errors }) => {
                const upd = (n, v) => setDraft(prev => ({ ...prev, [n]: v }));
                const showCash = ['cash', 'upi', 'card', 'bank_transfer', 'cheque', 'adjustment', 'mixed'].includes(draft.payment_mode);
                const showMetal = ['metal', 'mixed'].includes(draft.payment_mode);
                const showRef = ['upi', 'card', 'bank_transfer', 'cheque', 'mixed'].includes(draft.payment_mode);
                return (
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <DateInput label="Date" name="payment_date" value={draft.payment_date} onChange={upd} required error={errors.payment_date} />
                        <SelectInput label="Mode" name="payment_mode" value={draft.payment_mode} onChange={upd} required options={PAYMENT_MODES} error={errors.payment_mode} />
                        {showCash && <TextInput label="Amount" name="cash_amount" value={draft.cash_amount} onChange={upd} prefix="Rs." type="number" error={errors.cash_amount} />}
                        {showMetal && <TextInput label="Metal Weight" name="metal_weight" value={draft.metal_weight} onChange={upd} suffix="g" type="number" error={errors.metal_weight} />}
                        {showMetal && <TextInput label="Metal Purity" name="metal_purity" value={draft.metal_purity} onChange={upd} type="number" error={errors.metal_purity} />}
                        {showRef && <TextInput label="Reference" name="reference_number" value={draft.reference_number} onChange={upd} error={errors.reference_number} />}
                        <TextArea label="Notes" name="notes" value={draft.notes} onChange={upd} rows={1} className="sm:col-span-2" error={errors.notes} />
                    </div>
                );
            }}
        />
    );
}

export default function Index({ sales, filters, customers, availableProducts }) {
    const rows = sales?.data || [];
    const [localCustomers, setLocalCustomers] = useState(customers || []);
    const [previewSale, setPreviewSale] = useState(null);
    const [paymentsId, setPaymentsId] = useState(null);
    const selectedPaymentsSale = rows.find(row => row.id === paymentsId);

    const handleCustomerAdded = (customer) => {
        setLocalCustomers((prev) => [customer, ...prev]);
    };

    const rowActionItems = (row) => {
        const items = [];

        items.push({
            label: 'Preview & Print',
            icon: PreviewIcon,
            color: 'primary',
            onClick: () => setPreviewSale(row),
        });

        items.push({
            label: 'Receipts',
            icon: PaymentIcon,
            color: 'success',
            onClick: () => setPaymentsId(row.id),
        });

        if (row.customer?.mobile) {
            const msg = encodeURIComponent(`Bill No: ${row.bill_number}\nAmount: Rs.${row.final_amount}\nThank you - Mahendra Jewellers`);
            const mobile = normalizeIndianMobile(row.customer.mobile);
            items.push({
                label: 'Send WhatsApp',
                icon: WhatsAppIcon,
                color: 'success',
                onClick: () => window.open(`https://wa.me/${mobile}?text=${msg}`, '_blank', 'noopener'),
            });
        }

        if (row.sale_type === 'on_approval') {
            items.push({
                label: 'Convert to GST',
                icon: ConvertIcon,
                color: 'warning',
                confirm: 'Convert this On Approval sale to GST? This will mark attached products as sold.',
                onClick: () => router.post(`/sales/${row.id}/convert-to-gst`, {}, { preserveScroll: true }),
            });
            items.push({
                label: 'Return Items to Stock',
                icon: ReturnStockIcon,
                color: 'success',
                confirm: 'Return all items from this approval bill back to active stock?',
                onClick: () => router.post(`/sales/${row.id}/return-approval-to-stock`, {}, { preserveScroll: true }),
            });
        }

        return items;
    };

    return (
        <>
        <InvoicePreview
            open={!!previewSale}
            sale={previewSale}
            onClose={() => setPreviewSale(null)}
        />
        <ResourceIndex
            title="Sales"
            resourceUrl="/sales"
            rows={rows}
            links={sales?.links}
            meta={{ from: sales?.from, to: sales?.to, total: sales?.total }}
            filters={filters}
            formWide="invoice"
            rowActionItems={rowActionItems}
            emptyActionLabel="Create first sale"
            totals={{
                bill_number: (rs) => <span className="text-xs text-gray-500">{rs.length} bills shown</span>,
                final_amount: (rs) => formatMoney(rs.reduce((s, r) => s + Number(r.final_amount || 0), 0), { digits: 0 }),
            }}
            renderForm={({ record, onClose, reopenAsNew }) => (
                <FormContent
                    record={record}
                    onClose={onClose}
                    reopenAsNew={reopenAsNew}
                    customers={localCustomers}
                    onCustomerAdded={handleCustomerAdded}
                    availableProducts={availableProducts}
                />
            )}
            columns={[
                { key: 'bill_number', label: 'Bill No', sortable: true },
                { key: 'sale_type', label: 'Type', sortable: true, mobileHidden: true, render: r => <Badge color={r.sale_type === 'gst' ? 'success' : 'warning'}>{r.sale_type === 'gst' ? 'GST' : 'Approval'}</Badge> },
                { key: 'customer', label: 'Customer', render: r => r.customer?.name || '-' },
                { key: 'sale_date', label: 'Date', sortable: true, mobileHidden: true },
                { key: 'final_amount', label: 'Amount', sortable: true, align: 'right', render: r => <span className="font-semibold text-gray-800">₹{Number(r.final_amount).toLocaleString('en-IN')}</span> },
                { key: 'payment_type', label: 'Payment', sortable: true, mobileHidden: true, render: r => <Badge color={r.payment_type === 'full' ? 'success' : 'danger'}>{r.payment_type}</Badge> },
            ]}
        />
        <SlideOver
            open={!!selectedPaymentsSale}
            onClose={() => setPaymentsId(null)}
            title={`Receipts - ${selectedPaymentsSale?.bill_number || ''}`}
            subtitle={selectedPaymentsSale?.customer?.name}
            wide="90"
        >
            <SalesPaymentsPanel sale={selectedPaymentsSale} />
        </SlideOver>
        </>
    );
}
