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

type Contact = {
    id: number;
    contact_number: string;
    type: 'customer' | 'supplier' | 'both';
    entity_type: 'individual' | 'business';
    name: string;
    contact_person: string | null;
    email: string | null;
    phone: string | null;
    address: string | null;
    notes: string | null;
};

type ContactLink = { url: string | null; label: string; active: boolean };

export default function ContactsIndex({ business, contacts, type, search }: {
    business: { id: number; name: string };
    contacts: { data: Contact[]; links: ContactLink[]; current_page: number; last_page: number; total: number };
    type: 'all' | 'customer' | 'supplier';
    search: string;
}) {
    const [showForm, setShowForm] = useState(false);
    const form = useForm({
        type: 'customer',
        entity_type: 'individual',
        name: '',
        contact_person: '',
        email: '',
        phone: '',
        address: '',
        notes: '',
    });
    const searchForm = useForm({ search });

    function createContact(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        form.post(contactRoutes.store.url(), {
            onSuccess: () => {
                form.reset();
                setShowForm(false);
            },
        });
    }

    function searchContacts(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        router.get(contactRoutes.index.url({ query: { type, search: searchForm.data.search } }), {}, {
            preserveState: true,
            replace: true,
        });
    }

    return (
        <>
            <Head title={`Customers and suppliers | ${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 flex-wrap items-center justify-between gap-3 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={locationRoutes.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">Locations</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">Businesses</Link>
                        </nav>
                    </div>
                </header>

                <div className="mx-auto max-w-6xl px-5 py-10 sm:py-12">
                    <div className="flex flex-wrap items-end justify-between gap-5">
                        <div>
                            <p className="text-sm font-semibold text-emerald-700 dark:text-emerald-400">{business.name}</p>
                            <h1 className="mt-2 text-3xl font-semibold tracking-tight">Customers and suppliers</h1>
                            <p className="mt-2 text-stone-500 dark:text-stone-400">Keep one contact profile even when a business is both a customer and supplier.</p>
                        </div>
                        <button type="button" onClick={() => setShowForm(!showForm)} className="rounded-xl bg-emerald-700 px-4 py-3 text-sm font-semibold text-white hover:bg-emerald-800">{showForm ? 'Close form' : 'Add contact'}</button>
                    </div>

                    <div className="mt-8 grid items-start gap-6 lg:grid-cols-[1fr_360px]">
                        <section className="min-w-0">
                            <div className="flex flex-wrap items-center justify-between gap-4">
                                <div className="flex gap-1 rounded-xl bg-stone-200/70 p-1 dark:bg-stone-800">
                                    {(['all', 'customer', 'supplier'] as const).map((filter) => <Link key={filter} href={contactRoutes.index.url({ query: { type: filter, search } })} className={`rounded-lg px-3 py-2 text-sm font-medium capitalize ${type === filter ? 'bg-white text-stone-900 shadow-sm dark:bg-stone-700 dark:text-white' : 'text-stone-600 hover:text-stone-900 dark:text-stone-400 dark:hover:text-white'}`}>{filter === 'all' ? 'All contacts' : `${filter}s`}</Link>)}
                                </div>
                                <form onSubmit={searchContacts} className="flex w-full gap-2 sm:w-auto">
                                    <input aria-label="Search contacts" value={searchForm.data.search} onChange={(event) => searchForm.setData('search', event.target.value)} placeholder="Search name, number, email…" className="min-w-0 flex-1 rounded-xl border border-stone-300 bg-white px-3 py-2.5 text-sm outline-none focus:border-emerald-600 dark:border-stone-700 dark:bg-stone-900 sm:w-64" />
                                    <button className="rounded-xl border border-stone-300 px-3 py-2.5 text-sm font-semibold hover:bg-white dark:border-stone-700 dark:hover:bg-stone-900">Search</button>
                                </form>
                            </div>

                            <div className="mt-5 overflow-hidden rounded-2xl border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-900">
                                {contacts.data.length === 0 ? <div className="px-6 py-14 text-center">
                                    <h2 className="font-semibold">No contacts found</h2>
                                    <p className="mt-1 text-sm text-stone-500 dark:text-stone-400">Add your first customer or supplier, or change your search.</p>
                                </div> : <>
                                    <div className="hidden grid-cols-[minmax(180px,1.4fr)_minmax(100px,0.8fr)_minmax(120px,1fr)_minmax(120px,1fr)] gap-4 border-b border-stone-200 bg-stone-50 px-5 py-3 text-xs font-semibold uppercase tracking-wide text-stone-500 dark:border-stone-800 dark:bg-stone-800/60 sm:grid">
                                        <span>Contact</span><span>Type</span><span>Email</span><span>Phone</span>
                                    </div>
                                    <ul className="divide-y divide-stone-100 dark:divide-stone-800">
                                        {contacts.data.map((contact) => <li key={contact.id} className="grid gap-3 px-5 py-4 sm:grid-cols-[minmax(180px,1.4fr)_minmax(100px,0.8fr)_minmax(120px,1fr)_minmax(120px,1fr)] sm:items-center sm:gap-4">
                                            <div className="min-w-0">
                                                <p className="truncate font-semibold">{contact.name}</p>
                                                <p className="mt-1 truncate text-xs text-stone-500">{contact.contact_number} · {contact.entity_type}</p>
                                                {contact.contact_person && <p className="mt-1 truncate text-xs text-stone-500">Contact: {contact.contact_person}</p>}
                                            </div>
                                            <span className="w-fit rounded-full bg-stone-100 px-2.5 py-1 text-xs font-medium capitalize text-stone-700 dark:bg-stone-800 dark:text-stone-300">{contact.type}</span>
                                            <span className="truncate text-sm text-stone-600 dark:text-stone-300">{contact.email || '—'}</span>
                                            <span className="truncate text-sm text-stone-600 dark:text-stone-300">{contact.phone || '—'}</span>
                                        </li>)}
                                    </ul>
                                </>}
                                <div className="flex flex-wrap items-center justify-between gap-3 border-t border-stone-100 px-5 py-3 dark:border-stone-800">
                                    <p className="text-xs text-stone-500">{contacts.total} {contacts.total === 1 ? 'contact' : 'contacts'} · Page {contacts.current_page} of {contacts.last_page}</p>
                                    <div className="flex gap-1">
                                        {contacts.links.slice(0, 1).concat(contacts.links.slice(-1)).map((link, index) => link.url ? <Link key={`${index}-${link.label}`} href={link.url} className={`rounded-lg px-3 py-1.5 text-sm ${link.active ? 'bg-emerald-700 font-semibold text-white' : 'border border-stone-200 hover:bg-stone-50 dark:border-stone-700 dark:hover:bg-stone-800'}`}>{link.label.includes('Previous') ? 'Previous' : link.label.includes('Next') ? 'Next' : link.label}</Link> : <span key={`${index}-${link.label}`} className="px-3 py-1.5 text-sm text-stone-400">{link.label.includes('Previous') ? 'Previous' : 'Next'}</span>)}
                                    </div>
                                </div>
                            </div>
                        </section>

                        {showForm && <section className="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 contact</h2>
                            <p className="mt-1 text-sm text-stone-500 dark:text-stone-400">Contact numbers are generated automatically.</p>
                            <form onSubmit={createContact} className="mt-5 space-y-4">
                                <label className="block text-sm font-medium">Record as
                                    <select value={form.data.type} onChange={(event) => form.setData('type', event.target.value as typeof form.data.type)} className="mt-2 w-full rounded-xl border border-stone-300 bg-white px-3 py-2.5 dark:border-stone-700 dark:bg-stone-950">
                                        <option value="customer">Customer</option><option value="supplier">Supplier</option><option value="both">Customer and supplier</option>
                                    </select>
                                </label>
                                <label className="block text-sm font-medium">Contact type
                                    <select value={form.data.entity_type} onChange={(event) => form.setData('entity_type', event.target.value as typeof form.data.entity_type)} className="mt-2 w-full rounded-xl border border-stone-300 bg-white px-3 py-2.5 dark:border-stone-700 dark:bg-stone-950">
                                        <option value="individual">Individual</option><option value="business">Business</option>
                                    </select>
                                </label>
                                <Field label={form.data.entity_type === 'business' ? 'Business name' : 'Full name'} value={form.data.name} error={form.errors.name} onChange={(value) => form.setData('name', value)} required />
                                {form.data.entity_type === 'business' && <Field label="Contact person" value={form.data.contact_person} error={form.errors.contact_person} onChange={(value) => form.setData('contact_person', value)} />}
                                <Field label="Email" type="email" value={form.data.email} error={form.errors.email} onChange={(value) => form.setData('email', value)} />
                                <Field label="Phone" type="tel" value={form.data.phone} error={form.errors.phone} onChange={(value) => form.setData('phone', value)} />
                                <Field label="Address" value={form.data.address} error={form.errors.address} onChange={(value) => form.setData('address', value)} />
                                <label className="block text-sm font-medium">Notes
                                    <textarea rows={3} value={form.data.notes} onChange={(event) => form.setData('notes', event.target.value)} className="mt-2 w-full rounded-xl border border-stone-300 bg-white px-3 py-2.5 dark:border-stone-700 dark:bg-stone-950" />
                                    {form.errors.notes && <span className="mt-1 block text-sm text-red-600">{form.errors.notes}</span>}
                                </label>
                                <button disabled={form.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">{form.processing ? 'Saving…' : 'Save contact'}</button>
                            </form>
                        </section>}
                    </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>
    );
}
