"use client";

import React, { useState, useMemo, useEffect } from "react";
import { formatPrice } from "@/utils/currencyHelper";
import { useCart } from "../context/CartContext";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { resolveImage } from "@/utils/imageHelper";

const getColorHex = (colorName: string): string => {
  const lower = colorName.toLowerCase();
  if (lower.includes("black")) return "#121212";
  if (lower.includes("white")) return "#f8fafc";
  if (lower.includes("red")) return "#dc2626";
  if (lower.includes("blue")) return "#2563eb";
  if (lower.includes("yellow")) return "#facc15";
  if (lower.includes("orange")) return "#f97316";
  if (lower.includes("green")) return "#16a34a";
  if (lower.includes("grey") || lower.includes("gray")) return "#4b5563";
  if (lower.includes("carbon")) return "#2b2b2b";
  if (lower.includes("pink")) return "#ec4899";
  if (lower.includes("silver")) return "#cbd5e1";
  return "#e2e8f0";
};

export type SubmodelVariant = {
  variant_id: string;
  sku_no: string;
  size: number | null;
  size_name: string | null;
  color: string | null;
  finish: string | null;
  is_active: boolean;
  mrp: number | null;
  product_images: string[];
  b2b_inward: {
    inward_id: string;
    dealer_price: number;
    currency: string;
    quantity: number | null;
    is_individual: boolean;
    is_carton: boolean;
    is_featured: boolean;
    is_active: boolean;
    is_new_arrival?: boolean;
    is_best_seller?: boolean;
    carton_box_size?: number;
  } | null;
};

type Props = {
  submodelVariants: SubmodelVariant[];
  defaultInwardId: string;
  defaultColor: string | null;
  defaultSizeName: string | null;
  defaultDealerPrice: number;
  defaultCurrency?: string;
  defaultMrp?: number | null;
  defaultIsCarton?: boolean;
  defaultIsIndividual?: boolean;
  defaultCartonBoxSize?: number;
  defaultImages: string[];
  apiBaseUrl: string;
  isNewArrival?: boolean;
  shortDescription: string;
  longDescription?: string;
  technicalSpecs?: {
    visor_type?: string;
    certification?: string[];
    chinstrap_lock?: string;
    pinlock?: string;
    spoiler?: string;
  };
};

export default function ProductVariantSelector({
  submodelVariants,
  defaultInwardId,
  defaultColor,
  defaultSizeName,
  defaultDealerPrice,
  defaultCurrency,
  defaultMrp,
  defaultIsCarton,
  defaultIsIndividual,
  defaultCartonBoxSize,
  defaultImages,
  apiBaseUrl,
  isNewArrival,
  shortDescription,
  longDescription,
  technicalSpecs,
}: Props) {
  const router = useRouter();
  const { openCart } = useCart();
  const [adding, setAdding] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isActiveUser, setIsActiveUser] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    const check = () => {
      setIsLoggedIn(!!localStorage.getItem("access_token"));
      setIsActiveUser(localStorage.getItem("is_active") === "true");
    };
    check();
    window.addEventListener("storage", check);
    return () => window.removeEventListener("storage", check);
  }, []);

  // Filter variants that are B2B active and inwarded
  const activeVariants = useMemo(() => {
    return submodelVariants.filter((v) => v.b2b_inward !== null && v.b2b_inward.is_active);
  }, [submodelVariants]);

  // Group variants by color
  const groupedByColor = useMemo(() => {
    const groups: Record<string, { variants: SubmodelVariant[]; startIndex: number }> = {};
    let globalIndex = 0;
    activeVariants.forEach((v) => {
      const colorKey = v.color || "Default Color";
      if (!groups[colorKey]) {
        groups[colorKey] = { variants: [], startIndex: globalIndex };
      }
      groups[colorKey].variants.push(v);
      globalIndex++;
    });
    return groups;
  }, [activeVariants]);

  // Unique colors list for swatches
  const uniqueColors = useMemo(() => {
    const colors = new Set<string>();
    activeVariants.forEach((v) => {
      if (v.color) colors.add(v.color);
    });
    return Array.from(colors);
  }, [activeVariants]);

  const [selectedColor, setSelectedColor] = useState<string | null>(defaultColor || uniqueColors[0] || null);

  // Quantities state keyed by inward_id
  const [quantities, setQuantities] = useState<Record<string, number>>({});

  // Active hover/selected image from row hover
  const [hoveredVariantIdx, setHoveredVariantIdx] = useState<number | null>(null);

  // Compute resolved images for the main gallery based on hovered variant OR active selected color
  const activeColorVariant = useMemo(() => {
    return activeVariants.find((v) => v.color === selectedColor) || activeVariants[0];
  }, [activeVariants, selectedColor]);

  const selectedColorVariants = useMemo(() => {
    return activeVariants.filter((v) => v.color === selectedColor);
  }, [activeVariants, selectedColor]);

  const mainVariant = hoveredVariantIdx !== null ? activeVariants[hoveredVariantIdx] : (activeColorVariant ?? null);
  const rawImages = mainVariant?.product_images?.length ? mainVariant.product_images : defaultImages;
  const [activeImageIdx, setActiveImageIdx] = useState(0);

  const resolvedImages = rawImages.map((img) => resolveImage(img));
  const fallbackImage =
    "https://static.wixstatic.com/media/703249_3a76a53b765e46d4b3a5e4c3ec6ddd7e~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/Full%20Face%20Helmet.png";

  const mainImage = resolvedImages[activeImageIdx] || fallbackImage;

  // Handle typable input changes
  const handleInputChange = (inwardId: string, val: string) => {
    if (val === "") {
      setQuantities((prev) => ({ ...prev, [inwardId]: 0 }));
      return;
    }
    const num = parseInt(val, 10);
    if (!isNaN(num) && num >= 0) {
      setQuantities((prev) => ({ ...prev, [inwardId]: num }));
    }
  };

  const increment = (inwardId: string) => {
    setQuantities((prev) => ({
      ...prev,
      [inwardId]: (prev[inwardId] || 0) + 1,
    }));
  };

  const decrement = (inwardId: string) => {
    setQuantities((prev) => ({
      ...prev,
      [inwardId]: Math.max(0, (prev[inwardId] || 0) - 1),
    }));
  };

  // Computations for checkout summary
  const summary = useMemo(() => {
    let totalItems = 0;
    let totalPrice = 0;
    let currency = defaultCurrency || "INR";

    activeVariants.forEach((v) => {
      const inward = v.b2b_inward!;
      const qty = quantities[inward.inward_id] || 0;
      if (qty > 0) {
        totalItems += qty;
        totalPrice += inward.dealer_price * qty;
        currency = inward.currency;
      }
    });

    return { totalItems, totalPrice, currency };
  }, [activeVariants, quantities, defaultCurrency]);

  const handleAddAllToCart = async () => {
    const itemsToAdd = Object.entries(quantities)
      .map(([inwardId, qty]) => ({ inwardId, qty }))
      .filter((item) => item.qty > 0);

    if (itemsToAdd.length === 0) return;

    const token = localStorage.getItem("access_token");
    if (!token) {
      router.push("/login");
      return;
    }

    setAdding(true);
    try {
      await Promise.all(
        itemsToAdd.map(({ inwardId, qty }) =>
          fetch(`${apiBaseUrl}/api/v1/b2b-cart/items`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${token}`,
            },
            body: JSON.stringify({ inward_id: inwardId, quantity: qty }),
          })
        )
      );

      openCart();
      setQuantities({});
    } catch (err) {
      alert("Failed to add items to cart.");
    } finally {
      setAdding(false);
    }
  };

  return (
    <div className="flex flex-col gap-16">
      {/* 1. Top Fold: Premium Interactive Gallery & Product Details Info */}
      <div className="flex flex-col lg:flex-row gap-12 xl:gap-16 items-start">

        {/* Left Part: Premium Interactive Image Gallery with Vertical Thumbnails */}
        <div className="w-full lg:w-[55%] flex gap-4 lg:sticky lg:top-28">

          {/* Vertical Thumbnails (Desktop) */}
          {resolvedImages.length > 1 && (
            <div className="hidden md:flex flex-col gap-3 w-18 shrink-0 max-h-[450px] overflow-y-auto pr-1 scrollbar-hide select-none">
              {resolvedImages.map((img, idx) => (
                <button
                  key={idx}
                  onClick={() => setActiveImageIdx(idx)}
                  className={`w-16 h-16 rounded-2xl border-2 bg-white overflow-hidden shrink-0 transition-all ${activeImageIdx === idx
                      ? "border-gray-950 shadow-sm scale-[1.02]"
                      : "border-gray-100 hover:border-gray-300"
                    }`}
                >
                  <img
                    src={img}
                    alt={`Thumbnail ${idx + 1}`}
                    className="w-full h-full object-contain p-1.5"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = fallbackImage;
                    }}
                  />
                </button>
              ))}
            </div>
          )}

          {/* Main Preview Card */}
          <div className="flex-1 bg-white border border-gray-100 rounded-[2.5rem] aspect-square flex items-center justify-center p-8 sm:p-12 overflow-hidden relative group max-h-[480px] select-none">
            <img
              src={mainImage}
              alt={shortDescription}
              className="w-full h-full object-contain group-hover:scale-103 transition-transform duration-700 ease-out drop-shadow-md"
              onError={(e) => {
                (e.target as HTMLImageElement).src = fallbackImage;
              }}
            />
            {isNewArrival && (
              <div className="absolute top-6 left-6 bg-primary text-white text-[10px] font-black px-4 py-1.5 rounded-full uppercase tracking-[0.2em] shadow-lg shadow-primary/20">
                New Arrival
              </div>
            )}
          </div>
        </div>

        {/* Right Part: Meta Information, Color Swatches & Specifications Accordion */}
        <div className="w-full lg:w-[45%] flex flex-col gap-6">
          <div className="flex flex-col gap-2">
            <h1 className="text-3xl lg:text-4xl font-black text-gray-900 tracking-tight leading-tight uppercase">
              {shortDescription}
            </h1>
          </div>

          {/* Long Description text block */}
          <p className="text-[14px] text-gray-500 font-medium leading-relaxed">
            {longDescription || `Premium certified protective gear featuring lightweight aerodynamic shell construction, comfortable inner linings, and safety-tested protection parameters designed specifically for modern riders.`}
          </p>

          {/* COLOR Selection Swatches */}
          {uniqueColors.length > 0 && (
            <div className="flex flex-col gap-3">
              {/* Stacked label: "COLOR" + selected color name below */}
              <div className="flex flex-col gap-0.5">
                <span className="text-[11px] font-black text-gray-400 uppercase tracking-widest leading-none">
                  COLOR
                </span>
                {selectedColor && (
                  <span className="text-[13px] font-black text-gray-800 uppercase tracking-wide leading-snug">
                    {selectedColor}
                  </span>
                )}
              </div>
              <div className="flex items-center gap-3">
                {uniqueColors.map((color) => (
                  <button
                    key={color}
                    onClick={() => {
                      setSelectedColor(color);
                      setActiveImageIdx(0);
                    }}
                    className={`w-8 h-8 rounded-full border border-gray-300 transition-all flex items-center justify-center relative ${selectedColor === color
                        ? "ring-2 ring-gray-950 ring-offset-2 scale-110 shadow-sm"
                        : "hover:scale-105"
                      }`}
                    title={color}
                  >
                    <span
                      className="w-full h-full rounded-full border border-white/20"
                      style={{ backgroundColor: getColorHex(color) }}
                    />
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Size & SKU selectors dependent on the selected Color */}
          {selectedColor && selectedColorVariants.length > 0 && (
            <div className="flex flex-col gap-3 border-t border-gray-150 pt-4 mt-2">
              <span className="text-[11px] font-black text-gray-400 uppercase tracking-widest leading-none mb-1">
                {mounted && isLoggedIn && isActiveUser ? "Select Quantities" : "Available Sizes"}
              </span>
              <div className="flex flex-row flex-wrap gap-x-10 gap-y-4">
                {selectedColorVariants.map((v, localIdx) => {
                  const inward = v.b2b_inward!;
                  const qty = quantities[inward.inward_id] || 0;
                  const colorGroup = groupedByColor[selectedColor];
                  const globalIdx = colorGroup ? colorGroup.startIndex + localIdx : 0;

                  return (
                    <div
                      key={v.variant_id}
                      className="flex flex-col justify-between gap-2 transition-all"
                      onMouseEnter={() => {
                        setHoveredVariantIdx(globalIdx);
                        setActiveImageIdx(0);
                      }}
                      onMouseLeave={() => setHoveredVariantIdx(null)}
                    >
                      <div className="flex flex-col">
                        <span className="text-base font-black text-gray-900 leading-none">
                          Size: {v.size_name || v.size || "N/A"}
                        </span>
                        <span className="text-[10px] font-bold text-gray-455 mt-1.5 tracking-wider uppercase leading-none">
                          SKU: {v.sku_no}
                        </span>
                        {/* Dealer price — only shown when logged in and active */}
                        {mounted && isLoggedIn && isActiveUser && inward.dealer_price && (
                          <span className="text-sm font-black text-emerald-600 mt-1 leading-none">
                            {formatPrice(inward.dealer_price, inward.currency)}
                          </span>
                        )}
                      </div>

                      {/* Stepper — only shown when logged in and active */}
                      {mounted && isLoggedIn && isActiveUser && (
                        <div className="flex items-center h-7 bg-gray-100 border border-gray-205 rounded-lg overflow-hidden px-1 justify-between w-24 select-none shadow-inner shrink-0 mt-0.5">
                          <button
                            onClick={() => decrement(inward.inward_id)}
                            className="w-5 h-5 rounded-md flex items-center justify-center text-gray-500 hover:bg-gray-200 active:scale-90 hover:text-gray-900 transition-all font-black text-xs"
                          >
                            −
                          </button>
                          <input
                            type="number"
                            min="0"
                            value={qty || ""}
                            onChange={(e) => handleInputChange(inward.inward_id, e.target.value)}
                            placeholder="0"
                            className="w-full text-center text-xs font-black bg-transparent outline-none border-0 text-gray-900 focus:ring-0 p-0 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                          />
                          <button
                            onClick={() => increment(inward.inward_id)}
                            className="w-5 h-5 rounded-md flex items-center justify-center text-gray-500 hover:bg-gray-200 active:scale-90 hover:text-gray-900 transition-all font-black text-xs"
                          >
                            +
                          </button>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )}
          {/* Cart summary + add-to-cart: only for logged-in active dealers */}
          {mounted && isLoggedIn && isActiveUser ? (
            <div className="border-t border-gray-150 pt-5 mt-2 flex flex-col gap-4 select-none">
              <div className="flex justify-between items-center">
                <div className="flex flex-col">
                  <span className="text-[9px] font-black text-gray-400 uppercase tracking-widest leading-none mb-1">
                    Total Selected
                  </span>
                  <span className="text-base font-black text-gray-900">
                    {summary.totalItems} {summary.totalItems === 1 ? "item" : "items"}
                  </span>
                </div>
                {summary.totalItems > 0 && (
                  <span className="text-sm font-black text-emerald-600">
                    {formatPrice(summary.totalPrice, summary.currency)}
                  </span>
                )}
              </div>

              <button
                onClick={handleAddAllToCart}
                disabled={adding || summary.totalItems === 0}
                className="w-full py-3.5 bg-[#FFC633] hover:bg-[#E0AB1F] text-gray-900 border border-[#E0AB1F] font-black text-xs tracking-wider uppercase rounded-xl transition-all shadow-md active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {adding ? (
                  <span className="w-4 h-4 border-2 border-slate-900/40 border-t-slate-900 rounded-full animate-spin" />
                ) : (
                  "Add Selected to Cart"
                )}
              </button>
            </div>
          ) : null}

          {/* Message for pending active approval */}
          {mounted && isLoggedIn && !isActiveUser && (
            <div className="border-t border-gray-150 pt-5 mt-2 flex flex-col gap-4 select-none">
              <div className="bg-yellow-50 border border-yellow-200 p-4 rounded-xl flex items-start gap-3">
                <svg className="w-5 h-5 text-yellow-600 mt-0.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8V7z" />
                </svg>
                <div className="flex flex-col">
                  <span className="text-sm font-bold text-yellow-800">Account Pending Approval</span>
                  <span className="text-xs font-medium text-yellow-700 mt-1">Prices and ordering will be unlocked once your account is approved.</span>
                </div>
              </div>
            </div>
          )}
          <div className="border-t border-gray-150 pt-6 mt-2 flex flex-col gap-4">
            <div className="flex justify-between items-center cursor-default">
              <span className="text-[12px] font-black text-gray-950 uppercase tracking-widest">
                Product Features
              </span>
            </div>

            <ul className="text-xs text-gray-600 space-y-3 list-disc pl-4 font-semibold leading-relaxed">
              {technicalSpecs?.certification && technicalSpecs.certification.length > 0 && (
                <li>
                  <strong className="text-gray-900">Safety Standards:</strong> Certified with {technicalSpecs.certification.join(', ')} safety compliance, ensuring reliable protection for riders.
                </li>
              )}
              {technicalSpecs?.chinstrap_lock && (
                <li>
                  <strong className="text-gray-900">Chin Strap:</strong> Equipped with a {technicalSpecs.chinstrap_lock} strap for a secure and adjustable fit.
                </li>
              )}
              {technicalSpecs?.visor_type && (
                <li>
                  <strong className="text-gray-900">Visor Type:</strong> {technicalSpecs.visor_type} shield.
                </li>
              )}
              {technicalSpecs?.pinlock && (
                <li>
                  <strong className="text-gray-900">Pinlock:</strong> {technicalSpecs.pinlock}.
                </li>
              )}
              {technicalSpecs?.spoiler && (
                <li>
                  <strong className="text-gray-900">Spoiler:</strong> {technicalSpecs.spoiler}.
                </li>
              )}
              <li>
                <strong className="text-gray-900">Shell Material:</strong> Durable construction for superior impact resistance.
              </li>
            </ul>
          </div>
        </div>

      </div>
    </div>
  );
}
