"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";
import { useWizardContext } from "../wizardContext";
import type { StepComponentProps } from "../wizardTypes";

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

const STORAGE_KEY = "categorySingleChild";
const GET_SUB_CATEGORY_NAME = "CategorySingle";

export default function Category2PieceTopChild({
  setIsStepValid,
  jumpToNext,
}: StepComponentProps) {
  const { state, updateState } = useWizardContext();
  const [selectedID, setSelectedID] = useState<string>(state?.ItemList || "");
  const [silhouetteList, setSilhouetteList] = useState<SilhouetteInterface[]>([]);
  const [categoryArray, setCategoryArray] = useState<SilhouetteInterface[]>([]);


  useEffect(() => {
    setIsStepValid(!!selectedID);

    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved && saved !== selectedID) {
      setSelectedID(saved);
      updateState("selectedID", saved);
    }
  }, [selectedID, setIsStepValid, updateState]);

  const handleChange = (id: string, silhouette_id: string) => {
    console.log("Selected silhouette:", id);
    localStorage.setItem("silhouette", silhouette_id);
    updateState("selectedID", id);
    localStorage.setItem(STORAGE_KEY, id);
    jumpToNext();
  };

  const getSubCategoryName = () => {
    const categoryName = localStorage.getItem(GET_SUB_CATEGORY_NAME);
    return categoryName ?? "";
  };

  useEffect(() => {
    const subcategoryId = localStorage.getItem("subcategoryId");
    const gender = localStorage.getItem("genderExpression");
    const sessionId = getUserSessionId();

    if (!subcategoryId) return;

    const fetchParentCategories = async () => {
      const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}/co-creation/silhouette?sub_category_id=${subcategoryId}&session_id=${sessionId}&gender=${gender}`;

      try {
        const response = await fetch(url, { cache: "no-store" });
        const contentType = response.headers.get("content-type");

        if (!response.ok || !contentType?.includes("application/json")) {
          const errorText = await response.text();
          console.error("Invalid API response (not JSON):", errorText);
          return;
        }

        const data = await response.json();

        const sortedList = (data.data || []).sort(
          (a: SilhouetteInterface, b: SilhouetteInterface) => {
            if (b.label === selectedID) return 1;
            return 0;
          }
        );

        setCategoryArray(data.category_array || []);
        setSilhouetteList(sortedList);
      } catch (error) {
        console.error("Failed to fetch category options:", error);
      }
    };

    fetchParentCategories();
  }, [selectedID]);

  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">{categoryArray[1]?.name ?? ""}</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.length > 0 ? (
              silhouetteList.map(
                ({ id, image, label, price, silhouette_id, has_selected }) => {
                  const isSelected = has_selected;

                  return (
                    <label
                      key={`${label}-${id}`}
                      onClick={() => handleChange(label, silhouette_id)}
                      className={`flex relative w-full border border-dashed cursor-pointer flex-col overflow-hidden transition-all duration-300 ${
                        isSelected
                          ? "border-green-400 bg-gray-100"
                          : "hover:bg-gray-100 border-transparent"
                      }`}
                    >
                      {isSelected && (
                        <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={STORAGE_KEY}
                        value={label}
                        checked={isSelected}
                        onChange={() => {}}
                        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>
                          {price !== undefined && price > 0 && (
                            <p className="mt-1">$ {price}</p>
                          )}
                        </div>
                      </div>
                    </label>
                  );
                }
              )
            ) : (
              <div className="flex w-full items-center justify-center p-4">
                <p className="text-sm text-gray-500">
                  No <span className="font-medium">silhouettes </span>
                  available for this category.
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
