// components/FleetClient.tsx

"use client";

import { useEffect, useState, useMemo } from "react";
import Navbar from "@/components/common/Navbar";
import { getVehiclesByCity } from "@/api/bookingApi";
import { useAppSelector } from "@/store/hooks";
import Image from "next/image";
import { Star, Fuel, Gauge, Settings, Zap, Weight, Cog } from "lucide-react";
import { useRouter } from "next/navigation";
import CitySelectModal from "@/components/common/CitySelectModal";
import Script from "next/script";


const API_BASE = process.env.NEXT_PUBLIC_API_URL;

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

  const ampm = hours >= 12 ? "PM" : "AM";
  hours = hours % 12 || 12;

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

const getNextTimeSlots = () => {
  const now = new Date();
  const slots: string[] = [];

  let minutes = now.getMinutes();
  let roundedMinutes = minutes < 30 ? 30 : 60;

  let start = new Date(now);
  start.setMinutes(roundedMinutes);
  start.setSeconds(0);

  if (roundedMinutes === 60) {
    start.setHours(start.getHours() + 1);
    start.setMinutes(0);
  }

  for (let i = 0; i < 6; i++) {
    const h = start.getHours();
    const m = start.getMinutes();

    const ampm = h >= 12 ? "PM" : "AM";
    const hour12 = h % 12 || 12;

    slots.push(
      `${String(hour12).padStart(2, "0")}:${String(m).padStart(2, "0")} ${ampm}`
    );

    start.setMinutes(start.getMinutes() + 30);
  }

  return slots;
};


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 formatISO = (date: string, time: string) => {
  if (!date || !time) return "";
  return `${date}T${time}:00`;
};

export default function FleetPage({
  searchParams,
  params,
}: {
  searchParams: any;
  params: { city: string; category: string };
}) {

const fromSlug = (slug: string) => slug.replace(/-/g, " ");

const urlCity = params?.city ? fromSlug(params.city) : null;


const { vehicle } = useAppSelector((state) => state.booking);
  const city = urlCity || useAppSelector((state) => state.booking.city);

  const [vehicles, setVehicles] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  const [filters, setFilters] = useState<Record<string, string[]>>({});
const [allVehicles, setAllVehicles] = useState<any[]>([]);

const rangeSteps = ["SMALL", "MEDIUM", "LARGE"] as const;
const [range, setRange] = useState<typeof rangeSteps[number]>("SMALL");


  const router = useRouter();

const [showDateTimePopup, setShowDateTimePopup] = useState(false);
const [showCityError, setShowCityError] = useState(false);
const [openCity, setOpenCity] = useState(false);

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

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

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]?.slice(0, 5) || ""
);

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

const [selectedVehicle, setSelectedVehicle] = useState<any>(null);

const category = vehicle === "bike" ? "two-wheeler" : "four-wheeler";

const [openDropdown, setOpenDropdown] = useState(false);
const [selectedOption, setSelectedOption] = useState("");

const dynamicFilters = useMemo(() => {
  const map: any = {
    BRAND: { key: "make_name", values: new Set() },
    MODEL: { key: "model_name", values: new Set() },
    TYPE: { key: "category", values: new Set() },
    ENGINE: { key: "fueltype", values: new Set() },
  };

  allVehicles.forEach((v: any) => {
    const attr = v.attributes || {};

    if (v.make_name) map.BRAND.values.add(v.make_name);
    if (v.model_name) map.MODEL.values.add(v.model_name);
    if (attr.category) map.TYPE.values.add(attr.category);
    if (attr.fueltype) map.ENGINE.values.add(attr.fueltype);
  });

  return Object.entries(map).map(([label, data]: any) => ({
    label,
    key: data.key,
    options: Array.from(data.values),
  }));
}, [allVehicles]);


const handleFilterChange = (key: string, value: string) => {
  setFilters((prev) => {
    const current = prev[key] || [];

    if (current.includes(value)) {
      return { ...prev, [key]: current.filter((v) => v !== value) };
    } else {
      return { ...prev, [key]: [...current, value] };
    }
  });
};


const handleRentNow = (item: any) => {
  if (!city) {
    setShowCityError(true);
    return;
  }

  // ✅ STORE SELECTED VEHICLE
  setSelectedVehicle(item);

  setShowDateTimePopup(true);
};
  

  useEffect(() => {
    if (!city) return;

    const fetchVehicles = async () => {
      try {
        setLoading(true);
       const data = await getVehiclesByCity(city, category);

const list = data?.submodels || [];

setVehicles(list);
setAllVehicles(list); // 👈 IMPORTANT (for filters)
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchVehicles();
 }, [city, category]);


useEffect(() => {
  if (!showDateTimePopup) return;

  setRentalType(searchParams?.rental_type || "daily");

  setPickupDate(searchParams?.from?.split("T")[0] || "");
  setPickupTime(searchParams?.from?.split("T")[1]?.slice(0, 5) || "");

  setReturnDate(searchParams?.to?.split("T")[0] || "");
  setReturnTime(searchParams?.to?.split("T")[1]?.slice(0, 5) || "");

  setMonths(searchParams?.months || "");
}, [showDateTimePopup]);


useEffect(() => {
  if (!allVehicles.length) return;

  let filtered = [...allVehicles];

  Object.entries(filters).forEach(([key, values]) => {
    if (!values.length) return;

    filtered = filtered.filter((v: any) => {
      if (key === "category" || key === "fueltype") {
        return values.includes(v.attributes?.[key]);
      }

      return values.includes(v[key]);
    });
  });

  setVehicles(filtered);
}, [filters, allVehicles]);

const getMinPrice = (v: any) => {
  const size =
    range === "SMALL" ? "S" : range === "MEDIUM" ? "M" : "L";

  let min = Infinity;

  v.plans?.forEach((plan: any) => {
    if (plan.size === size && plan.price < min) {
      min = plan.price;
    }
  });

  return min === Infinity ? v.starting_price : min;
};



const dropdownOptions = useMemo(() => {
  if (rentalType === "daily") {
    return [
      "1 Day",
      "2 Days",
      "3 Days",
      "4 Days",
      "7 Days",
      "10 Days",
    ];
  }

  return [
    "1 Month",
    "2 Months",
    "3 Months",
    "6 Months",
    "12 Months",
    "24 Months",
  ];
}, [rentalType]);

  return (
    <>

    <Script
  id="fleet-vehicle-schema"
  type="application/ld+json"
  dangerouslySetInnerHTML={{
    __html: JSON.stringify({
      "@context": "https://schema.org",

      "@type": "ItemList",

      name: `Ridoo ${vehicle === "bike" ? "Bike" : "Car"} Fleet in ${city}`,

      itemListElement: vehicles.map((item: any, index: number) => ({

        "@type": "ListItem",

        position: index + 1,

        item: {
          "@type": "Product",

          name: `${item.make_name} ${item.submodel_name}`,

          image: item.image?.startsWith("http")
            ? item.image
            : `https://ridoo.co.in${item.image}`,

          description: `Self drive ${item.make_name} ${item.submodel_name} available for rent in ${city}.`,

          brand: {
            "@type": "Brand",
            name: item.make_name || "Ridoo",
          },

         aggregateRating: {
  "@type": "AggregateRating",

  ratingValue: String(
    item.rating_value || 4.5
  ),

  reviewCount: String(
    item.rating_count || 10
  ),
},

          offers: {
            "@type": "Offer",

            priceCurrency: "INR",

            price: getMinPrice(item),

            availability: "https://schema.org/InStock",

            url: `https://ridoo.co.in/${params.city}/${params.category}/fleet`,
          },
        },
      })),
    }),
  }}
/>


<Script
  id="breadcrumb-schema"
  type="application/ld+json"
  dangerouslySetInnerHTML={{
    __html: JSON.stringify({
      "@context": "https://schema.org",

      "@type": "BreadcrumbList",

      itemListElement: [
        {
          "@type": "ListItem",
          position: 1,
          name: "Home",
          item: "https://ridoo.co.in",
        },
        {
          "@type": "ListItem",
          position: 2,
          name: city,
          item: `https://ridoo.co.in/${params.city}`,
        },
        {
          "@type": "ListItem",
          position: 3,
          name: vehicle === "bike" ? "Bike Rentals" : "Car Rentals",
          item: `https://ridoo.co.in/${params.city}/${params.category}`,
        },
        {
          "@type": "ListItem",
          position: 4,
          name: "Fleet",
          item: `https://ridoo.co.in/${params.city}/${params.category}/fleet`,
        },
      ],
    }),
  }}
/>



      {/* <Navbar vehicle={vehicle} setVehicle={setVehicle} /> */}

      <div className="px-4 md:px-10 py-8 md:py-12 bg-[#f7f7f7] min-h-screen mt-2">

        {/* HEADER */}
        <h1 className="text-3xl md:text-5xl font-bold">
          Our Fleet in{" "}
          <span className="text-primary relative">
            {city || "Indore"}
            <span className="absolute left-0 -bottom-2 w-full h-1 bg-primary"></span>
          </span>
        </h1>

        <p className="text-sm text-gray-500 mt-4 max-w-md">
          *Prices exclude taxes and fuel. Images are for representation purposes only, and the actual color may vary.
        </p>

        {/* TOP CONTROLS */}
        <div className="flex flex-col md:flex-row md:items-center justify-between mt-6 gap-4">

          {/* DROPDOWN */}
          {/* <div className="relative w-fit">
  <div
    onClick={() => setOpenDropdown(!openDropdown)}
    className="border px-3 py-2 rounded-md text-sm w-[200px]"
  >
    {selectedOption || "Select"}
  </div>

  {openDropdown && (
    <div className="absolute mt-1 w-full bg-white border rounded-md shadow z-10">
      {dropdownOptions.map((opt, i) => (
        <div
          key={i}
          onClick={() => {
            setSelectedOption(opt);
            setOpenDropdown(false);
          }}
          className="px-3 py-2 text-sm cursor-pointer hover:bg-primary hover:text-white"
        >
          {opt}
        </div>
      ))}
    </div>
  )}
</div> */}

          {/* TOGGLE */}
          {/* <div className="flex bg-orange-100 rounded-full p-1">
  <button
    onClick={() => setRentalType("daily")}
    className={`px-5 py-1 text-sm rounded-full ${
      rentalType === "daily"
        ? "bg-primary text-white"
        : "text-gray-600"
    }`}
  >
    Hourly
  </button>

  <button
    onClick={() => setRentalType("subscription")}
    className={`px-5 py-1 text-sm rounded-full ${
      rentalType === "subscription"
        ? "bg-primary text-white"
        : "text-gray-600"
    }`}
  >
    Subscription
  </button>
</div> */}


        </div>

        {/* MAIN */}
        <div className="flex flex-col lg:flex-row gap-6 mt-8">

          {/* SIDEBAR */}
          <div className="w-full lg:w-[260px] bg-white border border-orange-200 rounded-xl p-5 space-y-5">

  {/* RANGE */}
  {/* <div>
    <p className="text-center font-semibold mb-2">
  {range === "SMALL" ? "120KM" : range === "MEDIUM" ? "150KM" : "200KM"}
</p>

<input
  type="range"
  min={0}
  max={2}
  value={rangeSteps.indexOf(range)}
  onChange={(e) =>
    setRange(rangeSteps[Number(e.target.value)])
  }
  className="w-full accent-yellow-500"
/>

    <div className="flex justify-between text-[10px] text-gray-400 mt-1">
      <span>SMALL</span>
      <span>MEDIUM</span>
      <span>LARGE</span>
    </div>
  </div> */}

  {/* FILTERS */}
  {dynamicFilters.map((filter: any) => (
  <div key={filter.label} className="border-t pt-4">
    
    <p className="text-sm font-semibold mb-2">{filter.label}</p>

    <div className="space-y-2">
      {filter.options.map((opt: string) => (
        <label key={opt} className="flex items-center gap-2 text-xs">
          <input
            type="checkbox"
            checked={(filters[filter.key] || []).includes(opt)}
            onChange={() => handleFilterChange(filter.key, opt)}
          />
          {opt}
        </label>
      ))}
    </div>

  </div>
))}
</div>

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

      {loading && (
  <div className="col-span-full h-[300px] flex flex-col items-center justify-center gap-3">
    
    <Image
      src="/profile.gif"
      alt="Loading..."
      width={80}
      height={80}
      className="object-contain"
    />

    <p className="text-sm text-gray-500">Loading vehicles...</p>
  </div>
)}

            {!loading && vehicles.length === 0 ? (
  <div className="col-span-full text-center py-20 text-gray-400 text-lg">
    No vehicles available at this moment
  </div>
) : (
  vehicles.map((item: any, i) => {
    const data = {
      name: `${item.make_name} ${item.submodel_name}`,
      make_name: item.make_name,
      model_name: item.model_name,
      image: item.image || "/b1.png",
      price: item.starting_price,
      attrs: item.attributes || {},
    };

    return (
      <div
        key={i}
          className="rounded-2xl shadow-sm flex flex-col overflow-hidden 
     bg-white hover:shadow-xl cursor-pointer"
        onClick={() => handleRentNow(item)}
      >
        {/* CONTENT */}
        <div className="p-3 sm:p-4 flex flex-col">

          {/* IMAGE */}
          <div className="h-28 sm:h-32 flex items-center justify-center mb-2">
            <Image
              src={`${API_BASE}${data.image}`}
              alt={data.name}
              width={160}
              height={100}
              className="object-contain max-h-full max-w-full"
            />
          </div>

          {/* TITLE */}
          <h3 className="text-sm font-semibold text-center mt-1">
            {data.name}
          </h3>

          {/* RATING */}
          <div className="flex items-center justify-center gap-1 mt-1 text-xs text-gray-500">
            <Star className="text-yellow-400 fill-yellow-400" size={14} />
            <span className="font-medium text-gray-700">4.9</span>
            <span>(236 reviews)</span>
          </div>

          {/* SPECS */}
          <div className="grid grid-cols-2 gap-y-3 gap-x-4 mt-4 text-xs text-gray-600 place-items-center">
            <Spec icon={<Fuel size={14} className="text-primary" />} text={data.attrs?.fueltype} />
            <Spec icon={<Gauge size={14} className="text-primary" />} text={`${data.attrs?.mileage || "N/A"} KMPL`} />
            <Spec icon={<Zap size={14} className="text-primary" />} text={`${data.attrs?.power || "N/A"} BHP`} />
            <Spec icon={<Settings size={14} className="text-primary" />} text={`${data.attrs?.torque || "N/A"} Nm`} />
            <Spec icon={<Weight size={14} className="text-primary" />} text={`${data.attrs?.weight || "N/A"} Kg`} />
            <Spec icon={<Cog size={14} className="text-primary" />} text={data.attrs?.transmission} />
          </div>

          {/* PRICE */}
          <div className="pt-4 flex justify-between ml-3 mr-3">
            <p className="text-2xs text-gray-400">
              Price starting @
            </p>

            <p className="text-center font-semibold text-gray-900 mt-1">
              ₹ {getMinPrice(item)}
            </p>
          </div>
        </div>

        {/* BUTTON */}
        <button
          onClick={() => handleRentNow(item)}
          className="w-full bg-primary text-white text-sm py-3 font-medium rounded-b-2xl flex items-center justify-center gap-2"
        >
          Rent Now →
        </button>
      </div>
    );
  })
)}
          </div>
        </div>
      </div>

      <CitySelectModal
  open={openCity}
  onClose={() => setOpenCity(false)}
/>

{showCityError && (
  <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
    <div className="bg-white p-6 rounded-xl w-[300px] text-center space-y-4">
      <h2 className="text-lg font-semibold">Select City</h2>

      <p className="text-sm text-gray-500">
        Please select your city before booking
      </p>

      <div className="flex gap-3">
        <button
          onClick={() => setShowCityError(false)}
          className="flex-1 border py-2 rounded-lg"
        >
          Cancel
        </button>

        <button
          onClick={() => {
            setShowCityError(false);
            setOpenCity(true);
          }}
          className="flex-1 bg-primary text-white py-2 rounded-lg"
        >
          Select City
        </button>
      </div>
    </div>
  </div>
)}

{showDateTimePopup && (
  <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
   onClick={() => setShowDateTimePopup(false)}
  >
     <div className="bg-white p-6 rounded-xl w-[95%] max-w-6xl xl:max-w-7xl"
       onClick={(e) => e.stopPropagation()}
     >

      {/* HEADER */}
      <h2 className="text-lg font-semibold mb-5">
        Select Date & Time
      </h2>

      {/* MAIN ROW */}
      <div className="flex flex-col lg:flex-row lg:items-center gap-6">

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

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

        {/* DIVIDER */}
        <div className="hidden lg:block h-12 w-px bg-gray-300" />

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

          {/* PICKUP DATE */}
          <div>
            <label className="text-xs text-gray-500">Pickup Date</label>
            <input
              type="date"
              value={pickupDate}
              min={new Date().toISOString().split("T")[0]}
              onChange={(e) => setPickupDate(e.target.value)}
              className="w-full border rounded-md px-3 py-2 mt-1 text-sm cursor-pointer"
            />
          </div>

          {/* PICKUP TIME */}
          <div>
            <label className="text-xs text-gray-500">Pickup Time</label>
            <select
              value={pickupTime}
              onChange={(e) => setPickupTime(e.target.value)}
              className="w-full border rounded-md px-3 py-2 mt-1 text-sm cursor-pointer"
            >
              <option value="">Select Time</option>
              {generateTimeOptions(pickupDate).map((t) => (
  <option key={t} value={t}>
    {formatTo12Hour(t)}
  </option>
))}
            </select>
          </div>


          {/* DAILY FLOW */}
          {rentalType === "daily" && (
  <>
    <div>
      <label className="text-xs text-gray-500">Return Date</label>
      <input
        type="date"
        value={returnDate}
        min={pickupDate}
        onChange={(e) => setReturnDate(e.target.value)}
        className="w-full border rounded-md px-3 py-2 mt-1 text-sm cursor-pointer"
      />
    </div>

    <div>
      <label className="text-xs text-gray-500">Return Time</label>
      <select
        value={returnTime}
        onChange={(e) => setReturnTime(e.target.value)}
        className="w-full border rounded-md px-3 py-2 mt-1 text-sm cursor-pointer"
      >
        <option value="">Select Time</option>
        {generateTimeOptions(returnDate).map((t) => (
  <option key={t} value={t}>
    {formatTo12Hour(t)}
  </option>
))}
      </select>
    </div>
  </>
)}

          {/* MONTHLY FLOW */}
          {rentalType === "monthly" && (
            <div>
              <label className="text-xs text-gray-500">Months</label>
              <select
                value={months}
                onChange={(e) => setMonths(e.target.value)}
                className="w-full border rounded-md px-3 py-2 mt-1 text-sm cursor-pointer"
              >
                <option value="">Select</option>
                {[1, 2, 3, 6, 12].map((m) => (
                  <option key={m} value={m}>
                    {m} month{m > 1 ? "s" : ""}
                  </option>
                ))}
              </select>
            </div>
          )}
        </div>

        {/* BUTTON */}
        <div className="lg:w-auto w-full">
          <button
            onClick={() => {
              if (!pickupDate || !pickupTime) {
                setError("Select pickup date & time");
                return;
              }

             if (rentalType === "daily") {
                if (!returnDate || !returnTime) {
                  setError("Select return date & time");
                  return;
                }

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

                const diff =
                  (end.getTime() - start.getTime()) /
                  (1000 * 60 * 60);

                if (diff < 1) {
                  setError("Minimum 1 hour booking required");
                  return;
                }
              }

              if (rentalType === "monthly" && !months) {
                setError("Select months");
                return;
              }

              setError("");
              setShowDateTimePopup(false);

             const make = selectedVehicle?.make_name;
const model = selectedVehicle?.model_name;

const fromISO = formatISO(pickupDate, pickupTime);
const toISO =
  rentalType === "daily"
    ? formatISO(returnDate, returnTime)
    : "";

router.push(
  `/vehicles?city=${city}&rental_type=${rentalType}&from=${fromISO}&to=${toISO}&months=${months || ""}&make=${encodeURIComponent(make || "")}&model=${encodeURIComponent(model || "")}`
);
            }}
            className="w-full bg-primary text-white px-6 py-2 rounded-lg mt-2 lg:mt-0"
          >
            Continue
          </button>
        </div>
      </div>

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

     
    </div>
  </div>
)}


    </>
  );
}

const Spec = ({ icon, text }: any) => (
  <div className="flex items-center justify-center gap-1">
    {icon}
    <span>{text || "N/A"}</span>
  </div>
);