"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  getAccessoriesByPickupPoint,
  createCustomerOrder,
} from "@/api/bookingApi";
import {
  ChevronLeft,
  ChevronDown,
  Minus,
  Plus,
  Bike,
  Tags,
  Layers,
  Settings,
  Grid,
} from "lucide-react";

import Image from "next/image";


export default function AccessoriesPage({
  initialAccessories,
  bookingData,
}: {
  initialAccessories: any[];
  bookingData: any;
}) {
  const router = useRouter();

  const [filters, setFilters] = useState<Record<string, string[]>>({});
const [openFilter, setOpenFilter] = useState<string | null>(null);

  /* ---------------- GET DATA ---------------- */

  if (!bookingData) {
  return <div>Something went wrong</div>;
}

const { vehicle, selectedPlan, pickup_point_id, from, to } = bookingData;

  /* ---------------- STATE ---------------- */
  const [allAccessories, setAllAccessories] = useState(initialAccessories);
const [accessories, setAccessories] = useState(initialAccessories);
  const [cart, setCart] = useState<any>({});

  /* ---------------- API ---------------- */




// useEffect(() => {
//   if (!pickup_point_id) return;

//   getAccessoriesByPickupPoint(
//     pickup_point_id,
//     from,   // ✅ added
//     to,     // ✅ added
//     {}
//   )
//     .then((res) => {
//       setAllAccessories(res.accessories || []);
//     })
//     .catch(console.error);
// }, [pickup_point_id, from, to]);

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

  getAccessoriesByPickupPoint(
    pickup_point_id,
    from,   // ✅ added
    to,     // ✅ added
    Object.fromEntries(
      Object.entries(filters).map(([key, values]) => [
        key,
        values.join(","),
      ])
    )
  )
    .then((res) => {
      setAccessories(res.accessories || []);
    })
    .catch(console.error);
}, [pickup_point_id, filters, from, to]);


const dynamicFilters = useMemo(() => {
  const map: any = {
    COLOUR: { key: "colour", values: new Set() },
    MODEL: { key: "model", values: new Set() },
    TYPE: { key: "category", values: new Set() },
  };

  allAccessories.forEach((a: any) => {
    if (a.colour) map.COLOUR.values.add(a.colour);
    if (a.model) map.MODEL.values.add(a.model);
    if (a.category) map.TYPE.values.add(a.category);
  });

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


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

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

function FilterItem({ title, isOpen, onClick, children }: any) {
  return (
    <div className="border-b last:border-none">
      <button
        onClick={onClick}
        className="w-full flex justify-between px-4 py-4 text-sm font-semibold"
      >
        {title}
        <ChevronDown
          size={16}
          className={isOpen ? "rotate-180" : ""}
        />
      </button>

      {isOpen && children}
    </div>
  );
}

  /* ---------------- CART ---------------- */


const updateQty = (id: string, delta: number) => {
  const accessory = accessories.find(a => a.accessory_id === id);

  if (!accessory) return;

  const maxQty = accessory.available_quantity || 0;

  setCart((prev: any) => {
    const current = prev[id] || 0;

    // ❌ prevent increment above available_quantity
    if (delta > 0 && current >= maxQty) return prev;

    const next = Math.max(current + delta, 0);

    if (next === 0) {
      const copy = { ...prev };
      delete copy[id];
      return copy;
    }

    return { ...prev, [id]: next };
  });
};

  /* ---------------- PRICE ---------------- */
  const accessoriesTotal = useMemo(() => {
    return accessories.reduce((sum, a: any) => {
      const qty = cart[a.accessory_id] || 0;
      return sum + qty * a.price;
    }, 0);
  }, [cart, accessories]);

  /* ---------------- PROCEED ---------------- */



  const handleProceed = async () => {
  try {

    const payload = {
  // customer_id: data.booking.customer_id,
  submodel_id: bookingData.submodel.submodel_id,
  pickup_point_id,
  package_size: bookingData.range,
  rental_type: selectedPlan.type,

  // ✅ FIX HERE
  from_date: bookingData.from,
  to_date: bookingData.to,

  accessories: Object.entries(cart).map(([id, quantity]) => ({
    accessory_id: id,
    quantity,
  })),
};

    const res = await createCustomerOrder(payload);

    router.push(
      `/summary?data=${encodeURIComponent(
        JSON.stringify({
          order_id: res.order_id,
          booking_id: res.booking_id,
          booking: bookingData,
        })
      )}`
    );
  } catch (err) {
    console.error(err);
  }
};


  /* ---------------- UI ---------------- */
  return (
    <div className="min-h-screen bg-[#fafafa]">

      {/* HEADER */}
      <div className="sticky top-[80px] z-40 bg-primary px-4 md:px-10 py-5 md:py-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        
        <div className="flex items-center gap-4 text-white">
          <button
            onClick={() => router.back()}
            className="bg-white/20 p-2 rounded-lg"
          >
            <ChevronLeft />
          </button>

          <div>
            <div className="text-sm md:text-lg">Current selection</div>
            <div className="text-lg md:text-2xl font-semibold">
              {vehicle.make_name} {vehicle.submodel_name}
            </div>
            <div className="text-xs md:text-sm mt-1">
              Accessories ₹ {accessoriesTotal.toFixed(2)}
            </div>
          </div>
        </div>

        <button
          onClick={handleProceed}
          className="bg-white text-primary px-6 md:px-10 py-2 md:py-3 rounded-lg font-semibold shadow"
        >
          Proceed To Book
        </button>
      </div>

      {/* BODY */}
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-6 md:py-10 grid grid-cols-1 lg:grid-cols-4 gap-6 md:gap-10">

        {/* FILTERS (hidden on mobile) */}
        <div className="hidden lg:block">
  <div className="bg-white border border-orange-200 rounded-2xl overflow-hidden">

    <FilterItem
  title="PRICE"
  isOpen={openFilter === "PRICE"}
  onClick={() =>
    setOpenFilter(openFilter === "PRICE" ? null : "PRICE")
  }
>
  <div className="px-4 pb-4">

    {/* ✅ COUNT + CLEAR */}
    <div className="flex justify-between items-center pb-2 text-xs">
      <span className="text-gray-500">
        {(filters.price_min || filters.price_max) ? "1 selected" : "0 selected"}
      </span>

      {(filters.price_min || filters.price_max) && (
        <button
          className="text-primary"
          onClick={() =>
            setFilters((prev) => {
              const updated = { ...prev };
              delete updated.price_min;
              delete updated.price_max;
              return updated;
            })
          }
        >
          Clear
        </button>
      )}
    </div>

    {/* MIN PRICE */}
    <input
      type="number"
      placeholder="Min Price"
      className="w-full border rounded px-2 py-1 text-xs mb-2"
      value={filters.price_min?.[0] || ""}
      onChange={(e) =>
        setFilters((prev) => ({
          ...prev,
          price_min: [e.target.value],
        }))
      }
    />

    {/* MAX PRICE */}
    <input
      type="number"
      placeholder="Max Price"
      className="w-full border rounded px-2 py-1 text-xs"
      value={filters.price_max?.[0] || ""}
      onChange={(e) =>
        setFilters((prev) => ({
          ...prev,
          price_max: [e.target.value],
        }))
      }
    />

  </div>
</FilterItem>

    {dynamicFilters.map((filter: any) => (
      <FilterItem
        key={filter.label}
        title={filter.label}
        isOpen={openFilter === filter.label}
        onClick={() =>
          setOpenFilter(
            openFilter === filter.label ? null : filter.label
          )
        }
      >
        <div className="px-4 pb-4">

  {/* ✅ SELECTED COUNT + CLEAR */}
  <div className="flex justify-between items-center pb-2 text-xs">
    <span className="text-gray-500">
      {(filters[filter.key] || []).length} selected
    </span>

    {filters[filter.key]?.length > 0 && (
      <button
        className="text-primary"
        onClick={() =>
          setFilters((prev) => {
            const updated = { ...prev };
            delete updated[filter.key];
            return updated;
          })
        }
      >
        Clear
      </button>
    )}
  </div>

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

</div>
      </FilterItem>
    ))}

  </div>
</div>

        {/* ACCESSORIES */}
        <div className="lg:col-span-3 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-5 md:gap-10">

            {accessories.map((a: any) => {
  const qty = cart[a.accessory_id] || 0;
  const isAvailable = a.available_quantity > 0;
  const isMaxReached = qty >= a.available_quantity;

            return (
              <div
                key={a.accessory_id}
                className={`rounded-2xl shadow-md p-4 md:p-6 flex flex-col justify-between transition
  ${isAvailable 
    ? "bg-white hover:shadow-xl" 
    : "bg-gray-200 opacity-70 cursor-not-allowed"}
`}
              >
                <div className="text-center">
                  

                  <Image
  alt={a.model || "Accessory"}
  src={`${process.env.NEXT_PUBLIC_API_URL}${a.image_url}`}
  width={300}
  height={200}
  className="h-28 md:h-40 w-auto mx-auto object-contain"
/>

                  <h3 className="font-semibold text-base md:text-lg mt-3">
                    {a.model}
                  </h3>

                  <p className="text-xs md:text-sm text-gray-500 mt-1">
                    {a.description}
                  </p>

                  <div className="text-xs text-gray-400 mt-2">
                    ₹ {a.price} × {a.max_qty || 1}
                  </div>

                  {!isAvailable && (
  <div className="text-red-500 text-sm font-semibold mt-2">
    Not Available
  </div>
)}

<div className="text-xs text-gray-500 mt-1">
  Available: {a.available_quantity}
</div>
                </div>

                {/* COUNTER */}
                <div className="flex items-center justify-between mt-5">
                  <div className="flex items-center gap-3">
                      <button
  disabled={!isAvailable}
  onClick={() => updateQty(a.accessory_id, -1)}
  className={`w-8 h-8 md:w-9 md:h-9 rounded-md flex items-center justify-center
    ${isAvailable ? "bg-primary text-white" : "bg-gray-400 text-white cursor-not-allowed"}
  `}
>
                      <Minus size={14} />
                    </button>

                    <span className="font-semibold text-base w-6 text-center">
                      {qty}
                    </span>

                <button
  disabled={!isAvailable || isMaxReached}
  onClick={() => updateQty(a.accessory_id, 1)}
  className={`w-8 h-8 md:w-9 md:h-9 rounded-md flex items-center justify-center
    ${
      isAvailable && !isMaxReached
        ? "bg-primary text-white"
        : "bg-gray-400 text-white cursor-not-allowed"
    }
  `}
>
                      <Plus size={14} />
                    </button>
                  </div>

                  <div className="font-semibold text-base md:text-lg">
                    ₹ {(qty * a.price).toFixed(2)}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}


