import { Head, Link, useForm } from '@inertiajs/react';
import { BadgeCheck, CircleUserRound, FileCheck2, Ticket } from 'lucide-react';

type Profile = {
    id: number;
    display_name: string;
    slug: string;
    type: string;
    verification_status: string;
};
type Order = {
    code: string;
    status: string;
    event: string;
    event_slug: string;
};
type Discipline = { id: number; name: string };
type ProfileApplication = {
    id: number;
    type: 'rider' | 'driver';
    display_name: string;
    legal_name: string | null;
    date_of_birth: string | null;
    mobile: string | null;
    hometown: string | null;
    nationality: string;
    bio: string | null;
    racing_background: string;
    race_classes: string | null;
    achievements: string | null;
    event_history: string | null;
    discipline_ids: number[];
    supporting_links: string[];
    decision_history: {
        action: string;
        note?: string | null;
        reviewed_at?: string;
    }[];
    status: string;
    review_note: string | null;
};

function statusLabel(status: string): string {
    return status.replaceAll('_', ' ');
}

export default function RacerWorkspace({
    profiles,
    applications,
    disciplines,
    orders,
    canOrganize,
}: {
    profiles: Profile[];
    applications: ProfileApplication[];
    disciplines: Discipline[];
    orders: Order[];
    canOrganize: boolean;
}) {
    const activeApplication = applications.find((application) =>
        ['pending', 'rejected'].includes(application.status),
    );
    const availableTypes = (['rider', 'driver'] as const).filter(
        (type) => !profiles.some((profile) => profile.type === type),
    );
    const application = activeApplication ?? null;

    return (
        <>
            <Head title="Racer workspace" />
            <main className="min-h-full bg-slate-50 px-4 py-4 text-slate-900 sm:px-6 lg:px-7">
                <div className="mx-auto max-w-[1500px]">
                    <p className="text-xs font-semibold text-slate-500">
                        Racing.lk / Racer workspace
                    </p>
                    <h1 className="mt-1 text-2xl font-bold tracking-tight">
                        Racer dashboard
                    </h1>
                    <p className="mt-1 max-w-2xl text-sm text-slate-600">
                        Apply to join the racing.lk racer directory, manage your
                        profile, and keep track of race-day activity.
                    </p>

                    <div className="mt-5 grid items-start gap-4 xl:grid-cols-[1.1fr_.9fr]">
                        <section className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm sm:p-5">
                            <div className="flex flex-wrap items-start justify-between gap-4">
                                <div>
                                    <p className="text-[10px] font-black tracking-[.2em] text-[#c83229] uppercase">
                                        Racer identity
                                    </p>
                                    <h2 className="mt-2 text-2xl font-black">
                                        Your profiles
                                    </h2>
                                </div>
                                <Link
                                    href="/people?type=rider"
                                    className="rounded-lg border border-[#171b1c]/15 px-3 py-2 text-sm font-bold hover:border-[#c83229] hover:text-[#a52620]"
                                >
                                    Browse racers
                                </Link>
                            </div>

                            <div className="mt-5 space-y-3">
                                {profiles.map((profile) => (
                                    <article
                                        key={profile.id}
                                        className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200 bg-slate-50 p-4"
                                    >
                                        <span>
                                            <CircleUserRound className="mr-2 inline size-4 text-[#c83229]" />
                                            <strong>
                                                {profile.display_name}
                                            </strong>
                                            <span className="ml-2 text-xs text-slate-500">
                                                {profile.type} ·{' '}
                                                {statusLabel(
                                                    profile.verification_status,
                                                )}
                                            </span>
                                        </span>
                                        <Link
                                            href={`/${profile.type}s/${profile.slug}`}
                                            className="text-sm font-bold underline underline-offset-4"
                                        >
                                            View profile
                                        </Link>
                                    </article>
                                ))}
                                {profiles.length === 0 && (
                                    <p className="rounded-xl border border-dashed border-slate-300 p-4 text-sm leading-6 text-slate-600">
                                        A public racer profile is created only
                                        after Racing.lk reviews your
                                        application.
                                    </p>
                                )}
                            </div>

                            {applications.length > 0 && (
                                <div className="mt-6 border-t border-slate-200 pt-5">
                                    <h3 className="text-sm font-black">
                                        Application history
                                    </h3>
                                    <div className="mt-3 space-y-2">
                                        {applications.map((item) => (
                                            <div
                                                key={item.id}
                                                className="flex items-center justify-between gap-3 rounded-lg bg-slate-50 px-3 py-2.5"
                                            >
                                                <span className="text-sm font-semibold">
                                                    {item.display_name} ·{' '}
                                                    {item.type}
                                                </span>
                                                <span
                                                    className={`rounded-full px-3 py-1 text-xs font-bold capitalize ${item.status === 'approved' ? 'bg-green-100 text-green-800' : item.status === 'rejected' ? 'bg-red-100 text-red-800' : 'bg-amber-100 text-amber-900'}`}
                                                >
                                                    {statusLabel(item.status)}
                                                </span>
                                            </div>
                                        ))}
                                    </div>
                                    {application?.status === 'rejected' &&
                                        application.review_note && (
                                            <p className="mt-3 rounded-xl border border-red-200 bg-red-50 p-4 text-sm leading-6 text-red-900">
                                                <strong>
                                                    Reviewer feedback:{' '}
                                                </strong>
                                                {application.review_note}
                                            </p>
                                        )}
                                    {application?.decision_history.map(
                                        (decision, index) =>
                                            decision.action === 'rejected' &&
                                            decision.note && (
                                                <p
                                                    key={`${decision.action}-${index}`}
                                                    className="mt-3 rounded-xl border border-red-200 bg-red-50 p-4 text-sm leading-6 text-red-900"
                                                >
                                                    <strong>
                                                        Previous reviewer
                                                        feedback:{' '}
                                                    </strong>
                                                    {decision.note}
                                                </p>
                                            ),
                                    )}
                                </div>
                            )}

                            {application || availableTypes.length > 0 ? (
                                <ApplicationForm
                                    key={application?.id ?? availableTypes[0]}
                                    application={application}
                                    availableTypes={availableTypes}
                                    disciplines={disciplines}
                                />
                            ) : (
                                <p className="mt-4 rounded-lg bg-slate-50 p-3 text-sm leading-6 text-slate-600">
                                    Your rider and driver profile applications
                                    have been reviewed.
                                </p>
                            )}
                        </section>

                        <section className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm sm:p-5">
                            <p className="text-xs font-semibold text-slate-500">
                                Race day
                            </p>
                            <h2 className="mt-1 text-lg font-bold">
                                Tickets and events
                            </h2>
                            <div className="mt-5 space-y-3">
                                {orders.map((order) => (
                                    <article
                                        key={order.code}
                                        className="rounded-lg border border-slate-200 bg-slate-50 p-3"
                                    >
                                        <Ticket className="mr-2 inline size-4 text-red-700" />
                                        <Link
                                            href={`/events/${order.event_slug}`}
                                            className="font-bold underline underline-offset-4"
                                        >
                                            {order.event}
                                        </Link>
                                        <span className="ml-2 text-xs text-slate-500 capitalize">
                                            {statusLabel(order.status)}
                                        </span>
                                        <p className="mt-1 text-xs text-slate-500">
                                            Order {order.code}
                                        </p>
                                    </article>
                                ))}
                            </div>
                            {orders.length === 0 && (
                                <p className="mt-4 text-sm leading-6 text-slate-600">
                                    Your ticket orders will appear here.
                                </p>
                            )}
                            <div className="mt-6 flex flex-wrap gap-3">
                                <Link
                                    href="/events"
                                    className="rounded-lg bg-slate-900 px-4 py-2.5 text-sm font-bold text-white hover:bg-red-700"
                                >
                                    Explore events
                                </Link>
                                {canOrganize && (
                                    <Link
                                        href="/organizer"
                                        className="rounded-lg border border-slate-300 px-4 py-2.5 text-sm font-bold text-slate-700 hover:border-red-300 hover:text-red-700"
                                    >
                                        Open Organizer workspace
                                    </Link>
                                )}
                            </div>
                            {!canOrganize && (
                                <Link
                                    href="/organizer"
                                    className="mt-4 inline-block text-sm font-bold text-[#f6c84f] underline underline-offset-4"
                                >
                                    Set up an Organizer workspace
                                </Link>
                            )}
                        </section>
                    </div>
                </div>
            </main>
        </>
    );
}

function ApplicationForm({
    application,
    availableTypes,
    disciplines,
}: {
    application: ProfileApplication | null;
    availableTypes: ('rider' | 'driver')[];
    disciplines: Discipline[];
}) {
    const form = useForm({
        type: application?.type ?? availableTypes[0] ?? 'rider',
        display_name: application?.display_name ?? '',
        legal_name: application?.legal_name ?? '',
        date_of_birth: application?.date_of_birth ?? '',
        mobile: application?.mobile ?? '',
        hometown: application?.hometown ?? '',
        nationality: application?.nationality ?? 'Sri Lankan',
        bio: application?.bio ?? '',
        racing_background: application?.racing_background ?? '',
        race_classes: application?.race_classes ?? '',
        achievements: application?.achievements ?? '',
        event_history: application?.event_history ?? '',
        discipline_ids: application?.discipline_ids ?? [],
        supporting_links: [
            application?.supporting_links[0] ?? '',
            application?.supporting_links[1] ?? '',
            application?.supporting_links[2] ?? '',
        ],
    });

    const inputClass =
        'w-full rounded-lg border border-slate-300 bg-white px-3.5 py-3 text-sm text-[#171b1c] outline-none transition focus:border-[#c83229] focus:ring-2 focus:ring-[#c83229]/15';
    const labelClass = 'grid gap-1.5 text-xs font-bold text-slate-700';
    const errors = form.errors as Record<string, string | undefined>;

    function submit(event: React.FormEvent<HTMLFormElement>): void {
        event.preventDefault();
        if (application) {
            form.put(`/profile-applications/${application.id}`, {
                preserveScroll: true,
            });
        } else {
            form.post('/profile-applications', { preserveScroll: true });
        }
    }

    return (
        <form
            onSubmit={submit}
            className="mt-5 rounded-xl border border-slate-200 bg-white p-4 sm:p-5"
        >
            <div className="flex items-start gap-3">
                <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-slate-100 text-red-700">
                    <FileCheck2 size={19} />
                </span>
                <div>
                    <p className="text-[10px] font-black tracking-[.18em] text-[#c83229] uppercase">
                        Racing.lk review
                    </p>
                    <h3 className="mt-1 text-lg font-black">
                        {application?.status === 'rejected'
                            ? 'Update and reapply'
                            : application
                              ? 'Your profile application'
                              : 'Apply for a racer profile'}
                    </h3>
                    <p className="mt-1 text-sm leading-6 text-slate-600">
                        Share your racing background and achievements. Personal
                        details are encrypted and handled privately.
                    </p>
                </div>
            </div>

            <div className="mt-5 grid gap-3 sm:grid-cols-2">
                <label className={labelClass}>
                    Profile type
                    <select
                        className={inputClass}
                        value={form.data.type}
                        disabled={Boolean(application)}
                        onChange={(event) =>
                            form.setData(
                                'type',
                                event.target.value as 'rider' | 'driver',
                            )
                        }
                    >
                        {(['rider', 'driver'] as const)
                            .filter(
                                (type) =>
                                    application?.type === type ||
                                    availableTypes.includes(type),
                            )
                            .map((type) => (
                                <option key={type} value={type}>
                                    {type === 'rider'
                                        ? 'Motorcycle rider'
                                        : 'Car driver'}
                                </option>
                            ))}
                    </select>
                </label>
                <label className={labelClass}>
                    Public racing name
                    <input
                        className={inputClass}
                        maxLength={100}
                        required
                        value={form.data.display_name}
                        onChange={(event) =>
                            form.setData('display_name', event.target.value)
                        }
                    />
                </label>
                <label className={labelClass}>
                    Legal name{' '}
                    <span className="font-normal text-slate-500">Private</span>
                    <input
                        className={inputClass}
                        required
                        value={form.data.legal_name}
                        onChange={(event) =>
                            form.setData('legal_name', event.target.value)
                        }
                    />
                </label>
                <label className={labelClass}>
                    Mobile{' '}
                    <span className="font-normal text-slate-500">
                        Only visible to email-verified members
                    </span>
                    <input
                        className={inputClass}
                        type="tel"
                        required
                        value={form.data.mobile}
                        onChange={(event) =>
                            form.setData('mobile', event.target.value)
                        }
                    />
                </label>
                <label className={labelClass}>
                    Date of birth{' '}
                    <span className="font-normal text-slate-500">Private</span>
                    <input
                        className={inputClass}
                        type="date"
                        max={new Date().toISOString().slice(0, 10)}
                        value={form.data.date_of_birth}
                        onChange={(event) =>
                            form.setData('date_of_birth', event.target.value)
                        }
                    />
                </label>
                <label className={labelClass}>
                    Hometown
                    <input
                        className={inputClass}
                        value={form.data.hometown}
                        onChange={(event) =>
                            form.setData('hometown', event.target.value)
                        }
                    />
                </label>
                <label className={labelClass}>
                    Nationality
                    <input
                        className={inputClass}
                        required
                        value={form.data.nationality}
                        onChange={(event) =>
                            form.setData('nationality', event.target.value)
                        }
                    />
                </label>
                <label className={`${labelClass} sm:col-span-2`}>
                    Racing disciplines
                    <div className="grid gap-2 rounded-lg border border-slate-300 bg-white p-3 sm:grid-cols-2">
                        {disciplines.map((discipline) => {
                            const checked = form.data.discipline_ids.includes(
                                discipline.id,
                            );
                            return (
                                <label
                                    key={discipline.id}
                                    className="flex items-center gap-2 text-sm font-medium"
                                >
                                    <input
                                        type="checkbox"
                                        checked={checked}
                                        onChange={(event) =>
                                            form.setData(
                                                'discipline_ids',
                                                event.target.checked
                                                    ? [
                                                          ...form.data
                                                              .discipline_ids,
                                                          discipline.id,
                                                      ]
                                                    : form.data.discipline_ids.filter(
                                                          (id) =>
                                                              id !==
                                                              discipline.id,
                                                      ),
                                            )
                                        }
                                        className="size-4 accent-[#c83229]"
                                    />
                                    {discipline.name}
                                </label>
                            );
                        })}
                    </div>
                </label>
                <label className={labelClass}>
                    Race classes
                    <input
                        className={inputClass}
                        placeholder="e.g. MX1, Super Sport"
                        value={form.data.race_classes}
                        onChange={(event) =>
                            form.setData('race_classes', event.target.value)
                        }
                    />
                </label>
                <label className={labelClass}>
                    Public introduction
                    <input
                        className={inputClass}
                        maxLength={1200}
                        value={form.data.bio}
                        onChange={(event) =>
                            form.setData('bio', event.target.value)
                        }
                    />
                </label>
                <label className={`${labelClass} sm:col-span-2`}>
                    Racing background
                    <textarea
                        className={inputClass}
                        required
                        rows={4}
                        maxLength={5000}
                        placeholder="Tell us about your racing experience, training and development."
                        value={form.data.racing_background}
                        onChange={(event) =>
                            form.setData(
                                'racing_background',
                                event.target.value,
                            )
                        }
                    />
                </label>
                <label className={labelClass}>
                    Achievements
                    <textarea
                        className={inputClass}
                        rows={3}
                        maxLength={3000}
                        value={form.data.achievements}
                        onChange={(event) =>
                            form.setData('achievements', event.target.value)
                        }
                    />
                </label>
                <label className={labelClass}>
                    Event history
                    <textarea
                        className={inputClass}
                        rows={3}
                        maxLength={3000}
                        value={form.data.event_history}
                        onChange={(event) =>
                            form.setData('event_history', event.target.value)
                        }
                    />
                </label>
                <div className={`${labelClass} sm:col-span-2`}>
                    Supporting links{' '}
                    <span className="font-normal text-slate-500">
                        Optional results, team or media links
                    </span>
                    {[0, 1, 2].map((index) => (
                        <input
                            key={index}
                            className={inputClass}
                            type="url"
                            placeholder="https://"
                            value={form.data.supporting_links[index] ?? ''}
                            onChange={(event) =>
                                form.setData(
                                    'supporting_links',
                                    form.data.supporting_links.map(
                                        (link, linkIndex) =>
                                            linkIndex === index
                                                ? event.target.value
                                                : link,
                                    ),
                                )
                            }
                        />
                    ))}
                </div>
            </div>
            {Object.entries(errors).map(
                ([field, message]) =>
                    message && (
                        <p
                            key={field}
                            className="mt-2 text-xs font-semibold text-red-700"
                        >
                            {message}
                        </p>
                    ),
            )}
            <p className="mt-4 flex items-start gap-2 text-xs leading-5 text-slate-600">
                <BadgeCheck className="mt-0.5 size-4 shrink-0 text-[#c83229]" />
                Approval creates your public profile. The verified badge
                requires a separate licence and identity-document review.
            </p>
            <button
                disabled={form.processing}
                className="mt-5 rounded-lg bg-[#171b1c] px-5 py-3 text-sm font-black text-white transition hover:bg-[#c83229] disabled:opacity-50"
            >
                {form.processing
                    ? 'Sending application…'
                    : application?.status === 'rejected'
                      ? 'Update and reapply'
                      : application
                        ? 'Save application changes'
                        : 'Submit for review'}
            </button>
        </form>
    );
}
