"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Image from "next/image";
import { ChevronLeft, ChevronRight, Search, Plane, Calendar, Users, ArrowLeftRight } from "lucide-react";

export type TicketSlideItem = {
  id: string;
  imageUrl: string;
  title: string;
  subtitle: string;
  ctaText: string;
  ctaLink: string;
};

export type TicketCountryOption = {
  id: string;
  name: string;
  cities: Array<{ id: string; name: string }>;
};

export type TicketSearchState = {
  fromCountryId: string;
  fromCityId: string;
  toCountryId: string;
  toCityId: string;
  tripType: "one_way" | "return_trip";
  departureDate: string;
  returnDate: string;
  passengers: number;
};

const fallbackSlides: TicketSlideItem[] = [
  {
    id: "1",
    imageUrl: "https://images.unsplash.com/photo-1436491865332-7a61a109cc05?w=1800&q=80",
    title: "Book International Flights Easily",
    subtitle: "Tell us your route and dates. Our team will manually source the best fare options for you.",
    ctaText: "Create Request",
    ctaLink: "#ticket-request",
  },
  {
    id: "2",
    imageUrl: "https://images.unsplash.com/photo-1483450388369-9ed95738483c?w=1800&q=80",
    title: "One-Way or Return Ticket Requests",
    subtitle: "Choose your trip type, cities, and travel dates. We handle the rest from our admin desk.",
    ctaText: "Start Search",
    ctaLink: "#ticket-request",
  },
  {
    id: "3",
    imageUrl: "https://images.unsplash.com/photo-1517479149777-5f3b1511d5ad?w=1800&q=80",
    title: "Human Support for Every Booking",
    subtitle: "No auto checkout. Every request is reviewed by super admin and followed up by email.",
    ctaText: "Request Now",
    ctaLink: "#ticket-request",
  },
];

export default function TicketsSlider({
  slides,
  countries,
  value,
  onChange,
  onApplySearch,
}: {
  slides: TicketSlideItem[];
  countries: TicketCountryOption[];
  value: TicketSearchState;
  onChange: (next: TicketSearchState) => void;
  onApplySearch: () => void;
}) {
  const safeSlides = slides.length ? slides : fallbackSlides;
  const [current, setCurrent] = useState(0);

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

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

  const fromCities = useMemo(
    () => countries.find((c) => c.id === value.fromCountryId)?.cities ?? [],
    [countries, value.fromCountryId]
  );
  const toCities = useMemo(
    () => countries.find((c) => c.id === value.toCountryId)?.cities ?? [],
    [countries, value.toCountryId]
  );

  const slide = safeSlides[current];

  return (
    <div className="relative">
      <div className="relative h-[420px] md:h-[500px] overflow-hidden bg-navy-900">
        {safeSlides.map((s, i) => (
          <div key={s.id} className={`absolute inset-0 transition-opacity duration-700 ${i === current ? "opacity-100" : "opacity-0"}`}>
            <Image src={s.imageUrl} alt={s.title} fill priority={i === 0} className="object-cover" sizes="100vw" unoptimized />
            <div className="absolute inset-0 bg-gradient-to-r from-navy-950/90 via-navy-900/70 to-navy-900/30" />
          </div>
        ))}

        <div className="relative z-10 h-full flex items-center">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
            <div className="max-w-2xl">
              <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-semibold text-gold-300 bg-gold-500/15 border border-gold-500/30 mb-4">
                <Plane size={12} /> Manual Ticket Desk
              </div>
              <h1 className="text-3xl md:text-5xl font-bold text-white leading-tight">{slide.title}</h1>
              <p className="mt-4 text-sm md:text-base text-white/80 max-w-xl">{slide.subtitle}</p>
              <a href={slide.ctaLink || "#ticket-request"} className="inline-flex mt-6 px-5 py-2.5 rounded-xl bg-gold-500 hover:bg-gold-600 text-white text-sm font-semibold transition-colors">
                {slide.ctaText || "Create Request"}
              </a>
            </div>
          </div>
        </div>

        <button onClick={prev} className="absolute z-20 left-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full border border-white/20 bg-white/10 hover:bg-white/20 text-white flex items-center justify-center">
          <ChevronLeft size={18} />
        </button>
        <button onClick={next} className="absolute z-20 right-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full border border-white/20 bg-white/10 hover:bg-white/20 text-white flex items-center justify-center">
          <ChevronRight size={18} />
        </button>
      </div>

      <div className="relative z-30 -mt-10 px-4 sm:px-6">
        <div className="max-w-6xl mx-auto bg-white border border-neutral-200 rounded-2xl shadow-2xl p-4 md:p-5 grid lg:grid-cols-6 gap-3">
          <div className="lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-neutral-600 mb-1">From Country</label>
              <select
                value={value.fromCountryId}
                onChange={(e) => onChange({ ...value, fromCountryId: e.target.value, fromCityId: "" })}
                className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              >
                <option value="">Select country</option>
                {countries.map((c) => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-neutral-600 mb-1">From City</label>
              <select
                value={value.fromCityId}
                onChange={(e) => onChange({ ...value, fromCityId: e.target.value })}
                className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              >
                <option value="">Select city</option>
                {fromCities.map((city) => (
                  <option key={city.id} value={city.id}>{city.name}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-neutral-600 mb-1">To Country</label>
              <select
                value={value.toCountryId}
                onChange={(e) => onChange({ ...value, toCountryId: e.target.value, toCityId: "" })}
                className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              >
                <option value="">Select country</option>
                {countries.map((c) => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-neutral-600 mb-1">To City</label>
              <select
                value={value.toCityId}
                onChange={(e) => onChange({ ...value, toCityId: e.target.value })}
                className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              >
                <option value="">Select city</option>
                {toCities.map((city) => (
                  <option key={city.id} value={city.id}>{city.name}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
            <div>
              <label className="block text-xs font-medium text-neutral-600 mb-1">Trip</label>
              <div className="relative">
                <ArrowLeftRight size={14} className="absolute left-2.5 top-2.5 text-neutral-400" />
                <select
                  value={value.tripType}
                  onChange={(e) => onChange({ ...value, tripType: e.target.value as "one_way" | "return_trip" })}
                  className="w-full border border-neutral-300 rounded-lg pl-8 pr-3 py-2 text-sm"
                >
                  <option value="one_way">One Way</option>
                  <option value="return_trip">Return</option>
                </select>
              </div>
            </div>
            <div>
              <label className="block text-xs font-medium text-neutral-600 mb-1">Departure</label>
              <div className="relative">
                <Calendar size={14} className="absolute left-2.5 top-2.5 text-neutral-400" />
                <input type="date" value={value.departureDate} onChange={(e) => onChange({ ...value, departureDate: e.target.value })} className="w-full border border-neutral-300 rounded-lg pl-8 pr-3 py-2 text-sm" />
              </div>
            </div>
            <div>
              <label className="block text-xs font-medium text-neutral-600 mb-1">Return</label>
              <div className="relative">
                <Calendar size={14} className="absolute left-2.5 top-2.5 text-neutral-400" />
                <input
                  type="date"
                  value={value.returnDate}
                  onChange={(e) => onChange({ ...value, returnDate: e.target.value })}
                  disabled={value.tripType !== "return_trip"}
                  className="w-full border border-neutral-300 rounded-lg pl-8 pr-3 py-2 text-sm disabled:bg-neutral-100"
                />
              </div>
            </div>
            <div>
              <label className="block text-xs font-medium text-neutral-600 mb-1">Passengers</label>
              <div className="relative">
                <Users size={14} className="absolute left-2.5 top-2.5 text-neutral-400" />
                <input
                  type="number"
                  min={1}
                  max={9}
                  value={value.passengers}
                  onChange={(e) => onChange({ ...value, passengers: Number(e.target.value) || 1 })}
                  className="w-full border border-neutral-300 rounded-lg pl-8 pr-3 py-2 text-sm"
                />
              </div>
            </div>
          </div>

          <div className="lg:col-span-6 flex justify-end">
            <button
              onClick={onApplySearch}
              className="inline-flex items-center gap-2 px-5 py-2.5 bg-navy-700 hover:bg-navy-800 text-white text-sm font-semibold rounded-xl"
            >
              <Search size={15} /> Use These Search Details
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
