"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 = "CategoryTwoPiece";
const CATEGORY_KEY_ID = "categoryId";
const CATEGORY_KEY_NAME = "categoryName";

interface SubCategoryInterface {
  id: string;
  image: string;
  title: string;
}

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

  const [selected_bottom_category_id, setSelectedBottomCategoryId] =
    useState<string>("");

  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, id: string) => {
    setSelectedSubCategory(SubCategoryList);
    updateState?.("SubCategoryList", SubCategoryList);
    localStorage.setItem(STORAGE_KEY, SubCategoryList);
    localStorage.setItem("subcategoryId", id);

    localStorage.setItem("bottomCategoryId", id);

    jumpToNext?.();
  };

  //console.log("CATEGORY_KEY_ID:", localStorage.getItem(CATEGORY_KEY_ID));

  useEffect(() => {
    const categoryId = localStorage.getItem(CATEGORY_KEY_ID);
    if (categoryId) {
      const fetchParentCategories = async () => {
        try {
          const response = await fetch(
            `${process.env.NEXT_PUBLIC_API_BASE_URL}/co-creation/sub-category/bottom/${categoryId}?session_id=${getUserSessionId()}`,
            {
              cache: "no-store",
            },
          );
          const data = await response.json();
          setSubCategoryList(data.data || []);
          setSelectedBottomCategoryId(data.selected_bottom_category_id || "");
          localStorage.setItem(
            "subcategoryId",
            data.selected_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-2/3">
          <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">
              {subCategoryList &&
                subCategoryList.map(({ id, image, title }) => {
                  const isSelected = selected_bottom_category_id === id;
                  return (
                    <label
                      key={id}
                      className={`relative flex w-full cursor-pointer flex-col overflow-hidden border-1 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="SubCategoryList"
                        value={title}
                        checked={isSelected}
                        onChange={() => handleChange(title, id)}
                        onClick={() => {
                          if (selected_bottom_category_id === id) {
                            jumpToNext?.();
                          }
                        }}
                        className="sr-only"
                      />
                      <div className="flex flex-col items-center p-2">
                        <Image
                          src={`${AWS_CDN_URL}/${image}`}
                          alt={title}
                          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="">{title}</p>
                        </div>
                      </div>
                    </label>
                  );
                })}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
