"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import Image from "next/image";
import {
  ArrowRight, ChevronLeft, ChevronRight, Search, Globe,
  GraduationCap, Briefcase, Plane, Building2, Users, Calendar, FileText,
} from "lucide-react";

export type VisaSlideItem = {
  id: string;
  image: string;
  badge: string;
  badgeIcon: "graduation" | "briefcase" | "plane" | "building" | "users" | "globe";
  title: string;
  highlight: string;
  description: string;
  cta: { label: string; href: string };
  ctaSecondary: { label: string; href: string };
  stats: Array<{ label: string; value: string }>;
};

const fallbackSlides: VisaSlideItem[] = [
  {
    id: "1",
    image: "https://images.pexels.com/photos/207684/pexels-photo-207684.jpeg?auto=compress&cs=tinysrgb&w=1920",
    badgeIcon: "graduation",
    badge: "Student Visa",
    title: "Study at the",
    highlight: "World's Best Universities",
    description:
      "We handle your student visa from start to finish — document review, application prep, embassy submission — so you can focus on your future.",
    cta: { label: "Apply Now", href: "/visa/apply?type=student-visa" },
    ctaSecondary: { label: "Explore Countries", href: "/visa" },
    stats: [
      { label: "Success Rate", value: "97%" },
      { label: "Countries", value: "40+" },
      { label: "Students Placed", value: "3,200+" },
    ],
  },
  {
    id: "2",
    image: "https://images.pexels.com/photos/323780/pexels-photo-323780.jpeg?auto=compress&cs=tinysrgb&w=1920",
    badgeIcon: "briefcase",
    badge: "Work Visa",
    title: "Build Your Career",
    highlight: "Anywhere in the World",
    description:
      "Skilled worker visas, employer sponsorship guidance, and work permit applications across the UK, Australia, Canada, UAE and more.",
    cta: { label: "Get Started", href: "/visa/apply?type=work-visa" },
    ctaSecondary: { label: "View Requirements", href: "/visa" },
    stats: [
      { label: "Processed", value: "5,800+" },
      { label: "Avg. Timeline", value: "6 Weeks" },
      { label: "Countries", value: "30+" },
    ],
  },
  {
    id: "3",
    image: "https://images.pexels.com/photos/62623/wing-plane-flying-airplane-62623.jpeg?auto=compress&cs=tinysrgb&w=1920",
    badgeIcon: "plane",
    badge: "Tourist & Holiday Visa",
    title: "Travel the World",
    highlight: "Without the Hassle",
    description:
      "Holiday visas, tourist visas, and multi-entry permits handled quickly. We prepare your documentation so your trip starts on time.",
    cta: { label: "Plan My Trip", href: "/visa/apply?type=tourist-visa" },
    ctaSecondary: { label: "See Destinations", href: "/visa" },
    stats: [
      { label: "Applications", value: "12,000+" },
      { label: "Avg. Processing", value: "3–5 Days" },
      { label: "Countries", value: "50+" },
    ],
  },
  {
    id: "4",
    image: "https://images.pexels.com/photos/325185/pexels-photo-325185.jpeg?auto=compress&cs=tinysrgb&w=1920",
    badgeIcon: "building",
    badge: "Business Visa",
    title: "Expand Your Business",
    highlight: "Across Borders",
    description:
      "Business visas, investor permits, and company establishment support. We make cross-border commerce smooth and compliant.",
    cta: { label: "Business Enquiry", href: "/visa/apply?type=business-visa" },
    ctaSecondary: { label: "Learn More", href: "/visa" },
    stats: [
      { label: "Businesses Served", value: "420+" },
      { label: "Countries", value: "25+" },
      { label: "Expert Advisors", value: "15" },
    ],
  },
  {
    id: "5",
    image: "https://images.pexels.com/photos/1388944/pexels-photo-1388944.jpeg?auto=compress&cs=tinysrgb&w=1920",
    badgeIcon: "users",
    badge: "Family & PR",
    title: "Reunite Your Family",
    highlight: "Start a New Life",
    description:
      "Family reunion visas, spouse permits, and permanent residency applications — we guide every member of your family through the process.",
    cta: { label: "Family Visa Enquiry", href: "/visa/apply?type=family-visa" },
    ctaSecondary: { label: "PR Pathways", href: "/visa" },
    stats: [
      { label: "Families United", value: "1,900+" },
      { label: "PR Approvals", value: "680+" },
      { label: "Countries", value: "20+" },
    ],
  },
];

type BadgeIconType = "graduation" | "briefcase" | "plane" | "building" | "users" | "globe";

function BadgeIcon({ type }: { type: BadgeIconType }) {
  if (type === "graduation") return <GraduationCap size={12} className="shrink-0" />;
  if (type === "briefcase") return <Briefcase size={12} className="shrink-0" />;
  if (type === "plane") return <Plane size={12} className="shrink-0" />;
  if (type === "building") return <Building2 size={12} className="shrink-0" />;
  if (type === "users") return <Users size={12} className="shrink-0" />;
  return <Globe size={12} className="shrink-0" />;
}

export default function VisaSlider({ slides = fallbackSlides }: { slides?: VisaSlideItem[] }) {
  const [current, setCurrent] = useState(0);
  const [transitioning, setTransitioning] = useState(false);
  const [failedSlides, setFailedSlides] = useState<Record<number, boolean>>({});

  const fallbackImage = "https://images.pexels.com/photos/531880/pexels-photo-531880.jpeg?auto=compress&cs=tinysrgb&w=1920";
  const safeSlides = slides.length ? slides : fallbackSlides;

  const goTo = useCallback(
    (index: number) => {
      if (transitioning) return;
      setTransitioning(true);
      setCurrent(index);
      setTimeout(() => setTransitioning(false), 600);
    },
    [transitioning]
  );

  const prev = () => goTo((current - 1 + safeSlides.length) % safeSlides.length);
  const next = useCallback(() => goTo((current + 1) % safeSlides.length), [current, goTo, safeSlides.length]);

  useEffect(() => {
    const t = setInterval(next, 6000);
    return () => clearInterval(t);
  }, [next]);

  const slide = safeSlides[current];

  return (
    <div className="relative">
      {/* Slider frame */}
      <div className="relative h-[460px] md:h-[540px] overflow-hidden bg-navy-900">
        {/* Background images */}
        {safeSlides.map((s, i) => (
          <div
            key={s.id}
            className={`absolute inset-0 transition-opacity duration-700 ease-in-out ${i === current ? "opacity-100" : "opacity-0"}`}
          >
            <Image
              src={failedSlides[i] ? fallbackImage : s.image}
              alt={s.badge}
              fill
              priority={i === 0}
              className="object-cover"
              sizes="100vw"
              unoptimized
              onError={() => setFailedSlides((prev) => ({ ...prev, [i]: true }))}
            />
            <div className="absolute inset-0 bg-gradient-to-r from-navy-950/90 via-navy-900/70 to-transparent" />
          </div>
        ))}

        {/* Content */}
        <div className="relative z-10 h-full flex flex-col justify-center pb-14 md:pb-12">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
            <div className="max-w-2xl">
              {/* Badge */}
              <div className="inline-flex items-center gap-2 px-3 py-1.5 bg-gold-500/20 text-gold-300 text-xs font-semibold rounded-full mb-4 border border-gold-500/30">
                <BadgeIcon type={slide.badgeIcon} />
                {slide.badge}
              </div>

              {/* Headline */}
              <h1 className="text-3xl md:text-5xl lg:text-6xl font-bold text-white leading-tight tracking-tight">
                {slide.title}
                <br />
                <span className="text-gold-400">{slide.highlight}</span>
              </h1>

              {/* Description */}
              <p className="mt-4 text-base text-white/75 leading-relaxed max-w-xl">
                {slide.description}
              </p>

              {/* Stats */}
              <div className="flex gap-5 md:gap-6 mt-5 flex-wrap">
                {slide.stats.map((stat) => (
                  <div key={stat.label}>
                    <div className="text-lg font-bold text-gold-400">{stat.value}</div>
                    <div className="text-xs text-white/55">{stat.label}</div>
                  </div>
                ))}
              </div>

              {/* CTA Buttons */}
              <div className="flex flex-wrap items-center gap-3 mt-6">
                <Link
                  href={slide.cta.href}
                  className="inline-flex items-center gap-2 px-5 py-2.5 bg-gold-500 hover:bg-gold-600 text-white text-sm font-semibold rounded-xl transition-all shadow-lg shadow-gold-500/25"
                >
                  {slide.cta.label}
                  <ArrowRight size={14} />
                </Link>
                <Link
                  href={slide.ctaSecondary.href}
                  className="inline-flex items-center gap-2 px-5 py-2.5 bg-white/10 hover:bg-white/20 text-white text-sm font-medium rounded-xl border border-white/20 backdrop-blur-sm transition-all"
                >
                  {slide.ctaSecondary.label}
                </Link>
              </div>
            </div>
          </div>
        </div>

        {/* Arrows */}
        <button
          onClick={prev}
          aria-label="Previous slide"
          className="absolute left-4 top-1/2 -translate-y-1/2 z-20 w-9 h-9 bg-white/10 hover:bg-white/25 backdrop-blur-sm rounded-full flex items-center justify-center text-white border border-white/20 transition-all"
        >
          <ChevronLeft size={18} />
        </button>
        <button
          onClick={next}
          aria-label="Next slide"
          className="absolute right-4 top-1/2 -translate-y-1/2 z-20 w-9 h-9 bg-white/10 hover:bg-white/25 backdrop-blur-sm rounded-full flex items-center justify-center text-white border border-white/20 transition-all"
        >
          <ChevronRight size={18} />
        </button>

        {/* Dots */}
        <div className="absolute bottom-16 md:bottom-5 left-1/2 -translate-x-1/2 z-20 flex items-center gap-2">
          {safeSlides.map((_, i) => (
            <button
              key={i}
              onClick={() => goTo(i)}
              aria-label={`Go to slide ${i + 1}`}
              className={`transition-all rounded-full ${
                i === current ? "w-7 h-2 bg-gold-400" : "w-2 h-2 bg-white/30 hover:bg-white/60"
              }`}
            />
          ))}
        </div>

        {/* Slide counter */}
        <div className="absolute bottom-16 md:bottom-5 right-6 z-20 text-white/40 text-xs font-mono">
          {String(current + 1).padStart(2, "0")} / {String(safeSlides.length).padStart(2, "0")}
        </div>
      </div>

      {/* Floating search bar — outside overflow-hidden */}
      <div className="relative z-20 -mt-8 px-4 sm:px-6">
        <div className="max-w-5xl mx-auto">
          <div className="bg-white rounded-2xl shadow-2xl border border-neutral-200 overflow-hidden grid md:grid-cols-[1.2fr_1.3fr_1fr_auto]">
            <div className="flex items-center gap-2 px-4 border-b md:border-b-0 md:border-r border-neutral-200 min-w-0">
              <FileText size={16} className="text-neutral-400 shrink-0" />
              <select className="flex-1 py-4 text-sm text-neutral-700 bg-transparent focus:outline-none cursor-pointer appearance-none min-w-0">
                <option value="">All Visa Types</option>
                <option value="student-visa">Student Visa</option>
                <option value="work-visa">Work Visa</option>
                <option value="tourist-visa">Tourist Visa</option>
                <option value="business-visa">Business Visa</option>
                <option value="family-visa">Family / Spouse Visa</option>
                <option value="pr-visa">Permanent Residency</option>
                <option value="working-holiday">Holiday Working Visa</option>
                <option value="transit-visa">Transit Visa</option>
              </select>
            </div>
            <div className="flex items-center gap-2 px-4 border-b md:border-b-0 md:border-r border-neutral-200 min-w-0">
              <Search size={16} className="text-neutral-400 shrink-0" />
              <input
                type="search"
                placeholder="Destination country (e.g. UK, Japan)"
                className="flex-1 py-4 text-sm text-neutral-800 placeholder:text-neutral-400 focus:outline-none bg-transparent min-w-0"
              />
            </div>
            <div className="flex items-center gap-2 px-4 border-b md:border-b-0 md:border-r border-neutral-200 min-w-0">
              <Calendar size={16} className="text-neutral-400 shrink-0" />
              <input
                type="text"
                placeholder="Travel month"
                className="flex-1 py-4 text-sm text-neutral-800 placeholder:text-neutral-400 focus:outline-none bg-transparent min-w-0"
              />
            </div>
            <Link
              href="/visa/apply"
              className="flex items-center justify-center gap-2 px-6 py-4 bg-gold-500 hover:bg-gold-600 text-white text-sm font-semibold transition-colors whitespace-nowrap"
            >
              <Search size={15} />
              Find Visa
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
