"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 SilhouetteInterface {
  id: string;
  image: string;
  title: string;
  label: string;
  varPrice?: number;
  price?: number;
  silhouette_id: string;
}

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

const STORAGE_KEY = "CategoryThreePieceVest";
const NO_VEST = "No vest";

export default function CategoryThreePieceChild({
  updateState,
  setIsStepValid,
  jumpToNext,
  state,
}: Props) {
  const [isVestMode, setIsVestMode] = useState(false);

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

  const [selectedSubCategory, setSelectedSubCategory] = useState<string>(
    state?.SubCategoryList || "",
  );

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

    setIsVestMode(saved === NO_VEST);
  }, [updateState, selectedSubCategory, setIsStepValid]);

  const handleChange = (SubCategoryList: string, silhouette_id: string) => {
    updateState?.("SubCategoryList", SubCategoryList);
    localStorage.setItem(STORAGE_KEY, SubCategoryList);

    localStorage.setItem("silhouette", silhouette_id);
    localStorage.setItem("vestCategoryId", silhouette_id);

    jumpToNext?.();
  };

  const selected = state?.SubCategoryList ?? "";

  const handleVestMode = () => {
    localStorage.setItem(STORAGE_KEY, NO_VEST);
    setSelectedSubCategory(NO_VEST);
    updateState?.("SubCategoryList", NO_VEST);
    setIsVestMode(true);
    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/vest?sub_category_id=${subcategoryId}&suit_enable=Yes&session_id=${getUserSessionId()}`,
          {
            cache: "no-store",
          },
        );
        const data = await response.json();
        setSilhouetteList(data.data || []);
      } catch (error) {
        console.error("Failed to fetch category options:", error);
      }
    };
    fetchParentCategories();
  }, []);

  console.log("Silhouette List:", silhouetteList);

  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">Vests</span> (optional)
          </h2>

          <p className="text-sm font-light"></p>
        </div>

        <div className="cc-vision-wrap">
          <div className="ccvision-scrollcontent">
            <div className="gridItems bottomAlign">
              {silhouetteList &&
                silhouetteList.map(
                  ({ id, image, label, price, silhouette_id }) => (
                    <label
                      key={label}
                      className={`relative flex w-full cursor-pointer flex-col overflow-hidden border border-dashed transition-all duration-300 ${
                        selectedSubCategory === label
                          ? "border-green-400 bg-gray-100"
                          : "border-transparent hover:bg-gray-100"
                      }`}
                    >
                      {selectedSubCategory === label && (
                        <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={selectedSubCategory === label}
                        onChange={() => handleChange(label, silhouette_id)}
                        onClick={() => 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>
                  ),
                )}
              {silhouetteList.length === 0 ? (
                <div className="flex w-full items-center justify-center p-4">
                  <p className="text-sm font-light">
                    No vest options available at the moment.
                  </p>
                </div>
              ) : null}
            </div>
          </div>
          {/* MORNI Mode Button */}
          <div className="ccBottomBtnWrap">
            <button
              type="button"
              onClick={handleVestMode}
              className={`mt-4 flex h-12.25 w-full flex-col items-center justify-center border-1 border-dashed p-2 text-center align-middle transition-all duration-300 ${
                isVestMode
                  ? "border-2 border-green-500 bg-gray-100"
                  : "hover:bg-gray-100"
              }`}
            >
              <p className="text-base/4 font-medium uppercase">No vest</p>
            </button>
          </div>
        </div>
      </div>
    </>
  );
}
