import { Head, Link, useForm } from '@inertiajs/react';
import { useState } from 'react';
import type { FormEvent, InputHTMLAttributes } from 'react';
import locationRoutes from '@/routes/locations';
import businessRoutes from '@/routes/businesses';
import contactRoutes from '@/routes/contacts';

type Warehouse = {
    id: number;
    name: string;
    code: string | null;
    is_default: boolean;
};

type Branch = {
    id: number;
    name: string;
    code: string | null;
    phone: string | null;
    address: string | null;
    is_default: boolean;
    warehouses: Warehouse[];
};

export default function LocationsIndex({ business, branches }: { business: { id: number; name: string }; branches: Branch[] }) {
    const branchForm = useForm({ name: '', code: '', phone: '', address: '' });
    const warehouseForm = useForm({ name: '', code: '' });
    const [warehouseBranchId, setWarehouseBranchId] = useState<number | null>(null);

    function createBranch(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        branchForm.post(locationRoutes.branches.store.url(), { onSuccess: () => branchForm.reset() });
    }

    function createWarehouse(event: FormEvent<HTMLFormElement>, branchId: number) {
        event.preventDefault();
        warehouseForm.post(locationRoutes.warehouses.store.url(branchId), { onSuccess: () => warehouseForm.reset() });
    }

    return (
        <>
            <Head title={`Locations | ${business.name}`} />
            <main className="min-h-screen bg-stone-50 text-stone-900 dark:bg-stone-950 dark:text-stone-100">
                <header className="border-b border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-900">
                    <div className="mx-auto flex max-w-6xl items-center justify-between px-5 py-4">
                        <Link href={businessRoutes.index.url()} className="text-sm font-bold tracking-wide text-emerald-700 dark:text-emerald-400">PC SUITE</Link>
                        <nav className="flex items-center gap-2 text-sm">
                            <Link href={contactRoutes.index.url()} className="rounded-lg px-3 py-2 font-medium text-stone-600 hover:bg-stone-100 dark:text-stone-300 dark:hover:bg-stone-800">Contacts</Link>
                            <Link href={businessRoutes.index.url()} className="rounded-lg px-3 py-2 font-medium text-stone-600 hover:bg-stone-100 dark:text-stone-300 dark:hover:bg-stone-800">Switch business</Link>
                        </nav>
                    </div>
                </header>

                <div className="mx-auto max-w-6xl px-5 py-12">
                    <p className="text-sm font-semibold text-emerald-700 dark:text-emerald-400">BUSINESS SETUP</p>
                    <h1 className="mt-2 text-3xl font-semibold tracking-tight">Branches and warehouses</h1>
                    <p className="mt-2 text-stone-500 dark:text-stone-400">Set up where your team works and where your stock is kept for <span className="font-medium text-stone-800 dark:text-stone-200">{business.name}</span>.</p>

                    <div className="mt-9 grid gap-6 lg:grid-cols-[1.25fr_0.75fr]">
                        <section className="space-y-5">
                            {branches.length === 0 && <div className="rounded-2xl border border-dashed border-stone-300 bg-white p-7 dark:border-stone-700 dark:bg-stone-900">
                                <h2 className="font-semibold">Add your first branch</h2>
                                <p className="mt-1 text-sm text-stone-500 dark:text-stone-400">PC Suite will create a Main warehouse under it automatically.</p>
                            </div>}
                            {branches.map((branch) => <article key={branch.id} className="rounded-2xl border border-stone-200 bg-white p-6 dark:border-stone-800 dark:bg-stone-900">
                                <div className="flex flex-wrap items-start justify-between gap-3">
                                    <div>
                                        <div className="flex flex-wrap items-center gap-2">
                                            <h2 className="text-lg font-semibold">{branch.name}</h2>
                                            {branch.is_default && <span className="rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300">Default branch</span>}
                                        </div>
                                        <p className="mt-1 text-sm text-stone-500 dark:text-stone-400">{[branch.code, branch.address, branch.phone].filter(Boolean).join(' · ') || 'Branch location'}</p>
                                    </div>
                                </div>

                                <div className="mt-6 border-t border-stone-100 pt-5 dark:border-stone-800">
                                    <div className="flex items-center justify-between gap-3">
                                        <h3 className="text-sm font-semibold">Warehouses</h3>
                                        <div className="flex items-center gap-3">
                                            <span className="text-xs text-stone-500">{branch.warehouses.length} {branch.warehouses.length === 1 ? 'location' : 'locations'}</span>
                                            <button type="button" onClick={() => { setWarehouseBranchId(warehouseBranchId === branch.id ? null : branch.id); warehouseForm.reset(); }} className="text-xs font-semibold text-emerald-700 hover:underline dark:text-emerald-400">{warehouseBranchId === branch.id ? 'Close' : 'Add warehouse'}</button>
                                        </div>
                                    </div>
                                    <ul className="mt-3 space-y-2">
                                        {branch.warehouses.map((warehouse) => <li key={warehouse.id} className="flex items-center justify-between rounded-xl bg-stone-50 px-4 py-3 text-sm dark:bg-stone-800/70">
                                            <span className="font-medium">{warehouse.name}{warehouse.code && <span className="ml-2 font-normal text-stone-500">{warehouse.code}</span>}</span>
                                            {warehouse.is_default && <span className="text-xs font-medium text-emerald-700 dark:text-emerald-400">Default</span>}
                                        </li>)}
                                    </ul>
                                    {warehouseBranchId === branch.id && <form onSubmit={(event) => createWarehouse(event, branch.id)} className="mt-4 grid gap-3 sm:grid-cols-[1fr_0.7fr_auto]">
                                        <label className="text-xs font-medium text-stone-600 dark:text-stone-300">New warehouse name
                                            <input required value={warehouseForm.data.name} onChange={(event) => warehouseForm.setData('name', event.target.value)} placeholder="e.g. Repairs stockroom" className="mt-1.5 w-full rounded-lg border border-stone-300 bg-white px-3 py-2 text-sm outline-none focus:border-emerald-600 dark:border-stone-700 dark:bg-stone-950" />
                                            {warehouseForm.errors.name && <span className="mt-1 block text-red-600">{warehouseForm.errors.name}</span>}
                                        </label>
                                        <label className="text-xs font-medium text-stone-600 dark:text-stone-300">Code <span className="font-normal">(optional)</span>
                                            <input value={warehouseForm.data.code} onChange={(event) => warehouseForm.setData('code', event.target.value)} placeholder="WH-02" className="mt-1.5 w-full rounded-lg border border-stone-300 bg-white px-3 py-2 text-sm outline-none focus:border-emerald-600 dark:border-stone-700 dark:bg-stone-950" />
                                            {warehouseForm.errors.code && <span className="mt-1 block text-red-600">{warehouseForm.errors.code}</span>}
                                        </label>
                                        <button disabled={warehouseForm.processing} className="self-end rounded-lg border border-stone-300 px-3 py-2 text-sm font-semibold hover:bg-stone-50 disabled:opacity-60 dark:border-stone-700 dark:hover:bg-stone-800">Add warehouse</button>
                                    </form>}
                                </div>
                            </article>)}
                        </section>

                        <section className="h-fit rounded-2xl border border-stone-200 bg-white p-6 dark:border-stone-800 dark:bg-stone-900">
                            <h2 className="text-lg font-semibold">Add a branch</h2>
                            <p className="mt-1 text-sm text-stone-500 dark:text-stone-400">A main warehouse is created with each new branch.</p>
                            <form onSubmit={createBranch} className="mt-6 space-y-4">
                                <Field label="Branch name" value={branchForm.data.name} error={branchForm.errors.name} onChange={(value) => branchForm.setData('name', value)} placeholder="e.g. Ikeja Branch" required />
                                <Field label="Branch code" value={branchForm.data.code} error={branchForm.errors.code} onChange={(value) => branchForm.setData('code', value)} placeholder="e.g. LAG-01" />
                                <Field label="Phone" value={branchForm.data.phone} error={branchForm.errors.phone} onChange={(value) => branchForm.setData('phone', value)} type="tel" />
                                <Field label="Address" value={branchForm.data.address} error={branchForm.errors.address} onChange={(value) => branchForm.setData('address', value)} />
                                <button disabled={branchForm.processing} className="w-full rounded-xl bg-emerald-700 px-4 py-3 text-sm font-semibold text-white hover:bg-emerald-800 disabled:opacity-60">{branchForm.processing ? 'Saving…' : 'Create branch'}</button>
                            </form>
                        </section>
                    </div>

                    {branches.length > 0 && <div className="mt-8 flex justify-end"><Link href={businessRoutes.index.url()} className="rounded-xl border border-stone-300 px-4 py-2.5 text-sm font-semibold hover:bg-white dark:border-stone-700 dark:hover:bg-stone-900">Done with locations</Link></div>}
                </div>
            </main>
        </>
    );
}

function Field({ label, value, error, onChange, ...attributes }: { label: string; value: string; error?: string; onChange: (value: string) => void } & InputHTMLAttributes<HTMLInputElement>) {
    return (
        <label className="block text-sm font-medium">{label}
            <input value={value} onChange={(event) => onChange(event.target.value)} {...attributes} className="mt-2 w-full rounded-xl border border-stone-300 bg-white px-3 py-2.5 outline-none focus:border-emerald-600 focus:ring-2 focus:ring-emerald-600/20 dark:border-stone-700 dark:bg-stone-950" />
            {error && <span className="mt-1 block text-sm text-red-600">{error}</span>}
        </label>
    );
}
