import { Head, Link, useForm } from '@inertiajs/react';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
import { Textarea } from '@/components/ui/textarea';
import { index, show, store, update } from '@/routes/contacts';

type Option = { value: number | string; label: string };

type Contact = {
    id: string;
    kind: string;
    name: string;
    email: string | null;
    phone: string | null;
    address: string | null;
    city: string | null;
    state: string | null;
    contact_category_id: number | null;
    nin_encrypted: string | null;
    rc_number: string | null;
    notes: string | null;
};

const NONE = 'none';

export default function ContactForm({
    contact,
    categories,
    kinds,
}: {
    contact: Contact | null;
    categories: Option[];
    kinds: Option[];
}) {
    const editing = contact !== null;

    const form = useForm({
        kind: contact?.kind ?? 'individual',
        name: contact?.name ?? '',
        email: contact?.email ?? '',
        phone: contact?.phone ?? '',
        address: contact?.address ?? '',
        city: contact?.city ?? '',
        state: contact?.state ?? '',
        contact_category_id: contact?.contact_category_id ?? null,
        nin_encrypted: contact?.nin_encrypted ?? '',
        rc_number: contact?.rc_number ?? '',
        notes: contact?.notes ?? '',
    });

    const isOrg = form.data.kind === 'organization';

    const submit = (e: React.FormEvent) => {
        e.preventDefault();

        if (editing) {
            form.put(update(contact.id).url, { preserveScroll: true });
        } else {
            form.post(store().url, { preserveScroll: true });
        }
    };

    return (
        <>
            <Head title={editing ? 'Edit contact' : 'New contact'} />
            <form onSubmit={submit} className="flex flex-col gap-6 p-4">
                <PageHeader
                    title={editing ? 'Edit contact' : 'New contact'}
                    action={
                        <div className="flex gap-2">
                            <Button asChild variant="outline" type="button">
                                <Link
                                    href={editing ? show(contact.id) : index()}
                                >
                                    Cancel
                                </Link>
                            </Button>
                            <Button type="submit" disabled={form.processing}>
                                {form.processing && <Spinner />}
                                Save
                            </Button>
                        </div>
                    }
                />

                <Card>
                    <CardHeader>
                        <CardTitle>Details</CardTitle>
                    </CardHeader>
                    <CardContent className="grid gap-4 sm:grid-cols-2">
                        <div className="grid gap-2">
                            <Label htmlFor="kind">Kind</Label>
                            <Select
                                value={form.data.kind}
                                onValueChange={(v) => form.setData('kind', v)}
                            >
                                <SelectTrigger id="kind">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    {kinds.map((k) => (
                                        <SelectItem
                                            key={k.value}
                                            value={String(k.value)}
                                        >
                                            {k.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={form.errors.kind} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="name">
                                {isOrg ? 'Organization name' : 'Full name'}
                            </Label>
                            <Input
                                id="name"
                                value={form.data.name}
                                onChange={(e) =>
                                    form.setData('name', e.target.value)
                                }
                                required
                            />
                            <InputError message={form.errors.name} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="email">Email (optional)</Label>
                            <Input
                                id="email"
                                type="email"
                                value={form.data.email}
                                onChange={(e) =>
                                    form.setData('email', e.target.value)
                                }
                            />
                            <InputError message={form.errors.email} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="phone">Phone (optional)</Label>
                            <Input
                                id="phone"
                                value={form.data.phone}
                                onChange={(e) =>
                                    form.setData('phone', e.target.value)
                                }
                            />
                            <InputError message={form.errors.phone} />
                        </div>
                        <div className="grid gap-2 sm:col-span-2">
                            <Label htmlFor="address">Address (optional)</Label>
                            <Input
                                id="address"
                                value={form.data.address}
                                onChange={(e) =>
                                    form.setData('address', e.target.value)
                                }
                            />
                            <InputError message={form.errors.address} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="city">City (optional)</Label>
                            <Input
                                id="city"
                                value={form.data.city}
                                onChange={(e) =>
                                    form.setData('city', e.target.value)
                                }
                            />
                            <InputError message={form.errors.city} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="state">State (optional)</Label>
                            <Input
                                id="state"
                                value={form.data.state}
                                onChange={(e) =>
                                    form.setData('state', e.target.value)
                                }
                            />
                            <InputError message={form.errors.state} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="category">
                                Category (optional)
                            </Label>
                            <Select
                                value={
                                    form.data.contact_category_id
                                        ? String(form.data.contact_category_id)
                                        : NONE
                                }
                                onValueChange={(v) =>
                                    form.setData(
                                        'contact_category_id',
                                        v === NONE ? null : Number(v),
                                    )
                                }
                            >
                                <SelectTrigger id="category">
                                    <SelectValue placeholder="Uncategorized" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value={NONE}>
                                        Uncategorized
                                    </SelectItem>
                                    {categories.map((c) => (
                                        <SelectItem
                                            key={c.value}
                                            value={String(c.value)}
                                        >
                                            {c.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError
                                message={form.errors.contact_category_id}
                            />
                        </div>
                        {isOrg ? (
                            <div className="grid gap-2">
                                <Label htmlFor="rc_number">
                                    RC number (optional)
                                </Label>
                                <Input
                                    id="rc_number"
                                    value={form.data.rc_number}
                                    onChange={(e) =>
                                        form.setData(
                                            'rc_number',
                                            e.target.value,
                                        )
                                    }
                                />
                                <InputError message={form.errors.rc_number} />
                            </div>
                        ) : (
                            <div className="grid gap-2">
                                <Label htmlFor="nin">
                                    NIN (optional, 11 digits)
                                </Label>
                                <Input
                                    id="nin"
                                    inputMode="numeric"
                                    value={form.data.nin_encrypted}
                                    onChange={(e) =>
                                        form.setData(
                                            'nin_encrypted',
                                            e.target.value,
                                        )
                                    }
                                />
                                <InputError
                                    message={form.errors.nin_encrypted}
                                />
                            </div>
                        )}
                        <div className="grid gap-2 sm:col-span-2">
                            <Label htmlFor="notes">Notes (optional)</Label>
                            <Textarea
                                id="notes"
                                value={form.data.notes}
                                onChange={(e) =>
                                    form.setData('notes', e.target.value)
                                }
                            />
                            <InputError message={form.errors.notes} />
                        </div>
                    </CardContent>
                </Card>
            </form>
        </>
    );
}
