"use client";

import { useMemo } from "react";
import { useRouter } from "next/navigation";
import {
  ChevronLeft,
  Star,
  Fuel,
  Gauge,
  Settings,
  Zap,
  Cog,
  Weight,
  Clock, // ✅ THIS WAS MISSING
} from "lucide-react";
import Image from "next/image";

/* ---------------- PLAN PICKER ---------------- */
const getPlanFromRange = (plans: any[], range: string) => {
  const sizeMap: any = {
    SMALL: "S",
    MEDIUM: "M",
    LARGE: "L",
  };

  return plans?.find((p) => p.size === sizeMap[range]);
};

const formatTime = (iso: string | null) => {
  if (!iso) return "";
  return new Date(iso).toLocaleTimeString("en-IN", {
    hour: "2-digit",
    minute: "2-digit",
    hour12: true,
  });
};

const formatDate = (iso: string | null) => {
  if (!iso) return "";
  return new Date(iso).toLocaleDateString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
};

const getDuration = (from: string | null, to: string | null) => {
  if (!from || !to) return "";

  const diff =
    new Date(to).getTime() - new Date(from).getTime();

  const hrs = Math.floor(diff / (1000 * 60 * 60));
  const mins = Math.floor((diff / (1000 * 60)) % 60);

  return `${hrs} hrs, ${mins} mins`;
};

export default function PartnerPricingPage({
  submodel,
  partners,
  booking,
}: {
  submodel: any;
  partners: any[];
  booking: any;
}) {
  const router = useRouter();

  // ✅ DATA FROM QUERY (you will pass JSON string)

 if (!submodel || !partners) {
  return <div>Invalid data</div>;
}

  const range = booking?.range || "SMALL";
  const attrs =
  submodel?.submodel?.attributes ||
  submodel?.attributes ||
  {};

  /* -------- UNIQUE PARTNERS -------- */
  const uniquePartners = useMemo(() => {
    const seen = new Set();

    return partners.filter((p: any) => {
      const key = p.pickup_point_id;

      if (seen.has(key)) return false;

      seen.add(key);
      return true;
    });
  }, [partners]);

  /* ---------------- UI ---------------- */

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

{/* ================= TOP BOOKING BAR ================= */}
<div className="sticky top-[80px] z-40 bg-primary px-4 md:px-10 py-4 md:py-6">
  <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 text-white">

    {/* LEFT */}
    <div className="flex items-center gap-3 flex-wrap">

      {/* BACK */}
      <button
        onClick={() => router.back()}
        className="bg-white/20 p-2 md:p-3 rounded-lg"
      >
        <ChevronLeft size={18} />
      </button>

      <div className="flex items-center gap-4 flex-wrap mr-10">

      {/* IMAGE FIX ✅ */}
      <div className="flex items-center justify-center ml-10">
  <Image
  alt="Vehicle"
  src={`${process.env.NEXT_PUBLIC_API_URL}${submodel?.image_url || submodel?.image}`}
  width={120}
  height={96}
  className="h-16 md:h-20 lg:h-24 w-auto object-contain"
/>
</div>

      {/* SPECS */}
    

<div className="grid grid-cols-3 gap-x-6 gap-y-3 text-white ml-10">

  <HeaderItem icon={<Fuel size={18} />} text={`${attrs.engine || 249} cc`} />

  <HeaderItem icon={<Gauge size={18} />} text={`${attrs.mileage} KMPL`} />

  <HeaderItem icon={<Weight size={18} />} text={`${attrs.weight} KG`} />

  <HeaderItem icon={<Settings size={18} />} text={`${attrs.torque || "--"} Nm`} />

  <HeaderItem icon={<Zap size={18} />} text={`${attrs.power || "--"} BHP`} />

  <HeaderItem icon={<Clock size={18} />} text={attrs.transmission} />

</div>

    </div>

      {/* FROM */}
      <div>
        <div className="text-sm font-semibold">
          {formatTime(booking?.from)}
        </div>
        <div className="text-xs opacity-80">
          {formatDate(booking?.from)}
        </div>
      </div>

      <Clock size={16} />

      {/* DURATION */}
      <div className="text-sm">
        {getDuration(booking?.from, booking?.to)}
      </div>

      <div className="hidden md:block text-xl">→</div>

      {/* TO */}
      <div>
        <div className="text-sm font-semibold">
          {formatTime(booking?.to)}
        </div>
        <div className="text-xs opacity-80">
          {formatDate(booking?.to)}
        </div>
      </div>
    </div>

    {/* RIGHT (BIKE INFO) */}
    <div>
      Package: {range}
    </div>

  </div>
</div>
   
      {/* BODY */}
   <div className="max-w-7xl mx-auto p-4 md:p-6 flex gap-6">

    {/* ================= FILTER SIDEBAR ================= */}
{/* <div className="hidden md:block w-64 bg-white rounded-xl shadow p-4 h-fit">

  <FilterItem title="PRICE" />
  <FilterItem title="RATING" />
  <FilterItem title="AREA" />
  <FilterItem title="DISTANCE" />

</div> */}

      <div className="flex-1">
  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {uniquePartners.map((partner: any) => {
            const isAvailable = (partner.vehicle_count || 0) > 0;
            const plan = getPlanFromRange(partner.plans, range);

            return (
<div
  key={partner.vehicle_id}
  className="bg-white rounded-xl shadow hover:shadow-lg transition flex flex-col justify-between cursor-pointer"
    onClick={() => {
    if (!isAvailable) return;

    router.push(
      `/accessories?data=${encodeURIComponent(
        JSON.stringify({
          booking: {
            ...booking,
            vehicle: partner,
            selectedPlan: plan,
            submodel,
            pickup_point_id: partner.pickup_point_id,
          },
        })
      )}`
    );
  }}
>

  {/* BIG INITIAL */}
  <div className="text-7xl font-bold text-primary text-center p-3">
    {partner.pickup_point_name?.slice(0, 2).toUpperCase()}
  </div>

  {/* PARTNER NAME */}
  <div className="text-left mt-2 text-sm text-gray-700 ml-3">
    {partner.pickup_point_name}
  </div>

  {/* RATING */}
  <div className="flex justify-left items-left gap-1 text-xs text-gray-500 mt-1 ml-3">
    <Star size={14} className="text-yellow-400 fill-yellow-400" />
    <span>4.5(66 reviews)</span>
  </div>

  {/* PRICE */}
  <div className="text-center mt-3 flex justify-between">
    <div className="text-xs text-gray-400 ml-3">Price</div>
    <div className="font-semibold text-gray-800 mr-3">
      ₹ {isAvailable ? plan?.price : "--"}
    </div>
  </div>

  {/* BUTTON */}
<div
  className={`w-full py-3 text-sm font-medium text-center
              flex items-center justify-center gap-2
              rounded-b-2xl transition-all duration-200
              ${
                isAvailable
                  ? "bg-primary text-white hover:bg-primary cursor-pointer shadow-md"
                  : "bg-gray-300 text-white cursor-not-allowed"
              }`}
>
  Select partner →
</div>
</div>
            );
          })}
        </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- SPEC ---------------- */
function Spec({ icon, text }: any) {
  return (
    <div className="flex items-center gap-2">
      <span className="text-primary">{icon}</span>
      <span className="text-xs">{text || "--"}</span>
    </div>
  );
}

function FilterItem({ title }: any) {
  return (
    <div className="border-b py-3 flex justify-between items-center text-sm cursor-pointer">
      <span className="font-medium text-gray-700">{title}</span>
      <span>⌄</span>
    </div>
  );
}

function HeaderItem({ icon, text }: any) {
  return (
    <div className="flex items-center gap-2">
      <span className="text-white">{icon}</span>
      <span className="text-sm font-medium">{text}</span>
    </div>
  );
}