"use client";

import Image from "next/image";
import type { ReactNode } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { HeroModelStrip } from "@/components/home/HeroModelStrip";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  EvBatteryIcon,
  EvChargingIcon,
  EvChevronLeftIcon,
  EvChevronRightIcon,
  EvSpeedIcon,
} from "@/components/ui/ev-icons";
import { brands as mockBrands, scooters as mockScooters, type Brand, type Scooter } from "@/lib/mock-data";
import { resolveAssetUrl } from "@/lib/media";
import { cn } from "@/lib/utils";

type HomeHeroProps = {
  brands?: Brand[];
  scooters?: Scooter[];
};

export function HomeHero({ brands = mockBrands, scooters = mockScooters }: HomeHeroProps) {
  if (!scooters.length) {
    return null;
  }

  const [activeIndex, setActiveIndex] = useState(0);
  const featuredScooters = useMemo(() => scooters, [scooters]);
  const activeScooter = featuredScooters[activeIndex] ?? scooters[0];
  const activeBrand = brands.find((brand) => brand.id === activeScooter?.brandId);
  const heroBackgroundImage = "/images/backgrounds/hero-bg-mockup.png";
  const activeShowcaseImage =
    resolveAssetUrl(activeScooter?.heroImage) ||
    resolveAssetUrl(activeScooter?.posterImage) ||
    resolveAssetUrl(activeScooter?.thumbnailImage) ||
    "/images/scooters/hero-scooter-v2.png";
  const [heroImageSrc, setHeroImageSrc] = useState(activeShowcaseImage);

  const stats = useMemo(
    () => [
      {
        label: "Range",
        value: `${activeScooter.rangeKm} km`,
        icon: EvBatteryIcon,
      },
      {
        label: "Top Speed",
        value: `${activeScooter.topSpeedKmph} km/h`,
        rawValue: activeScooter.topSpeedKmph,
        icon: EvSpeedIcon,
      },
      {
        label: "Charging Time",
        value: activeScooter.chargingTime
          .replace(/hours?/gi, "hrs")
          .replace(/\s{2,}/g, " ")
          .trim(),
        icon: EvChargingIcon,
      },
    ],
    [activeScooter.chargingTime, activeScooter.rangeKm, activeScooter.topSpeedKmph],
  );

  const move = useCallback((direction: -1 | 1) => {
    if (featuredScooters.length === 0) {
      return;
    }

    setActiveIndex(
      (current) => (current + direction + featuredScooters.length) % featuredScooters.length,
    );
  }, [featuredScooters.length]);

  const goNext = useCallback(() => {
    move(1);
  }, [move]);

  const goPrev = useCallback(() => {
    move(-1);
  }, [move]);

  useEffect(() => {
    if (featuredScooters.length <= 1) return;

    const timer = window.setTimeout(() => {
      setActiveIndex((current) => (current + 1) % featuredScooters.length);
    }, 4500);

    return () => window.clearTimeout(timer);
  }, [activeIndex, featuredScooters.length]);

  useEffect(() => {
    if (activeIndex >= featuredScooters.length) {
      setActiveIndex(0);
    }
  }, [activeIndex, featuredScooters.length]);

  useEffect(() => {
    setHeroImageSrc(activeShowcaseImage);
  }, [activeShowcaseImage, activeScooter?.id]);

  const statsCtaBlock = (
    <div className="mt-8">
      <div className="grid gap-3 sm:grid-cols-3">
        {stats.map((stat) => {
          const Icon = stat.icon;
          return (
            <div
              key={stat.label}
              className="group relative overflow-hidden rounded-2xl border border-primary/20 bg-gradient-to-br from-white via-white to-primary/[0.06] px-4 py-3.5 shadow-[0_10px_26px_rgba(12,57,110,0.12)] transition-all duration-300 hover:-translate-y-0.5 hover:shadow-[0_14px_30px_rgba(12,57,110,0.18)]"
            >
              <div className="pointer-events-none absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-primary/65 via-ev/75 to-primary/65 opacity-80" />
              <div className="flex items-center gap-2.5">
                <span className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-primary/20 bg-primary/[0.07] text-primary transition-colors duration-300 group-hover:bg-primary/[0.12]">
                  <Icon className="h-4 w-4" />
                </span>
                <div className="min-w-0 max-w-full">
                  <p className="break-words text-[clamp(1.1rem,1.15vw,1.52rem)] font-black leading-tight tracking-tight text-navy-deep sm:whitespace-nowrap">
                    {stat.label === "Top Speed" ? (
                      <>
                        {stat.rawValue} <span className="text-[0.82em] font-extrabold">km/h</span>
                      </>
                    ) : (
                      stat.value
                    )}
                  </p>
                  <p className="mt-1 break-words text-[0.92rem] font-bold leading-5 text-navy-muted sm:text-[0.94rem]">
                    {stat.label}
                  </p>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      <Button
        href={`/scooters/${activeScooter.slug}#product-information`}
        className="mt-4 h-14 w-full rounded-full border border-primary/35 bg-gradient-to-r from-white via-primary/[0.04] to-white px-8 text-base font-extrabold text-primary shadow-[0_10px_22px_rgba(23,105,255,0.16)] transition-all duration-300 hover:-translate-y-0.5 hover:border-primary/60 hover:from-primary/[0.08] hover:to-ev/[0.08] hover:text-primary-deep hover:shadow-[0_14px_26px_rgba(23,105,255,0.24)]"
        size="sm"
        variant="outline"
      >
        View All Features
      </Button>
    </div>
  );

  return (
    <section className="overflow-hidden bg-white px-2">
      <div className="container-custom">
        <div className="relative overflow-hidden rounded-[1.75rem] bg-[radial-gradient(circle_at_74%_48%,rgba(23,105,255,0.14),transparent_34%),linear-gradient(105deg,#f7fbff_0%,#eff6ff_41%,#dcecff_100%)] px-6 pb-14 pt-9 shadow-soft md:px-10 md:pb-16 md:pt-10">
          <Image
            src={heroBackgroundImage}
            alt=""
            fill
            priority
            sizes="100vw"
            className="object-cover object-center opacity-60"
          />
          <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_18%_18%,rgba(255,255,255,0.88),transparent_36%)]" />
          <div className="pointer-events-none absolute bottom-0 right-0 h-full w-[61%] bg-[linear-gradient(90deg,rgba(255,255,255,0)_0%,rgba(216,236,255,0.44)_100%)]" />
          <div className="pointer-events-none absolute right-[7%] top-12 h-[31rem] w-[31rem] rounded-full border border-white/75 bg-white/20" />
          <div className="pointer-events-none absolute right-[13%] top-20 h-[24rem] w-[24rem] rounded-full border-2 border-white/90" />
          <div className="relative grid min-h-[30rem] items-center gap-8 lg:grid-cols-[0.95fr_1.25fr]">
            <div className="max-w-xl">
              <Badge variant="blue" className="gap-2 bg-white/90 px-4 py-2 shadow-sm">
                <EvChargingIcon className="h-3.5 w-3.5" />
                Electric Today, Better Tomorrow
              </Badge>
              <h1 className="mt-6 text-5xl font-black leading-[1.08] text-navy-deep sm:text-6xl lg:text-[4.75rem]">
                Future of{" "}
                <span className="block">
                  Mobility is{" "}
                  <span className="bg-gradient-to-r from-ev-deep via-ev to-primary bg-clip-text text-transparent">
                    Electric
                  </span>
                </span>
              </h1>
              <p className="mt-5 max-w-xl text-base font-semibold text-navy-deep">
                Smart. Stylish. Sustainable.
              </p>
              <p className="mt-2 max-w-xl text-base leading-7 text-navy-muted">
                Explore electric scooters from trusted brands. Compare models, check branch
                availability, and book your test ride today.
              </p>
              <div className="mt-7 flex flex-col gap-3 sm:flex-row">
                <Button href="/book-test-ride" variant="green">
                  Book Test Ride
                </Button>
                <Button href="/scooters" variant="outline">
                  Explore Models
                </Button>
              </div>

              {statsCtaBlock}

            </div>

            <div className="relative">
              <div className="relative min-h-[25rem] overflow-visible lg:min-h-[35rem]">
                <div className="absolute right-5 top-3 z-20 hidden rounded-2xl border border-border bg-white/90 px-4 py-3 shadow-card lg:block">
                  <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-primary">Featured Model</p>
                  <p className="mt-1 text-lg font-black text-navy-deep">{activeScooter.name}</p>
                  <p className="text-xs font-semibold text-navy-muted">{activeBrand?.name ?? "Bashista Auto"}</p>
                </div>
                <div className="pointer-events-none absolute left-1/2 top-1/2 h-[30rem] w-[30rem] -translate-x-1/2 -translate-y-1/2 rounded-full border border-white/80 bg-white/20" />
                <div className="pointer-events-none absolute bottom-8 left-1/2 h-24 w-[36rem] max-w-[90%] -translate-x-1/2 rounded-[50%] bg-primary/15 blur-md" />
                <div className="pointer-events-none absolute bottom-6 left-1/2 h-12 w-[31rem] max-w-[84%] -translate-x-1/2 rounded-[50%] bg-white/70 blur-sm" />
                <Image
                  key={activeScooter.id}
                  src={heroImageSrc}
                  alt={`${activeBrand?.name ?? "Bashista"} ${activeScooter.name}`}
                  fill
                  sizes="(max-width: 1024px) 100vw, 55vw"
                  className="absolute -bottom-8 right-0 top-1 z-10 h-full w-full object-contain object-right drop-shadow-[0_26px_36px_rgba(8,43,83,0.2)] transition-all duration-300"
                  onError={() => setHeroImageSrc("/images/scooters/hero-scooter-v2.png")}
                />
                <div className="absolute -bottom-14 left-[56%] z-20 hidden -translate-x-1/2 items-center gap-4 rounded-full border border-white/80 bg-white/70 px-3 py-2 shadow-card backdrop-blur sm:flex">
                  <button
                    type="button"
                    aria-label="Previous scooter"
                    className="inline-flex h-11 w-11 items-center justify-center rounded-full bg-white text-navy-deep shadow-[0_8px_18px_rgba(10,45,88,0.18)] transition hover:text-primary"
                    onClick={goPrev}
                  >
                    <EvChevronLeftIcon className="h-5 w-5" />
                  </button>
                  <div className="flex items-center gap-2">
                    {featuredScooters.map((scooter, index) => (
                      <button
                        key={scooter.id}
                        type="button"
                        aria-label={`Show ${scooter.name}`}
                        className={cn(
                          "h-2.5 rounded-full transition-all duration-300",
                          index === activeIndex ? "w-8 bg-ev" : "w-2.5 bg-primary/20",
                        )}
                        onClick={() => setActiveIndex(index)}
                      />
                    ))}
                  </div>
                  <button
                    type="button"
                    aria-label="Next scooter"
                    className="inline-flex h-11 w-11 items-center justify-center rounded-full bg-white text-navy-deep shadow-[0_8px_18px_rgba(10,45,88,0.18)] transition hover:text-primary"
                    onClick={goNext}
                  >
                    <EvChevronRightIcon className="h-5 w-5" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <HeroModelStrip
        activeIndex={activeIndex}
        brands={brands}
        scooters={featuredScooters}
        onMove={move}
        onSelect={setActiveIndex}
      />
    </section>
  );
}
