import { Head, Link, router } from '@inertiajs/react';
import { motion, useReducedMotion, type MotionProps } from 'framer-motion';
import {
    BadgeCheck,
    FlagTriangleRight,
    MapPin,
    Search,
    Users,
} from 'lucide-react';
import { SiteActionLink } from '@/components/site-action';
import SiteLayout from '@/components/site-layout';

type Profile = {
    id: number;
    type: string;
    display_name: string;
    slug: string;
    hometown: string | null;
    nationality: string;
    verification_status: string;
    photo_url: string | null;
};
type Pager = {
    data: Profile[];
    links: { url: string | null; label: string; active: boolean }[];
    total: number;
    current_page: number;
    last_page: number;
};

const riderImages = [
    'https://images.unsplash.com/photo-1558981806-ec527fa84c39?auto=format&fit=crop&w=1200&q=85',
    'https://images.unsplash.com/photo-1558981359-219d6364c9c8?auto=format&fit=crop&w=1200&q=85',
    'https://images.unsplash.com/photo-1568772585407-9361f9bf3a87?auto=format&fit=crop&w=1200&q=85',
    'https://images.unsplash.com/photo-1622185135505-2d795003994a?auto=format&fit=crop&w=1200&q=85',
];
const driverImages = [
    'https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=crop&w=1200&q=85',
    'https://images.unsplash.com/photo-1504215680853-026ed2a45def?auto=format&fit=crop&w=1200&q=85',
    'https://images.unsplash.com/photo-1511919884226-fd3cad34687c?auto=format&fit=crop&w=1200&q=85',
    'https://images.unsplash.com/photo-1503736334956-4c8f8e92946d?auto=format&fit=crop&w=1200&q=85',
];

function initials(name: string): string {
    return name
        .split(' ')
        .map((part) => part[0])
        .slice(0, 2)
        .join('');
}

export default function ProfileIndex({
    type,
    profiles,
    filters,
}: {
    type: 'rider' | 'driver';
    profiles: Pager;
    filters: { q?: string };
}) {
    const plural = type === 'rider' ? 'Riders' : 'Drivers';
    const collection = type === 'rider' ? riderImages : driverImages;
    const reduceMotion = useReducedMotion();
    const featuredProfile = profiles.data[0];
    const remainingProfiles = profiles.data.slice(1);
    const reveal: MotionProps = reduceMotion
        ? {}
        : {
              initial: { opacity: 0, y: 24 },
              whileInView: { opacity: 1, y: 0 },
              viewport: { once: true, amount: 0.16 },
              transition: { duration: 0.55, ease: 'easeOut' },
          };

    return (
        <SiteLayout>
            <Head title={`${plural} of Sri Lanka`}>
                <meta
                    name="description"
                    content={`Meet verified Sri Lankan ${plural.toLowerCase()}, explore their racing history and follow their next event.`}
                />
            </Head>

            <section className="relative isolate overflow-hidden bg-[#090c0d] px-5 py-16 text-white sm:py-20 lg:px-8">
                <div className="absolute inset-0 -z-20 bg-[radial-gradient(circle_at_78%_5%,#e8422b55,transparent_25%),linear-gradient(115deg,#090c0d_18%,#172022_100%)]" />
                <div
                    aria-hidden="true"
                    className="race-track-detail race-track-detail--inverse"
                />
                <motion.div
                    initial={reduceMotion ? false : { opacity: 0, y: 24 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.7, ease: [0.16, 1, 0.3, 1] }}
                    className="mx-auto max-w-7xl"
                >
                    <p className="text-[10px] font-black tracking-[.28em] text-[#f6c84f] uppercase">
                        Meet the racers
                    </p>
                    <div className="mt-5 flex flex-wrap items-end justify-between gap-8">
                        <div>
                            <h1 className="text-5xl leading-[.85] font-black tracking-[-.085em] sm:text-7xl">
                                {type === 'rider' ? 'RIDER' : 'DRIVER'}
                                <br />
                                <span className="text-[#e8422b]">ROSTER.</span>
                            </h1>
                            <p className="mt-6 max-w-lg text-base leading-7 text-white/65">
                                The names, numbers and next generation of Sri
                                Lankan motorsport.
                            </p>
                        </div>
                        <div className="border-l border-white/15 pl-5">
                            <span className="block text-4xl font-black tracking-[-.06em]">
                                {profiles.total.toString().padStart(2, '0')}
                            </span>
                            <span className="mt-1 block text-[10px] font-bold tracking-[.18em] text-white/45 uppercase">
                                Public profiles
                            </span>
                        </div>
                    </div>
                </motion.div>
            </section>

            <section className="bg-[#e9e6dc] py-12 sm:py-16">
                <div className="mx-auto max-w-7xl px-5 lg:px-8">
                    <motion.div
                        {...reveal}
                        className="flex flex-wrap items-end justify-between gap-5"
                    >
                        <div>
                            <p className="text-[10px] font-black tracking-[.24em] text-[#e8422b] uppercase">
                                Discover the grid
                            </p>
                            <h2 className="mt-2 text-3xl font-black tracking-[-.065em] text-[#111516] sm:text-4xl">
                                Find the name behind the helmet.
                            </h2>
                        </div>
                        <div className="flex rounded-full border border-[#111516]/15 bg-[#f7f5ef] p-1">
                            <Link
                                href="/people?type=rider"
                                className={`rounded-full px-4 py-2 text-xs font-black transition ${type === 'rider' ? 'bg-[#111516] text-white' : 'text-[#59615b] hover:text-[#e8422b]'}`}
                            >
                                Riders
                            </Link>
                            <Link
                                href="/people?type=driver"
                                className={`rounded-full px-4 py-2 text-xs font-black transition ${type === 'driver' ? 'bg-[#111516] text-white' : 'text-[#59615b] hover:text-[#e8422b]'}`}
                            >
                                Drivers
                            </Link>
                        </div>
                    </motion.div>

                    <motion.form
                        {...reveal}
                        className="mt-8 flex max-w-2xl gap-2 rounded-[1.35rem] bg-[#f7f5ef] p-2 shadow-sm shadow-[#111516]/5"
                        onSubmit={(event) => {
                            event.preventDefault();
                            const searchValue = new FormData(
                                event.currentTarget,
                            ).get('q');
                            const value =
                                typeof searchValue === 'string'
                                    ? searchValue
                                    : '';
                            router.get(
                                '/people',
                                { type, q: value },
                                { preserveState: true },
                            );
                        }}
                    >
                        <Search
                            aria-hidden="true"
                            size={19}
                            className="my-auto ml-3 shrink-0 text-[#e8422b]"
                        />
                        <label htmlFor="racer-search" className="sr-only">
                            Search {plural.toLowerCase()} by name
                        </label>
                        <input
                            id="racer-search"
                            name="q"
                            defaultValue={filters.q || ''}
                            placeholder={`Search ${plural.toLowerCase()} by name`}
                            className="min-w-0 flex-1 bg-transparent px-2 py-3 text-sm font-medium outline-none placeholder:text-[#7f8780]"
                        />
                        <button
                            type="submit"
                            className="rounded-xl bg-[#111516] px-5 py-3 text-xs font-black text-white transition hover:bg-[#e8422b]"
                        >
                            Search
                        </button>
                    </motion.form>

                    {featuredProfile ? (
                        <div className="mt-10">
                            <motion.div {...reveal}>
                                <ProfileCard
                                    profile={featuredProfile}
                                    image={
                                        featuredProfile.photo_url ||
                                        collection[0]
                                    }
                                    featured
                                />
                            </motion.div>
                            {remainingProfiles.length > 0 && (
                                <div className="mt-5 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
                                    {remainingProfiles.map((profile, index) => (
                                        <motion.div
                                            key={profile.id}
                                            {...reveal}
                                            transition={{
                                                duration: 0.5,
                                                delay: reduceMotion
                                                    ? 0
                                                    : (index % 3) * 0.06,
                                            }}
                                        >
                                            <ProfileCard
                                                profile={profile}
                                                image={
                                                    profile.photo_url ||
                                                    collection[
                                                        (index + 1) %
                                                            collection.length
                                                    ]
                                                }
                                            />
                                        </motion.div>
                                    ))}
                                </div>
                            )}
                        </div>
                    ) : (
                        <motion.div
                            {...reveal}
                            className="mt-10 rounded-[1.8rem] border border-dashed border-[#111516]/20 bg-[#f7f5ef] p-12 text-center"
                        >
                            <Users className="mx-auto text-[#e8422b]" />
                            <h2 className="mt-5 text-xl font-black">
                                No {plural.toLowerCase()} found yet.
                            </h2>
                            <p className="mx-auto mt-2 max-w-md text-sm leading-6 text-[#606762]">
                                {filters.q
                                    ? 'Try a different name, or clear the search to see the full roster.'
                                    : 'Create an account and bring the first profile onto the grid.'}
                            </p>
                            {filters.q ? (
                                <SiteActionLink
                                    href={`/${type}s`}
                                    variant="dark"
                                    className="mt-6"
                                >
                                    View all {plural.toLowerCase()}
                                </SiteActionLink>
                            ) : (
                                <SiteActionLink
                                    href="/register"
                                    variant="primary"
                                    className="mt-6"
                                >
                                    Join the grid
                                </SiteActionLink>
                            )}
                        </motion.div>
                    )}

                    {profiles.last_page > 1 && (
                        <nav
                            aria-label={`${plural} pagination`}
                            className="mt-10 flex flex-wrap items-center justify-center gap-2"
                        >
                            {profiles.links.map((link, index) =>
                                link.url ? (
                                    <Link
                                        key={index}
                                        href={link.url}
                                        preserveScroll
                                        dangerouslySetInnerHTML={{
                                            __html: link.label,
                                        }}
                                        className={`grid min-h-10 min-w-10 place-items-center rounded-full border px-3 text-sm font-bold transition ${link.active ? 'border-[#111516] bg-[#111516] text-white' : 'border-[#111516]/15 bg-[#f7f5ef] text-[#46504a] hover:border-[#e8422b] hover:text-[#e8422b]'}`}
                                    />
                                ) : (
                                    <span
                                        key={index}
                                        aria-hidden="true"
                                        dangerouslySetInnerHTML={{
                                            __html: link.label,
                                        }}
                                        className="grid min-h-10 min-w-10 place-items-center rounded-full border border-[#111516]/10 px-3 text-sm font-bold text-[#9ca29e]"
                                    />
                                ),
                            )}
                        </nav>
                    )}

                    <motion.div
                        {...reveal}
                        className="mt-10 flex flex-wrap items-center justify-between gap-5 rounded-[1.7rem] bg-[#101416] p-6 text-white"
                    >
                        <div className="flex items-center gap-4">
                            <span className="grid size-11 place-items-center rounded-sm bg-[#e8422b]">
                                <FlagTriangleRight size={20} />
                            </span>
                            <div>
                                <p className="text-sm font-black">
                                    A new chapter starts on the grid.
                                </p>
                                <p className="mt-1 text-xs text-white/55">
                                    Follow the events where these racers write
                                    their next result.
                                </p>
                            </div>
                        </div>
                        <SiteActionLink
                            href="/events"
                            variant="hover-outline-inverse"
                            className="text-sm"
                        >
                            Find a race
                        </SiteActionLink>
                    </motion.div>
                </div>
            </section>
        </SiteLayout>
    );
}

function ProfileCard({
    profile,
    image,
    featured = false,
}: {
    profile: Profile;
    image: string;
    featured?: boolean;
}) {
    const profilePath = `/${profile.type === 'rider' ? 'riders' : 'drivers'}/${profile.slug}`;

    return (
        <Link
            href={profilePath}
            className={`group relative isolate flex overflow-hidden rounded-[1.8rem] bg-[#111516] text-white shadow-xl shadow-[#111516]/10 ${featured ? 'min-h-[470px] p-6 sm:p-9' : 'min-h-[340px] p-5'}`}
        >
            <img
                src={image}
                alt={
                    profile.photo_url
                        ? `${profile.display_name} racing portrait`
                        : `Motorsport ${profile.type} placeholder`
                }
                className="absolute inset-0 -z-20 size-full object-cover opacity-60 transition duration-700 group-hover:scale-105 group-hover:opacity-75"
            />
            <div className="absolute inset-0 -z-10 bg-[linear-gradient(20deg,rgba(7,9,9,.96)_5%,rgba(7,9,9,.6)_58%,rgba(7,9,9,.12)_100%)]" />
            <div className="flex w-full flex-col justify-between gap-8">
                <div className="flex items-start justify-between gap-4">
                    <span className="grid size-11 place-items-center rounded-sm bg-[#f6c84f] text-sm font-black text-[#111516]">
                        {initials(profile.display_name)}
                    </span>
                    {profile.verification_status === 'verified' && (
                        <span className="inline-flex items-center gap-1.5 rounded-full border border-[#f6c84f]/35 bg-[#111516]/45 px-3 py-1.5 text-[10px] font-black tracking-[.14em] text-[#f6c84f] uppercase backdrop-blur-sm">
                            <BadgeCheck size={13} />
                            Verified
                        </span>
                    )}
                </div>

                <div>
                    <span className="text-[10px] font-black tracking-[.2em] text-[#f6c84f] uppercase">
                        {profile.type} profile
                    </span>
                    <h3
                        className={`mt-4 max-w-2xl font-black tracking-[-.075em] ${featured ? 'text-4xl leading-[.88] sm:text-6xl' : 'text-3xl leading-[.9]'}`}
                    >
                        {profile.display_name}
                    </h3>
                    <div className="mt-5 flex items-center justify-between gap-3 border-t border-white/15 pt-4">
                        <span className="flex min-w-0 items-center gap-2 text-sm text-white/70">
                            <MapPin
                                size={15}
                                className="shrink-0 text-[#e8422b]"
                            />
                            <span className="truncate">
                                {profile.hometown || 'Sri Lanka'}
                            </span>
                        </span>
                    </div>
                </div>
            </div>
        </Link>
    );
}
