"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: { ItemList?: string };
}

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 SubCategoryStep({
  updateState,
  setIsStepValid,
  jumpToNext,
  state,
}: Props) {
  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);
    }
  }, [updateState, selectedID, setIsStepValid]);

  const handleChange = (selectedID: string, silhouette_id: string) => {
    ///alert("Please select a silhouette", selectedID);

    console.error("Please select a silhouette", selectedID);
    localStorage.setItem("silhouette", silhouette_id);

    updateState?.("selectedID", selectedID);
    localStorage.setItem(STORAGE_KEY, selectedID);
    jumpToNext?.();
  };

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

  useEffect(() => {
    const subcategoryId = localStorage.getItem("subcategoryId");
    /// if (!subcategoryId) return; // Only call API if value exists

    const fetchParentCategories = async () => {
      const subcategoryId = localStorage.getItem("subcategoryId");
      const gender = localStorage.getItem("genderExpression");
      const sessionId = getUserSessionId();
      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]);
  //console.log('categoryArray', categoryArray);
  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-2/3">
          <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 &&
                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={`relative flex w-full cursor-pointer flex-col overflow-hidden border border-dashed transition-all duration-300 ${
                          isSelected
                            ? "border-green-400 bg-gray-100"
                            : "border-transparent hover:bg-gray-100"
                        }`}
                      >
                        {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/4 justify-center text-center font-light capitalize">
                            <p className="">{label}</p>
                            {price !== undefined && price > 0 && (
                              <p className="mt-1 text-xs">$ {price}</p>
                            )}
                          </div>
                        </div>
                      </label>
                    );
                  },
                )}
              {silhouetteList.length === 0 && (
                <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>
    </>
  );
}
