// components/home/PopularBikes.tsx

"use client";

import Image from "next/image";
import { Star } from "lucide-react";
import type { VehicleType } from "@/types/booking";
import { useAppSelector } from "@/store/hooks";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import CitySelectModal from "../common/CitySelectModal";
import { getVehiclesByCity } from "@/api/bookingApi";
import {
  Fuel,
  Gauge,
  Zap,
  Settings,
  Weight,
  Cog,
} from "lucide-react";
import Script from "next/script";


interface PopularProps {
  vehicle: VehicleType;
}

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 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`; // ✅ FIXED
};

  export default function PopularBikes({
  vehicle,
  searchParams,
}: PopularProps & { searchParams: any }) {


const isBike = vehicle === "bike"; // ✅ restore original logic

const category = isBike ? "two-wheeler" : "four-wheeler";
  const { user, access_token } = useAppSelector((state) => state.auth);
  const [showLoginPopup, setShowLoginPopup] = useState(false);
const [showDateTimePopup, setShowDateTimePopup] = 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 [showCityError, setShowCityError] = useState(false);
const [openCity, setOpenCity] = useState(false);
  // const [cityModalOpen, setCityModalOpen] = useState(false);

const router = useRouter();

const { city } = useAppSelector((state) => state.booking);
const [vehiclesData, setVehiclesData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);

// const vehicles = vehiclesData.map((item: any) => ({
//   name: `${item.make_name} ${item.submodel_name}`,
//   make_name: item.make_name,        // ✅ ADD
//   model_name: item.model_name,      // ✅ ADD
//   image: item.image || "/b1.png",
//   rating: "4.5",
//   reviews: "100",
//   price: item.starting_price || 0,
//   attrs: item.attributes || {},
// }));


const vehicles = vehiclesData.map((item: any) => {
  const firstVehicle =
    item?.pickup_options?.[0]?.vehicles?.[0];

  const ratingData = firstVehicle?.average_rating;

  return {
    name: `${item.make_name} ${item.submodel_name}`,

    make_name: item.make_name,

    model_name: item.model_name,

    image: item.image || "/b1.png",

    rating:
      ratingData?.rating_value && ratingData.rating_count > 0
        ? ratingData.rating_value
        : null,

    reviews:
      ratingData?.rating_count || 0,

    price: item.starting_price || 0,

    attrs: item.attributes || {},
  };
});


      useEffect(() => {
  if (!city) return;

  const fetchVehicles = async () => {
    try {
      setLoading(true);

      const data = await getVehiclesByCity(city, category);

      // handle different API shapes safely
      setVehiclesData(data?.submodels || []);

    } catch (err) {
      console.error("Vehicle fetch failed:", 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]);


const [selectedVehicle, setSelectedVehicle] = useState<any>(null);

const handleRentNow = (item: any) => {
  if (!city) {
    setShowCityError(true);
    return;
  }

  // ✅ STORE SELECTED VEHICLE
  setSelectedVehicle(item);

  setShowDateTimePopup(true);
};

const carImages = [
  "/c1.png",
  "/c2.png",
  "/c3.png",
  "/c4.png",
];

const dummyCars = carImages.map((img) => ({
  name: "Car",
  image: img,
  rating: "-",
  reviews: "-",
  price: "-",
  attrs: {},
  isDummy: true,
}));

const displayVehicles = vehicles.slice(0, 4);
  

  return (
   
<>

<Script
  id="vehicle-schema"
  type="application/ld+json"
  dangerouslySetInnerHTML={{
    __html: JSON.stringify({
      "@context": "https://schema.org",

      "@type": "ItemList",

      itemListElement: vehicles.map(
        (item: any, index: number) => ({
          "@type": "ListItem",

          position: index + 1,

          item: {
            "@type": "Product",

            name: item.name,

            image: item.image?.startsWith("http")
              ? item.image
              : `https://ridoo.co.in${item.image}`,

            description: `Self drive ${item.name} available for rent.`,

            brand: {
              "@type": "Brand",

              name: item.make_name || "Ridoo",
            },

            // ✅ ADD ONLY IF REVIEWS EXIST
            ...(item.rating &&
            item.reviews > 0
              ? {
                  aggregateRating: {
                    "@type": "AggregateRating",

                    ratingValue: String(
                      item.rating
                    ),

                    reviewCount: String(
                      item.reviews
                    ),
                  },
                }
              : {}),

            offers: {
              "@type": "Offer",

              priceCurrency: "INR",

              price: String(
                item.price || 499
              ),

              availability:
                "https://schema.org/InStock",

              url: `https://ridoo.co.in/${city
                ?.toLowerCase()
                ?.replace(/\s+/g, "-")}/${
                isBike
                  ? "bike-rentals"
                  : "car-rentals"
              }`,
            },
          },
        })
      ),
    }),
  }}
/>

    <section className="max-w-7xl mx-auto px-4 sm:px-6 md:px-10 py-14 sm:py-20">

      
      
  {/* Heading */}
  <h2 className="text-2xl sm:text-3xl md:text-4xl font-bold text-gray-900 leading-snug">
    Most popular{" "}
    <span className="relative text-primary mr-2 sm:mr-3">
      {isBike ? "Bike" : "Car"}
      <svg
        className="absolute left-0 -bottom-2 sm:-bottom-3 w-full"
        height="12"
        viewBox="0 0 168 12"
        fill="none"
      >
        <path
          d="M2 10C50 2 120 2 166 10"
          stroke="#FFCB20"
          strokeWidth="4"
          strokeLinecap="round"
        />
      </svg>
    </span>
    rental deals
  </h2>




  {/* Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-[repeat(4,1fr)_auto] gap-6 sm:gap-8 mt-10 sm:mt-12">
       {loading && (
  <p className="text-center text-gray-500 mt-10">
    Loading vehicles...
  </p>
)}

{!loading && displayVehicles.length === 0 && (
  <p className="text-center text-gray-400 mt-10">
    No vehicles available
  </p>
)}

    {displayVehicles.map((item, index) => (
  <div
    key={index}
className={`rounded-2xl shadow-sm flex flex-col h-full overflow-hidden
 bg-white hover:shadow-xl cursor-pointer
`}
  onClick={() => handleRentNow(item)}
  >
    {/* CONTENT */}
    <div className="p-3 sm:p-4 flex flex-col h-full">

      {/* IMAGE */}
      <div className="h-28 sm:h-32 flex items-center justify-center mb-2">
        <Image
          src={`${process.env.NEXT_PUBLIC_API_URL}${item.image}`}
          alt={item.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">
  { item.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">{item.rating}</span>
    <span>({item.reviews} 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={item.attrs?.fueltype}
  />

  <Spec
    icon={<Gauge size={14} className="text-primary" />}
    text={`${item.attrs?.mileage || "N/A"} KMPL`}
  />

  <Spec
    icon={<Zap size={14} className="text-primary" />}
    text={`${item.attrs?.power || "N/A"} BHP`}
  />

  <Spec
    icon={<Settings size={14} className="text-primary" />}
    text={`${item.attrs?.torque || "N/A"} Nm`}
  />

  <Spec
    icon={<Weight size={14} className="text-primary" />}
    text={`${item.attrs?.weight || "N/A"} Kg`}
  />

  <Spec
    icon={<Cog size={14} className="text-primary" />}
    text={item.attrs?.transmission}
  />

</div>
      

      {/* FOOTER TEXT */}
      <div className="mt-auto pt-4 flex justify-between ml-3 mr-3">
  <p className="text-2xs text-gray-400">Price starting @</p>

  <p className="font-semibold mt-1">
    { `₹ ${item.price}` }
  </p>
</div>

    </div>

    {/* BUTTON (ATTACHED TO BOTTOM) */}
    <button
  onClick={() => handleRentNow(item)}
  disabled={!isBike}
  className={`w-full text-sm py-3 font-medium rounded-b-2xl flex items-center justify-center gap-2
    bg-primary text-white hover:scale-[1.02] cursor-pointer
  `}
>
  {"Rent Now →"}
</button>
  </div>
))}

  {isBike && vehicles.length > 4 && (
    <div
  onClick={() => {
  const selectedCity = localStorage.getItem("selectedCity");
  const selectedVehicle = localStorage.getItem("selectedVehicle");

  if (selectedCity && selectedVehicle) {
    const category =
      selectedVehicle === "bike" ? "bike-rentals" : "car-rentals";

    const slug = selectedCity.trim().replace(/\s+/g, "-");

    router.push(`/${slug.toLowerCase()}/${category}/fleet`);
  } else {
    router.push("/");
  }
}}
  className="hidden lg:flex flex-col items-center justify-center cursor-pointer group"
>
  <div className="bg-primary text-white w-12 h-12 rounded-full flex items-center justify-center text-xl group-hover:scale-110 transition">
    →
  </div>
  <p className="text-sm mt-2 text-gray-600 group-hover:text-primary">
    See All
  </p>
</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>
)}
</section>

</>
  );
}


const Spec = ({ icon, text }: any) => (
  <div className="flex items-center justify-center gap-1">
    {icon}
    <span>{text || "N/A"}</span>
  </div>
);