import { useForm } from '@inertiajs/react';
import { useRef } from 'react';
import ResourceIndex from '../../Components/ResourceIndex';
import { TextInput, TextArea } from '../../Components/Form';
import { DrawerFooter, useDrawerDirty, useDrawerCancel } from '../../Components/SlideOver';
import Button from '../../Components/Button';
import { useDirtyForm } from '../../hooks/useDirtyForm';
import { useFormKeyboard } from '../../hooks/useFormKeyboard';
import { isValidMobile, isValidGstin } from '../../lib/parse';

const IdentityIcon = (
    <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 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
    </svg>
);
const ContactIcon = (
    <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 5a2 2 0 012-2h3.28a1 1 0 01.95.68l1.5 4.49a1 1 0 01-.5 1.21l-2.26 1.13a11 11 0 005.52 5.52l1.13-2.26a1 1 0 011.21-.5l4.49 1.5a1 1 0 01.68.95V19a2 2 0 01-2 2h-1C9.72 21 3 14.28 3 6V5z" />
    </svg>
);
const TaxIcon = (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
    </svg>
);
const LocationIcon = (
    <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.657 16.657L13.414 20.9a2 2 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
        <path strokeLinecap="round" strokeLinejoin="round" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
    </svg>
);

function SectionHeader({ icon, label, optional }) {
    return (
        <div className="flex items-center gap-2 mb-4">
            <span className="inline-flex items-center justify-center w-7 h-7 rounded-lg bg-gradient-to-br from-primary-50 to-primary-100 border border-primary-200/60 text-primary-700 shadow-[inset_0_1px_0_rgba(255,255,255,0.6)]">
                {icon}
            </span>
            <h3 className="text-[0.8125rem] font-bold text-gray-700 uppercase tracking-wider">{label}</h3>
            {optional && <span className="ml-auto text-[0.6875rem] font-medium text-gray-400 uppercase tracking-wide">Optional</span>}
        </div>
    );
}

function FormContent({ record, onClose, reopenAsNew }) {
    const isEdit = !!record;
    const formRef = useRef(null);
    const { data, setData, post, put, processing, errors } = useForm({
        name: record?.name || '', mobile: record?.mobile || '',
        gst_number: record?.gst_number || '', address: record?.address || '',
        opening_receivable: record?.opening_receivable || '',
        opening_payable: record?.opening_payable || '',
        opening_metal_receivable: record?.opening_metal_receivable || '',
        opening_metal_payable: record?.opening_metal_payable || '',
    });
    const { isDirty, markClean } = useDirtyForm(data);
    useDrawerDirty(isDirty);
    const cancel = useDrawerCancel(onClose);

    const set = (n, v) => setData(n, v);
    const save = (andNew = false) => {
        const opts = { onSuccess: () => { markClean(); andNew ? reopenAsNew?.() : onClose(); } };
        isEdit ? put(`/customers/${record.id}`, opts) : post('/customers', opts);
    };
    const handleSubmit = (e) => { e.preventDefault(); save(false); };
    useFormKeyboard(formRef, { onSubmit: () => save(false), onCancel: onClose });

    const mobileValid = data.mobile && isValidMobile(data.mobile) ? 'Valid' : null;
    const mobileError = data.mobile && !isValidMobile(data.mobile) ? '10 digits required' : null;

    const gstinUpper = (data.gst_number || '').toUpperCase();
    const gstinValid = gstinUpper && isValidGstin(gstinUpper) ? 'Valid format' : null;
    const gstinError = gstinUpper && !isValidGstin(gstinUpper) ? 'Should be 15-char GSTIN' : null;

    return (
        <form ref={formRef} onSubmit={handleSubmit} className="max-w-2xl mx-auto">
            <div className="relative bg-white rounded-xl border border-gray-100 shadow-[0_1px_2px_rgba(17,24,39,0.04)] overflow-hidden">
                <div aria-hidden className="absolute top-0 left-5 right-5 h-[2px] bg-gradient-to-r from-transparent via-primary-500/60 to-transparent pointer-events-none" />

                <header className="px-6 pt-6 pb-5 border-b border-gray-100">
                    <h2 className="font-display text-lg font-bold text-gray-800 tracking-tight">
                        {isEdit ? 'Edit Customer' : 'New Customer'}
                    </h2>
                    <p className="text-xs text-gray-500 mt-1 leading-relaxed">
                        {isEdit
                            ? `Update contact and billing information for ${record?.name || 'this customer'}.`
                            : 'Add a new customer to your directory.'}
                    </p>
                </header>

                <div className="px-6 pt-5 pb-5">
                    <SectionHeader icon={IdentityIcon} label="Identity" />
                    <TextInput
                        label="Full Name"
                        name="name"
                        value={data.name}
                        onChange={set}
                        required
                        error={errors.name}
                        placeholder="e.g. Rajesh Kumar"
                        helper="As it should appear on the bill."
                    />
                </div>

                <div className="h-px bg-gray-100 mx-6" />

                <div className="px-6 py-5">
                    <SectionHeader icon={ContactIcon} label="Contact" />
                    <TextInput
                        label="Mobile Number"
                        name="mobile"
                        value={data.mobile}
                        onChange={set}
                        required
                        error={mobileError || errors.mobile}
                        valid={mobileValid}
                        placeholder="10-digit mobile"
                        prefix="+91"
                        helper="Used for WhatsApp bill delivery."
                    />
                </div>

                <div className="h-px bg-gray-100 mx-6" />

                <div className="px-6 py-5">
                    <SectionHeader icon={TaxIcon} label="Tax Details" optional />
                    <TextInput
                        label="GST Number"
                        name="gst_number"
                        value={data.gst_number}
                        onChange={(_, v) => set('gst_number', v.toUpperCase())}
                        error={gstinError || errors.gst_number}
                        valid={gstinValid}
                        placeholder="e.g. 29ABCDE1234F1Z5"
                        helper="Required only for B2B sales with input credit."
                    />
                </div>

                <div className="h-px bg-gray-100 mx-6" />

                <div className="px-6 pt-5 pb-6">
                    <SectionHeader icon={LocationIcon} label="Address" optional />
                    <TextArea
                        label="Billing Address"
                        name="address"
                        value={data.address}
                        onChange={set}
                        placeholder="Street, city, state, PIN code"
                    />
                </div>

                <div className="h-px bg-gray-100 mx-6" />

                <div className="px-6 pt-5 pb-6">
                    <SectionHeader icon={TaxIcon} label="Opening Balances" optional />
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <TextInput label="Receivable From Party" name="opening_receivable" value={data.opening_receivable} onChange={set} prefix="Rs." type="number" error={errors.opening_receivable} />
                        <TextInput label="Payable To Party" name="opening_payable" value={data.opening_payable} onChange={set} prefix="Rs." type="number" error={errors.opening_payable} />
                        <TextInput label="Metal Receivable" name="opening_metal_receivable" value={data.opening_metal_receivable} onChange={set} suffix="g" type="number" error={errors.opening_metal_receivable} />
                        <TextInput label="Metal Payable" name="opening_metal_payable" value={data.opening_metal_payable} onChange={set} suffix="g" type="number" error={errors.opening_metal_payable} />
                    </div>
                </div>
            </div>

            <DrawerFooter>
                <p className="text-[11px] text-gray-400 mr-auto hidden sm:block">
                    <span className="text-primary-600">★</span> required · <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> to save
                </p>
                <Button variant="secondary" onClick={cancel} type="button">Cancel</Button>
                {!isEdit && (
                    <Button variant="secondary" type="button" onClick={() => save(true)} disabled={processing}>
                        {processing ? '…' : 'Save & Add Another'}
                    </Button>
                )}
                <Button type="submit" disabled={processing}>
                    {processing ? 'Saving…' : isEdit ? 'Update Customer' : 'Create Customer'}
                </Button>
            </DrawerFooter>
        </form>
    );
}

export default function Index({ customers, filters }) {
    return (
        <ResourceIndex
            title="Customers"
            resourceUrl="/customers"
            rows={customers?.data || []}
            links={customers?.links}
            meta={{ from: customers?.from, to: customers?.to, total: customers?.total }}
            filters={filters}
            emptyActionLabel="Add first customer"
            renderForm={({ record, onClose, reopenAsNew }) => (
                <FormContent record={record} onClose={onClose} reopenAsNew={reopenAsNew} />
            )}
            columns={[
                { key: 'name', label: 'Name', sortable: true },
                { key: 'mobile', label: 'Mobile', sortable: true },
                { key: 'gst_number', label: 'GST', mobileHidden: true },
                { key: 'sales_count', label: 'Sales', align: 'center', render: r => (
                    <span className="inline-flex items-center justify-center min-w-[24px] h-6 rounded-full bg-primary-100 text-primary-700 text-xs font-semibold px-2 tabular-nums">
                        {r.sales_count || 0}
                    </span>
                )},
            ]}
        />
    );
}
