import { router, usePage } from '@inertiajs/react';
import { FormEvent, useState } from 'react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';

export type AdminOption = { id: number; label: string };
export type AdminCreateOptions = {
    available: { value: string; label: string }[];
    users: AdminOption[];
    profiles: AdminOption[];
    verified_profiles: AdminOption[];
    events: AdminOption[];
    organizers: AdminOption[];
    entries: AdminOption[];
    categories: AdminOption[];
};

const titles: Record<string, string> = {
    users: 'Create account',
    'edit-user': 'Edit account',
    profiles: 'Add racer profile',
    events: 'Create event',
    entries: 'Add event entry',
    results: 'Record result',
    teams: 'Create team',
    organizers: 'Create organizer',
    orders: 'Create ticket order',
    import: 'Import results',
};

const descriptions: Record<string, string> = {
    users: 'Create an account and send its owner a secure password setup link.',
    'edit-user': 'Update this account’s contact details and platform role.',
    profiles: 'Connect a public racer or driver profile to its owner account.',
    events: 'Set the race schedule, event information, and the first ticket level.',
    entries: 'Add a verified racer or driver to an event.',
    results:
        'Record the official finishing position, time, status, and points.',
    teams: 'Create a team and assign its manager.',
    organizers: 'Create an organizer and connect its owner account.',
    orders: 'Reserve available inventory as a pending order. Payment confirmation issues tickets.',
    import: 'Choose an event and upload its results CSV.',
};

export default function AdminCreateDialog({
    type,
    options,
    onClose,
    record,
}: {
    type: string;
    options: AdminCreateOptions;
    onClose: () => void;
    record?: { id: number; name: string; email: string; role: string };
}) {
    const [processing, setProcessing] = useState(false);
    const page = usePage();
    const errors =
        (page.props as typeof page.props & { errors?: Record<string, string> })
            .errors ?? {};
    function submit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        setProcessing(true);
        if (type === 'import') {
            const eventId = formData.get('event_id');
            if (typeof eventId !== 'string') {
                setProcessing(false);
                return;
            }
            router.post(
                `/organizer/events/${eventId}/results/import`,
                formData,
                {
                    forceFormData: true,
                    onFinish: () => setProcessing(false),
                    onSuccess: onClose,
                },
            );
            return;
        }
        if (type === 'edit-user' && record) {
            router.patch(`/admin/users/${record.id}`, formData, {
                onFinish: () => setProcessing(false),
                onSuccess: onClose,
            });
        } else {
            router.post(`/admin/${type}`, formData, {
                onFinish: () => setProcessing(false),
                onSuccess: onClose,
            });
        }
    }

    const fields =
        type === 'users' || type === 'edit-user' ? (
            <>
                <Field
                    label="Full name"
                    name="name"
                    defaultValue={record?.name}
                    required
                />
                <Field
                    label="Email address"
                    name="email"
                    type="email"
                    defaultValue={record?.email}
                    required
                />
                <Choice
                    label="Account role"
                    name="role"
                    required
                    items={[
                        'fan',
                        'rider',
                        'driver',
                        'organizer',
                        'moderator',
                        'admin',
                    ].map((role) => ({
                        value: role,
                        label:
                            role === 'admin'
                                ? 'Super Admin'
                                : role === 'moderator'
                                  ? 'Racing.lk staff'
                                  : role[0].toUpperCase() + role.slice(1),
                    }))}
                    defaultValue={record?.role}
                />
                {type === 'users' && (
                    <p className="text-xs text-slate-500">
                        Non-staff accounts receive a one-time email sign-in
                        code. Staff accounts receive a secure password setup
                        link.
                    </p>
                )}
            </>
        ) : type === 'profiles' ? (
            <>
                <Choice
                    label="Account"
                    name="user_id"
                    required
                    items={options.users}
                />
                <Choice
                    label="Profile type"
                    name="type"
                    required
                    items={[
                        { value: 'rider', label: 'Rider' },
                        { value: 'driver', label: 'Driver' },
                    ]}
                />
                <Field
                    label="Public display name"
                    name="display_name"
                    required
                />
                <Field label="Hometown" name="hometown" />
            </>
        ) : type === 'events' ? (
            <>
                <Choice
                    label="Organizer"
                    name="organizer_id"
                    required
                    items={options.organizers}
                />
                <Field label="Event name" name="title" required />
                <Field label="Discipline" name="discipline" required />
                <Field label="Venue" name="venue_name" required />
                <Field label="Location" name="location" />
                <Field
                    label="End date and time"
                    name="ends_at"
                    type="datetime-local"
                />
                <label className="grid gap-1.5 text-sm font-semibold text-slate-700 sm:col-span-2 xl:col-span-3">
                    Event description
                    <textarea
                        name="description"
                        rows={5}
                        maxLength={5000}
                        placeholder="Write the race brief. Leave a blank line between paragraphs."
                        className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-normal outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-100"
                    />
                    <span className="font-normal text-slate-500">
                        Blank lines become paragraph breaks on the event page.
                    </span>
                </label>
                <div className="sm:col-span-2 xl:col-span-3">
                    <Field
                        label="Event image (JPEG, PNG or WebP, up to 5 MB)"
                        name="banner"
                        type="file"
                        accept="image/jpeg,image/png,image/webp"
                    />
                </div>
                <Field
                    label="Start date and time"
                    name="starts_at"
                    type="datetime-local"
                    required
                />
                <div className="flex items-end rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 text-xs leading-5 text-slate-600">
                    This event gets one ticket group. Add more levels later from
                    the Tickets &amp; pricing page.
                </div>
                <Field
                    label="Ticket group name"
                    name="ticket_group_name"
                    defaultValue="Race day tickets"
                    required
                />
                <Field
                    label="First ticket level"
                    name="ticket_name"
                    defaultValue="General admission"
                    required
                />
                <Field
                    label="Ticket price (LKR)"
                    name="ticket_price"
                    type="number"
                    min="0"
                    step="0.01"
                    required
                />
                <Field
                    label="Max tickets per order"
                    name="ticket_per_order_max"
                    type="number"
                    min="1"
                    max="20"
                    defaultValue="6"
                    required
                />
                <label className="grid gap-1.5 text-sm font-semibold text-slate-700 sm:col-span-2 xl:col-span-2">
                    Ticket level details
                    <textarea
                        name="ticket_description"
                        rows={2}
                        maxLength={500}
                        placeholder="What does this pass include?"
                        className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-normal outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-100"
                    />
                </label>
                <Field
                    label="Ticket inventory"
                    name="ticket_quantity"
                    type="number"
                    min="1"
                    required
                />
                <fieldset className="rounded-xl border border-slate-200 bg-slate-50 p-4 sm:col-span-2 xl:col-span-3">
                    <legend className="px-1 text-sm font-black text-slate-800">
                        Payment methods for this event
                    </legend>
                    <div className="mt-2 flex flex-wrap gap-x-6 gap-y-3 text-sm font-semibold">
                        {(
                            [
                                ['cash', 'Cash at event'],
                                ['payhere', 'PayHere online'],
                                ['bank_transfer', 'Bank transfer'],
                            ] as const
                        ).map(([value, label]) => (
                            <label
                                key={value}
                                className="flex items-center gap-2"
                            >
                                <input
                                    type="checkbox"
                                    name="accepted_payment_methods[]"
                                    value={value}
                                    defaultChecked={value === 'cash'}
                                />
                                {label}
                            </label>
                        ))}
                    </div>
                    <p className="mt-2 text-xs text-slate-500">
                        PayHere and bank transfer need credentials in the
                        organizer’s payment settings before they can be
                        selected.
                    </p>
                </fieldset>
                <label className="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-3 text-sm font-semibold">
                    <input
                        type="hidden"
                        name="refund_requests_enabled"
                        value="0"
                    />
                    <input
                        type="checkbox"
                        name="refund_requests_enabled"
                        value="1"
                        defaultChecked
                    />
                    Allow customer refund requests
                </label>
                <Field
                    label="Refund cutoff hours before the event"
                    name="refund_cutoff_hours"
                    type="number"
                    min="0"
                    max="168"
                    defaultValue="2"
                />
            </>
        ) : type === 'entries' ? (
            <>
                <Choice
                    label="Event"
                    name="event_id"
                    required
                    items={options.events}
                />
                <Choice
                    label="Verified racer profile"
                    name="profile_id"
                    required
                    items={options.verified_profiles}
                />
                <Field label="Race number" name="race_number" />
            </>
        ) : type === 'results' ? (
            <>
                <Choice
                    label="Entry"
                    name="event_entry_id"
                    required
                    items={options.entries}
                />
                <Field
                    label="Finishing position"
                    name="position"
                    type="number"
                    min="1"
                />
                <Field
                    label="Result status"
                    name="result_status"
                    defaultValue="finished"
                    required
                />
                <Field
                    label="Race time"
                    name="time"
                    placeholder="e.g. 01:24:32.120"
                />
                <Field
                    label="Points"
                    name="points"
                    type="number"
                    min="0"
                    defaultValue="0"
                    required
                />
            </>
        ) : type === 'teams' ? (
            <>
                <Field label="Team name" name="name" required />
                <Field label="Hometown" name="hometown" />
                <Choice
                    label="Team manager"
                    name="manager_user_id"
                    items={options.users}
                />
            </>
        ) : type === 'organizers' ? (
            <>
                <Field label="Organizer name" name="name" required />
                <Choice
                    label="Owner account"
                    name="owner_id"
                    required
                    items={options.users}
                />
                <Field label="Description" name="description" />
            </>
        ) : type === 'orders' ? (
            <>
                <Choice
                    label="Customer account"
                    name="user_id"
                    required
                    items={options.users}
                />
                <Choice
                    label="Ticket category"
                    name="category_id"
                    required
                    items={options.categories}
                />
                <Field
                    label="Quantity"
                    name="quantity"
                    type="number"
                    min="1"
                    max="10"
                    defaultValue="1"
                    required
                />
                <p className="text-xs text-slate-500">
                    Creates a pending reservation and holds available inventory.
                    Tickets are issued only when payment is confirmed.
                </p>
            </>
        ) : type === 'import' ? (
            <>
                <Choice
                    label="Event"
                    name="event_id"
                    required
                    items={options.events}
                />
                <Field
                    label="CSV results file"
                    name="file"
                    type="file"
                    accept=".csv,text/csv"
                    required
                />
                <p className="text-xs text-slate-500">
                    CSV header must include profile_slug and position. Optional
                    columns: result_status, time and points.
                </p>
            </>
        ) : null;

    return (
        <Dialog open onOpenChange={(open) => !open && onClose()}>
            <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl xl:max-w-4xl">
                <DialogHeader>
                    <DialogTitle>{titles[type] ?? 'Add record'}</DialogTitle>
                    <DialogDescription>
                        {descriptions[type] ??
                            'Enter the relevant details below. Required fields are marked by the form.'}
                    </DialogDescription>
                </DialogHeader>
                <form onSubmit={submit} className="space-y-4">
                    {Object.keys(errors).length > 0 && (
                        <div
                            role="alert"
                            className="rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-800"
                        >
                            {Object.values(errors).join(' ')}
                        </div>
                    )}
                    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
                        {fields}
                    </div>
                    <DialogFooter>
                        <button
                            type="button"
                            onClick={onClose}
                            className="h-10 rounded-lg border border-slate-200 px-4 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                        >
                            Cancel
                        </button>
                        <button
                            disabled={processing}
                            className="h-10 rounded-lg bg-slate-900 px-4 text-sm font-semibold text-white hover:bg-slate-700 disabled:opacity-60"
                        >
                            {processing
                                ? 'Saving…'
                                : type === 'users'
                                  ? 'Create and email setup link'
                                  : type === 'edit-user'
                                    ? 'Save account'
                                    : type === 'orders'
                                      ? 'Reserve tickets'
                                      : type === 'import'
                                        ? 'Import results'
                                        : 'Create record'}
                        </button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}

function Field({
    label,
    name,
    type = 'text',
    required = false,
    ...props
}: {
    label: string;
    name: string;
    type?: string;
    required?: boolean;
    defaultValue?: string;
    min?: string;
    max?: string;
    step?: string;
    accept?: string;
    placeholder?: string;
}) {
    return (
        <label className="grid gap-1.5 text-sm font-semibold text-slate-700">
            {label}
            <input
                name={name}
                type={type}
                required={required}
                className="h-11 w-full rounded-lg border border-slate-200 bg-white px-3 text-sm font-normal outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-100"
                {...props}
            />
        </label>
    );
}

function Choice({
    label,
    name,
    items,
    required = false,
    defaultValue = '',
}: {
    label: string;
    name: string;
    items: (AdminOption | { value: string; label: string })[];
    required?: boolean;
    defaultValue?: string;
}) {
    return (
        <label className="grid gap-1.5 text-sm font-semibold text-slate-700">
            {label}
            <select
                name={name}
                required={required}
                defaultValue={defaultValue}
                className="h-11 w-full rounded-lg border border-slate-200 bg-white px-3 text-sm font-normal outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-100"
            >
                <option value="" disabled>
                    Select…
                </option>
                {items.map((item) => (
                    <option
                        key={'value' in item ? item.value : item.id}
                        value={'value' in item ? item.value : item.id}
                    >
                        {item.label}
                    </option>
                ))}
            </select>
        </label>
    );
}
