import { useForm } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import ResourceIndex from '../../Components/ResourceIndex';
import Badge from '../../Components/Badge';
import { FormSection, TextInput, SelectInput, TextArea, DateInput } from '../../Components/Form';
import Button from '../../Components/Button';

/**
 * Sales Returns form — autopopulates from a single lookup row.
 * Type any of { bill number, barcode, customer name, mobile } and the
 * matched sale + customer are selected. Barcode matches against any line
 * item's product_code on a sale.
 */
function FormContent({ record, onClose, sales, customers }) {
    const isEdit = !!record;

    const { data, setData, post, put, processing, errors } = useForm({
        sale_id: record?.sale_id || '', customer_id: record?.customer_id || '',
        return_date: record?.return_date || new Date().toISOString().split('T')[0],
        refund_amount: record?.refund_amount || '', refund_mode: record?.refund_mode || 'cash',
        reason: record?.reason || '',
    });
    const [lookup, setLookup] = useState({ bill: '', barcode: '', name: '', mobile: '' });

    const selectedSale = useMemo(
        () => (sales || []).find(s => String(s.id) === String(data.sale_id)),
        [sales, data.sale_id]
    );
    const selectedCustomer = useMemo(
        () => (customers || []).find(c => String(c.id) === String(data.customer_id)),
        [customers, data.customer_id]
    );

    const digits = (s) => String(s ?? '').replace(/\D/g, '');
    const clean  = (s) => String(s ?? '').trim().toLowerCase();
    const barcodeMatches = (product, val) => {
        const code = clean(product?.product_code);
        if (!code) return false;
        if (code === val) return true;
        if (val.startsWith('ch-') && clean(product?.category?.name) === 'chain') {
            return code === `mj-${val.slice(3)}`;
        }
        return false;
    };

    const pickSale = (sale) => {
        setData(prev => ({ ...prev, sale_id: sale.id, customer_id: sale.customer_id || '' }));
    };

    const findAndSelect = (field, v) => {
        const val = clean(v);
        if (!val) return;
        let matchedSale = null;

        if (field === 'bill' && val.length >= 2) {
            matchedSale = (sales || []).find(s => clean(s.bill_number) === val)
                       || (sales || []).find(s => clean(s.bill_number).includes(val));
        }
        if (field === 'barcode' && val.length >= 3) {
            matchedSale = (sales || []).find(s => (s.items || []).some(i => barcodeMatches(i.product, val)));
        }
        if (field === 'mobile') {
            const d = digits(v);
            if (d.length >= 5) {
                matchedSale = (sales || []).find(s => digits(s.customer?.mobile) === d);
                if (!matchedSale) {
                    const cust = (customers || []).find(c => digits(c.mobile) === d);
                    if (cust) setData('customer_id', cust.id);
                }
            }
        }
        if (field === 'name' && val.length >= 3) {
            matchedSale = (sales || []).find(s => clean(s.customer?.name) === val);
            if (!matchedSale) {
                const cust = (customers || []).find(c => clean(c.name) === val);
                if (cust) setData('customer_id', cust.id);
            }
        }
        if (matchedSale) pickSale(matchedSale);
    };

    const setLookupField = (field, v) => {
        setLookup(l => ({ ...l, [field]: v }));
        findAndSelect(field, v);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        isEdit ? put(`/credit-notes/${record.id}`, { onSuccess: onClose }) : post('/credit-notes', { onSuccess: onClose });
    };
    const set = (n, v) => setData(n, v);

    const billSuggestions    = useMemo(() => (sales || []).filter(s => s.bill_number).map(s => ({ value: s.bill_number, label: s.customer?.name || '' })), [sales]);
    const nameSuggestions    = useMemo(() => (customers || []).filter(c => c.name).map(c => ({ value: c.name, label: c.mobile || '' })), [customers]);
    const mobileSuggestions  = useMemo(() => (customers || []).filter(c => c.mobile).map(c => ({ value: c.mobile, label: c.name || '' })), [customers]);

    return (
        <form onSubmit={handleSubmit} className="space-y-4">
            <FormSection title="Find Original Bill" columns={1}>
                <div className="grid grid-cols-1 sm:grid-cols-4 gap-3">
                    <TextInput label="Bill Number" name="bill" value={lookup.bill}
                        onChange={(_, v) => setLookupField('bill', v)}
                        placeholder="MJ/GST/000123"
                        suggestions={billSuggestions} autoComplete="off" />
                    <TextInput label="Barcode (Product Code)" name="barcode" value={lookup.barcode}
                        onChange={(_, v) => setLookupField('barcode', v)}
                        placeholder="MJ-000123" />
                    <TextInput label="Customer Name" name="name" value={lookup.name}
                        onChange={(_, v) => setLookupField('name', v)}
                        suggestions={nameSuggestions} autoComplete="off" />
                    <TextInput label="Mobile" name="mobile" value={lookup.mobile}
                        onChange={(_, v) => setLookupField('mobile', v)}
                        prefix="+91"
                        suggestions={mobileSuggestions} autoComplete="off" />
                </div>
                {selectedSale && (
                    <div className="mt-2 flex items-center gap-3 px-3 py-2 rounded-md bg-gradient-to-r from-primary-50/60 to-transparent border border-primary-100">
                        <div className="flex-1">
                            <p className="text-sm font-semibold text-gray-800">{selectedSale.bill_number}</p>
                            <p className="text-xs text-gray-500">
                                {selectedCustomer?.name || '(no customer)'} · {selectedCustomer?.mobile || '—'}
                                {' · '}₹{Number(selectedSale.final_amount || 0).toLocaleString('en-IN')}
                            </p>
                        </div>
                        <button type="button" onClick={() => { setData({ ...data, sale_id: '', customer_id: '' }); setLookup({ bill: '', barcode: '', name: '', mobile: '' }); }}
                            className="text-xs text-gray-400 hover:text-gray-700 font-medium">Clear</button>
                    </div>
                )}
            </FormSection>

            <FormSection title="Return Details" columns={2}>
                <SelectInput label="Original Bill" name="sale_id" value={data.sale_id} onChange={set} required error={errors.sale_id}
                    placeholder="Select bill" options={(sales || []).map(s => ({ value: s.id, label: s.bill_number }))} />
                <SelectInput label="Customer" name="customer_id" value={data.customer_id} onChange={set} required error={errors.customer_id}
                    placeholder="Select" options={(customers || []).map(c => ({ value: c.id, label: c.name }))} />
                <DateInput label="Return Date" name="return_date" value={data.return_date} onChange={set} required />
                <TextInput label="Refund Amount" name="refund_amount" value={data.refund_amount} onChange={set} required prefix="₹" type="number" />
                <SelectInput label="Refund Mode" name="refund_mode" value={data.refund_mode} onChange={set} required
                    options={[{ value: 'cash', label: 'Cash' }, { value: 'bank_transfer', label: 'Bank Transfer' }, { value: 'adjust_future', label: 'Adjust Against Future' }]} />
            </FormSection>
            <FormSection title="Reason" columns={1}>
                <TextArea name="reason" value={data.reason} onChange={set} rows={2} />
            </FormSection>
            <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-100">
                <Button variant="secondary" onClick={onClose} type="button">Cancel</Button>
                <Button type="submit" disabled={processing}>{processing ? 'Saving...' : 'Save'}</Button>
            </div>
        </form>
    );
}

export default function Index({ creditNotes, filters, sales, customers }) {
    return (
        <ResourceIndex
            title="Sales Returns"
            resourceUrl="/credit-notes"
            rows={creditNotes?.data || []}
            links={creditNotes?.links}
            meta={{ from: creditNotes?.from, to: creditNotes?.to, total: creditNotes?.total }}
            filters={filters}
            renderForm={({ record, onClose }) => <FormContent record={record} onClose={onClose} sales={sales} customers={customers} />}
            columns={[
                { key: 'credit_note_number', label: 'CN No', sortable: true },
                { key: 'sale', label: 'Original Bill', mobileHidden: true, render: r => r.sale?.bill_number || '-' },
                { key: 'customer', label: 'Customer', render: r => r.customer?.name || '-' },
                { key: 'return_date', label: 'Date', sortable: true, mobileHidden: true },
                { key: 'refund_amount', label: 'Refund', sortable: true, align: 'right', render: r => <span className="font-semibold text-gray-800">₹{Number(r.refund_amount).toLocaleString('en-IN')}</span> },
                { key: 'refund_mode', label: 'Mode', sortable: true, mobileHidden: true, render: r => <Badge>{r.refund_mode?.replace(/_/g, ' ')}</Badge> },
            ]}
        />
    );
}
