"use client";

import { useEffect, useRef, useState } from "react";
import { getAllCities } from "@/api/bookingApi";
import { useAppDispatch } from "@/store/hooks";
import { setCity } from "@/store/slices/bookingSlice";
import { Search, ChevronLeft, ChevronRight } from "lucide-react";
import Image from "next/image";

interface Props {
  open: boolean;
  onClose: (city?: string) => void;
}

export default function CitySelectModal({ open, onClose }: Props) {
  const [cities, setCities] = useState<string[]>([]);
  const [search, setSearch] = useState("");
  const scrollRef = useRef<HTMLDivElement>(null);

  const dispatch = useAppDispatch();

  useEffect(() => {
    if (open) {
      getAllCities().then(setCities);
    }
  }, [open]);

  if (!open) return null;

  const filtered = cities.filter((c) =>
    c.toLowerCase().includes(search.toLowerCase())
  );

  const scrollLeft = () => {
    scrollRef.current?.scrollBy({ left: -300, behavior: "smooth" });
  };

  const scrollRight = () => {
    scrollRef.current?.scrollBy({ left: 300, behavior: "smooth" });
  };

const images = ["/location.svg", "/location.svg", "/location.svg", "/location.svg"];

  return (
   <div
  className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center px-4"
  onClick={() => onClose()}
>

    <div
  className="bg-white rounded-2xl w-full max-w-5xl p-6 relative shadow-xl border"
  onClick={(e) => e.stopPropagation()} // ✅ PREVENT CLOSE WHEN CLICKING INSIDE
>  
       

        <h2 className="text-xl font-semibold mb-6">
          Select City to Continue
        </h2>

        {/* Search */}
        <div className="flex items-center gap-3 border rounded-xl px-4 py-3 mb-6">
          <Search size={18} />
          <input
            placeholder="Search city"
            className="flex-1 outline-none"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>

        {/* Cities */}
        <div className="relative">
          <button
  onClick={scrollLeft}
  className="absolute -left-4 top-1/2 -translate-y-1/2 z-10 flex items-center justify-center w-10 h-10 rounded-full bg-white shadow-md border hover:bg-gray-50"
>
  <ChevronLeft className="w-5 h-5" />
</button>

          <div
            ref={scrollRef}
            className="flex gap-4 overflow-x-auto"
          >
           {filtered.map((city, index) => {
  const image = images[index % images.length]; // 🔁 rotation logic

  return (
    <div
      key={city}
     onClick={() => {
  dispatch(setCity(city));
  localStorage.setItem("selectedCity", city);

  onClose(city); // ✅ PASS CITY HERE
}}
      className="min-w-[140px] rounded-xl overflow-hidden border cursor-pointer hover:border-orange-400 hover:shadow-md transition"
    >
      {/* Image */}
      <div className="w-full h-[100px] bg-gray-100">
        <Image
          src={image}
          alt={city}
           width={180}
  height={54}
          className="w-full h-full object-cover"
        />
      </div>

      {/* City Name */}
      <div className="py-2 text-center">
        <p className="text-sm font-semibold text-gray-800">
          {city}
        </p>
      </div>
    </div>
  );
})}
          </div>

          <button
  onClick={scrollRight}
  className="absolute -right-4 top-1/2 -translate-y-1/2 z-10 flex items-center justify-center w-10 h-10 rounded-full bg-white shadow-md border hover:bg-gray-50"
>
  <ChevronRight className="w-5 h-5" />
</button>
        </div>
      </div>
    </div>
  );
}