// components/home/SearchSection.tsx

"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useAppSelector } from "@/store/hooks";
import CitySelectModal from "@/components/common/CitySelectModal";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const today = new Date().toISOString().split("T")[0];

const generateTimeOptions = (selectedDate: string) => {
  const options: string[] = [];
  const now = new Date();

  const isToday =
    selectedDate &&
    new Date(selectedDate).toDateString() === now.toDateString();

  for (let h = 0; h < 24; h++) {
    for (let m of ["00", "30"]) {
      const time = `${String(h).padStart(2, "0")}:${m}`;

      if (isToday) {
        const currentMinutes =
          now.getHours() * 60 + now.getMinutes();
        const optionMinutes = h * 60 + Number(m);
        if (optionMinutes < currentMinutes) continue;
      }

      options.push(time);
    }
  }

  return options;
};

const formatTo12Hour = (time: string) => {
  if (!time) return "";
  let [hours, minutes] = time.split(":").map(Number);

  const ampm = hours >= 12 ? "PM" : "AM";
  hours = hours % 12 || 12; // convert 0 -> 12

  return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")} ${ampm}`;
};

export default function SearchSection({
  searchParams,
}: {
  searchParams: any;
}) {
  const router = useRouter();

  const { city } = useAppSelector((state) => state.booking);
  const { access_token } = useAppSelector((state) => state.auth);

  const [openCity, setOpenCity] = useState(false);
    

const [pickupDate, setPickupDate] = useState(
  searchParams?.from?.split("T")[0] || today
);

const [pickupTime, setPickupTime] = useState(
  searchParams?.from?.split("T")[1]?.slice(0, 5) || ""
);

const [returnDate, setReturnDate] = useState(
  searchParams?.to?.split("T")[0] || ""
);

const [returnTime, setReturnTime] = useState(
  searchParams?.to?.split("T")[1] || ""
);

const [months, setMonths] = useState(
  searchParams?.months || ""
);

const [rentalType, setRentalType] = useState(
  searchParams?.rental_type || "daily"
);

  const [error, setError] = useState("");



  // ✅ HANDLE SEARCH (same as handleNext)
  const handleSearch = () => {

    // ✅ LOGIN CHECK
    // if (!access_token) {
    //   alert("Please login first");
    //   return;
    // }

    // ✅ CITY CHECK
    if (!city) {
      setOpenCity(true);
      return;
    }

    // ✅ PICKUP VALIDATION
    if (!pickupDate || !pickupTime) {
      setError("Please select pickup date and time");
      return;
    }

    // ✅ DAILY VALIDATION
    if (rentalType === "daily") {
      if (!returnDate || !returnTime) {
        setError("Please select return date and time");
        return;
      }

      const pickupDateTime = new Date(`${pickupDate}T${pickupTime}`);
      const returnDateTime = new Date(`${returnDate}T${returnTime}`);

      const diffInHours =
        (returnDateTime.getTime() - pickupDateTime.getTime()) /
        (1000 * 60 * 60);

      if (diffInHours < 1) {
        setError(
          "Return time must be at least 1 hour after pickup time"
        );
        return;
      }
    }

    // ✅ MONTHLY VALIDATION
    if (rentalType === "monthly") {
      if (!months) {
        setError("Please select number of months");
        return;
      }
    }

    setError("");

    // ✅ NAVIGATION (Next.js)
    router.push(
      `/vehicles?city=${city}&rental_type=${rentalType}&from=${pickupDate}T${pickupTime}&to=${
        rentalType === "daily"
          ? `${returnDate}T${returnTime}`
          : ""
      }&months=${months}`
    );
  };

  return (
    <>
      <section className="relative -mt-10 sm:-mt-14 md:-mt-16 z-20 px-4 sm:px-6">
        <div className="max-w-7xl mx-auto">
          <div className="bg-white rounded-xl border border-gray-300 shadow-md p-5 sm:p-6">

            <p className="text-primary font-semibold text-sm mb-5">
              Find your ride here!
            </p>

            <div className="flex flex-col lg:flex-row lg:items-center gap-6 lg:gap-4">

              {/* RENTAL TYPE */}
              <div className="lg:min-w-[220px]">
                <label className="flex items-center gap-2 text-sm">
                  <input
                    type="radio"
                    value="daily"
                    checked={rentalType === "daily"}
                    onChange={() => setRentalType("daily")}
                    className="accent-yellow-500"
                  />
                  Hourly/Daily rentals
                </label>

                <label className="flex items-center gap-2 text-sm mt-2">
                  <input
                    type="radio"
                    value="monthly"
                    checked={rentalType === "monthly"}
                    onChange={() => setRentalType("monthly")}
                    className="accent-yellow-500"
                  />
                  Monthly rentals
                </label>
              </div>

              <div className="hidden lg:block h-10 w-px bg-gray-300" />

              {/* FIELDS */}
              <div className="flex-1 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">

                {/* PICKUP DATE */}
                <div>
                  <label className="text-xs text-gray-500 font-medium">
                    Pickup Date
                  </label>
                  <input
                    type="date"
                    min={today}
                    value={pickupDate}
                    onChange={(e) => setPickupDate(e.target.value)}
                    onClick={(e: any) => e.target.showPicker()}
                    className="outline-none font-semibold text-sm mt-1 w-full cursor-pointer"
                  />
                </div>

                {/* PICKUP TIME */}
                <div>
                  <label className="text-xs text-gray-500 font-medium">
                    Pickup Time
                  </label>
                 <Select
  value={pickupTime}
  onValueChange={(value) => setPickupTime(value)}
>
  <SelectTrigger className="mt-1 h-11 w-full border border-gray-200 rounded-md bg-white px-3 font-semibold text-sm focus:ring-0 focus:border-primary">
    <SelectValue placeholder="Time" />
  </SelectTrigger>

  <SelectContent>
    {generateTimeOptions(pickupDate).map((t) => (
      <SelectItem
        key={t}
        value={t}
         className="z-[9999] bg-white border border-gray-200 shadow-lg rounded-md"
      >
        {formatTo12Hour(t)}
      </SelectItem>
    ))}
  </SelectContent>
</Select>
                </div>

                {/* RETURN DATE */}
                {rentalType === "daily" && (
                  <div>
                    <label className="text-xs text-gray-500 font-medium">
                      Return Date
                    </label>
                    <input
                      type="date"
                      min={pickupDate || today}
                      value={returnDate}
                      onChange={(e) => setReturnDate(e.target.value)}
                      onClick={(e: any) => e.target.showPicker()}
                      className="outline-none font-semibold text-sm mt-1 w-full cursor-pointer"
                    />
                  </div>
                )}

                {/* RETURN TIME */}
                {rentalType === "daily" && (
                  <div>
                    <label className="text-xs text-gray-500 font-medium">
                      Return Time
                    </label>
                    <Select
  value={returnTime}
  onValueChange={(value) => setReturnTime(value)}
>
<SelectTrigger className="mt-1 h-11 w-full border border-gray-200 rounded-md bg-white px-3 font-semibold text-sm focus:ring-0 focus:border-primary">
    <SelectValue placeholder="Time" />
  </SelectTrigger>

  <SelectContent>
    {generateTimeOptions(returnDate).map((t) => (
      <SelectItem
        key={t}
        value={t}
         className="z-[9999] bg-white border border-gray-200 shadow-lg rounded-md"
      >
        {formatTo12Hour(t)}
      </SelectItem>
    ))}
  </SelectContent>
</Select>
                  </div>
                )}

                {/* MONTHS */}
                {rentalType === "monthly" && (
                  <div>
                    <label className="text-xs text-gray-500 font-medium">
                      Months
                    </label>
                   <Select
  value={months}
  onValueChange={(value) => setMonths(value)}
>
<SelectTrigger className="mt-1 h-11 w-full border border-gray-200 rounded-md bg-white px-3 font-semibold text-sm focus:ring-0 focus:border-primary">
    <SelectValue placeholder="Select" />
  </SelectTrigger>

  <SelectContent>
    {[1, 2, 3, 6, 12].map((m) => (
      <SelectItem
        key={m}
        value={String(m)}
         className="z-[9999] bg-white border border-gray-200 shadow-lg rounded-md"
      >
        {m} month{m > 1 ? "s" : ""}
      </SelectItem>
    ))}
  </SelectContent>
</Select>
                  </div>
                )}
              </div>

              {/* BUTTON */}
              <div className="lg:ml-4 w-full lg:w-auto">
                <button
                  onClick={handleSearch}
                  className="w-full lg:w-auto bg-primary text-white px-8 py-3 rounded-lg font-semibold hover:bg-primary transition"
                >
                  Search
                </button>
              </div>
            </div>

            {/* ERROR */}
            {error && (
              <p className="text-red-500 text-sm mt-4">{error}</p>
            )}
          </div>
        </div>
      </section>

      {/* CITY MODAL */}
      <CitySelectModal
        open={openCity}
        onClose={() => setOpenCity(false)}
      />
    </>
  );
}