"use client";
import React, { useEffect, useState } from "react";
import Image from "next/image";
import {AWS_CDN_URL } from "@/utils/staticValues";
import { getUserSessionId } from "@/utils/helper";

interface Props {
  setIsStepValid: (isValid: boolean) => void;
  updateState: (key: string, value: any) => void;
  jumpToNext: () => void;
  state: { SubCategoryList?: string };
}

const STORAGE_KEY = "CategoryThreePieceBottom";

interface SilhouetteInterface {
  id: string;
  image: string;
  title: string;
  label: string;
  varPrice?: number;
  price?: number;
  silhouette_id: string;
  is_selected?: string;
}

export default function CategoryThreePieceStep2({
  updateState,
  setIsStepValid,
  jumpToNext,
  state,
}: Props) {
  const [selectedSubCategory, setSelectedSubCategory] = useState<string>(
    state?.SubCategoryList || "",
  );

  const [silhouetteList, setSilhouetteList] = useState<SilhouetteInterface[]>(
    [],
  );

  useEffect(() => {
    setIsStepValid(!!selectedSubCategory);
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved && saved !== selectedSubCategory) {
      setSelectedSubCategory(saved);
      updateState?.("SubCategoryList", saved);
    }
  }, [updateState, selectedSubCategory, setIsStepValid]);

  const handleChange = (SubCategoryList: string, silhouette_id: string) => {
    if (selectedSubCategory === SubCategoryList) {
      jumpToNext?.();
      return;
    }

    setSelectedSubCategory(SubCategoryList);
    updateState?.("SubCategoryList", SubCategoryList);
    localStorage.setItem(STORAGE_KEY, SubCategoryList);
    localStorage.setItem("silhouette", silhouette_id);
    localStorage.setItem("bottomCategoryId", silhouette_id);

    jumpToNext?.();
  };
  useEffect(() => {
    const subcategoryId = localStorage.getItem("subcategoryId") || "";

    const fetchParentCategories = async () => {
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_BASE_URL}/co-creation/outerwear/bottom?sub_category_id=${subcategoryId}&suit_enable=Yes&session_id=${getUserSessionId()}`,
          {
            cache: "no-store",
          },
        );
        const data = await response.json();
        setSilhouetteList(data.data || []);
        setSelectedSubCategory(data.bottom_category_id);
      } catch (error) {
        console.error("Failed to fetch category options:", error);
      }
    };
    fetchParentCategories();
  }, []);
  const selected = state?.SubCategoryList ?? "";

  return (
    <>
      <div className="mx-auto flex w-full flex-col items-center justify-center gap-2 align-middle">
        <div className="mx-auto flex w-full flex-col items-center justify-center gap-2 text-center md:w-[50%]">
          <h2 className="vision">
            What style of <span className="font-medium">Bottoms</span> are you
            looking for?
          </h2>
          <p className="text-sm font-light"></p>
        </div>

        <div className="cc-vision-wrap fullHeight">
          <div className="ccvision-scrollcontent noBottomBtn">
            <div className="gridItems bottomAlign">
              {silhouetteList &&
                silhouetteList.map(
                  ({ id, image, label, price, silhouette_id, is_selected }) => (
                    <label
                      key={label}
                      className={`relative flex w-full cursor-pointer flex-col overflow-hidden border border-dashed transition-all duration-300 ${
                        is_selected === "Yes"
                          ? "border-green-400 bg-gray-100"
                          : "border-transparent hover:bg-gray-100"
                      }`}
                      onClick={() => handleChange(label, silhouette_id)} 
                    >
                      {is_selected === "Yes" && (
                        <div className="absolute top-2 right-2 flex h-6 w-6 items-center justify-center rounded-full border-2 border-gray-100 bg-green-400 align-middle">
                          <i className="icon-[qlementine-icons--check-tick-16] text-white"></i>
                        </div>
                      )}
                      <input
                        type="radio"
                        name="SubCategoryList"
                        value={label}
                        checked={is_selected === "Yes"}
                        onChange={() => handleChange(label, silhouette_id)}
                        className="sr-only"
                      />
                      <div className="flex flex-col items-center p-2">
                        <Image
                          src={`${AWS_CDN_URL}/${image}`}
                          alt={label}
                          width={400}
                          height={400}
                          className="img-responsive"
                        />
                        <div className="mt-4 items-center text-xs md:text-sm justify-center text-center font-light capitalize">
                          <p className="">{label}</p>
                          <p className="mt-1">${price}</p>
                        </div>
                      </div>
                    </label>
                  ),
                )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
