"use client";

import { useState, useRef, useEffect } from "react";
import { 
  Gift, Plane, Car, CalendarDays, 
  MapPin, Calendar as CalendarIcon, Users, Search, ChevronDown, Check
} from "lucide-react";
import { Link } from "@/routing";

const destinationsList = [
  "Bali", "Lombok", "Labuan Bajo", "Raja Ampat", "Sumba", "Yogyakarta", "Bandung"
];

const participantsList = [
  "1 Orang", "2 Orang", "3 Orang", "4 Orang", "5+ Orang"
];

export function BookingWidget() {
  const [activeTab, setActiveTab] = useState("tour");
  const [destinasi, setDestinasi] = useState("");
  const [tanggal, setTanggal] = useState("");
  const [peserta, setPeserta] = useState("1 Orang");

  const [isDestOpen, setIsDestOpen] = useState(false);
  const [isPesertaOpen, setIsPesertaOpen] = useState(false);
  
  const dateInputRef = useRef<HTMLInputElement>(null);
  const destRef = useRef<HTMLDivElement>(null);
  const pesertaRef = useRef<HTMLDivElement>(null);

  // Close dropdowns when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (destRef.current && !destRef.current.contains(event.target as Node)) {
        setIsDestOpen(false);
      }
      if (pesertaRef.current && !pesertaRef.current.contains(event.target as Node)) {
        setIsPesertaOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const tabs = [
    { id: "tour", label: "Tour Package", icon: Gift, href: "/tour" },
    { id: "flight", label: "Flight Tickets", icon: Plane, href: "/flight" },
    { id: "car", label: "Car Rental", icon: Car, href: "/car-rental" },
    { id: "event", label: "Events", icon: CalendarDays, href: "/event" },
  ];

  const activeHref = tabs.find((tab) => tab.id === activeTab)?.href ?? "/tour";

  const handleDateClick = () => {
    if (dateInputRef.current) {
      if (typeof dateInputRef.current.showPicker === 'function') {
        dateInputRef.current.showPicker();
      } else {
        dateInputRef.current.focus();
      }
    }
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return "dd-mm-yyyy";
    const date = new Date(dateString);
    return date.toLocaleDateString("id-ID", { day: "2-digit", month: "short", year: "numeric" });
  };

  return (
    <div className="mx-auto max-w-[1100px] -mt-20 md:-mt-24 px-4 sm:px-6 lg:px-8 relative z-30">
      <div className="flex flex-col bg-white rounded-[32px] drop-shadow-[0_20px_40px_rgba(0,0,0,0.15)] p-2 md:p-3">
        
        {/* Tabs Container */}
        <div className="flex items-center border-b border-gray-100 px-2 md:px-6 pb-3 pt-2 gap-2 md:gap-8 overflow-x-auto no-scrollbar">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            const isActive = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center justify-center gap-2.5 py-3 px-6 text-[14px] font-bold transition-all rounded-2xl shrink-0 ${
                  isActive 
                    ? "bg-white text-[#d32f2f] shadow-[0_8px_20px_-6px_rgba(211,47,47,0.3)] border border-red-50/50" 
                    : "text-gray-500 hover:text-gray-800 hover:bg-gray-50"
                }`}
              >
                <Icon className={`h-5 w-5 ${isActive ? "text-[#d32f2f]" : "text-gray-400"}`} strokeWidth={isActive ? 2.5 : 2} />
                {tab.label}
              </button>
            );
          })}
        </div>

        {/* Form Body */}
        <div className="flex flex-col md:flex-row items-stretch divide-y md:divide-y-0 md:divide-x divide-gray-100/80 px-2 md:px-4 py-3">
          
          {/* Destinasi Dropdown */}
          <div className="flex-1 relative" ref={destRef}>
            <button 
              type="button"
              onClick={() => setIsDestOpen(!isDestOpen)}
              className="w-full text-left flex items-center justify-between p-4 md:p-6 hover:bg-gray-50 transition-colors group rounded-xl"
            >
              <div className="flex items-center gap-3">
                <div className="text-merah-ranata">
                  <MapPin className="h-6 w-6 stroke-[1.5]" />
                </div>
                <div>
                  <p className="text-sm font-bold text-heading">Destinasi</p>
                  <p className="text-sm text-muted mt-0.5">{destinasi || "Pilih destinasi"}</p>
                </div>
              </div>
              <ChevronDown className={`h-4 w-4 text-gray-400 transition-transform ${isDestOpen ? 'rotate-180' : ''}`} />
            </button>

            {isDestOpen && (
              <div className="absolute top-full left-0 right-0 mt-2 bg-white rounded-xl shadow-xl border border-gray-100 overflow-hidden z-50 py-2">
                {destinationsList.map((dest) => (
                  <button
                    key={dest}
                    onClick={() => {
                      setDestinasi(dest);
                      setIsDestOpen(false);
                    }}
                    className="w-full text-left px-6 py-3 text-sm hover:bg-red-50 hover:text-merah-ranata transition-colors flex items-center justify-between"
                  >
                    {dest}
                    {destinasi === dest && <Check className="h-4 w-4 text-merah-ranata" />}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Tanggal Picker */}
          <div className="flex-1 relative">
            <button 
              type="button"
              onClick={handleDateClick}
              className="w-full text-left flex items-center justify-between p-4 md:p-6 hover:bg-gray-50 transition-colors group rounded-xl"
            >
              <div className="flex items-center gap-3">
                <div className="text-merah-ranata">
                  <CalendarIcon className="h-6 w-6 stroke-[1.5]" />
                </div>
                <div>
                  <p className="text-sm font-bold text-heading">Tanggal</p>
                  <p className="text-sm text-muted mt-0.5">{formatDate(tanggal)}</p>
                </div>
              </div>
              <ChevronDown className="h-4 w-4 text-gray-400" />
            </button>
            <input
              ref={dateInputRef}
              type="date"
              value={tanggal}
              onChange={(e) => setTanggal(e.target.value)}
              className="absolute opacity-0 w-0 h-0 pointer-events-none"
            />
          </div>

          {/* Jumlah Peserta Dropdown */}
          <div className="flex-1 relative" ref={pesertaRef}>
            <button 
              type="button"
              onClick={() => setIsPesertaOpen(!isPesertaOpen)}
              className="w-full text-left flex items-center justify-between p-4 md:p-6 hover:bg-gray-50 transition-colors group rounded-xl"
            >
              <div className="flex items-center gap-3">
                <div className="text-merah-ranata">
                  <Users className="h-6 w-6 stroke-[1.5]" />
                </div>
                <div>
                  <p className="text-sm font-bold text-heading">Jumlah Peserta</p>
                  <p className="text-sm text-muted mt-0.5">{peserta}</p>
                </div>
              </div>
              <ChevronDown className={`h-4 w-4 text-gray-400 transition-transform ${isPesertaOpen ? 'rotate-180' : ''}`} />
            </button>

            {isPesertaOpen && (
              <div className="absolute top-full left-0 right-0 mt-2 bg-white rounded-xl shadow-xl border border-gray-100 overflow-hidden z-50 py-2">
                {participantsList.map((item) => (
                  <button
                    key={item}
                    onClick={() => {
                      setPeserta(item);
                      setIsPesertaOpen(false);
                    }}
                    className="w-full text-left px-6 py-3 text-sm hover:bg-red-50 hover:text-merah-ranata transition-colors flex items-center justify-between"
                  >
                    {item}
                    {peserta === item && <Check className="h-4 w-4 text-merah-ranata" />}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Submit Button */}
          <div className="p-2 md:p-3 flex items-center justify-center shrink-0">
            <Link
              href={`${activeHref}?dest=${destinasi}&date=${tanggal}&pax=${peserta}`}
              className="w-full md:w-auto bg-[#d32f2f] hover:bg-[#b71c1c] text-white rounded-2xl px-8 py-4 md:py-0 md:h-full flex items-center justify-center gap-2 font-bold text-sm transition shadow-lg shadow-red-900/20"
            >
              <Search className="h-5 w-5" />
              Cari Sekarang
            </Link>
          </div>

        </div>
      </div>
    </div>
  );
}
