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

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

interface SubCategoryInterface {
  id: string;
  image: string;
  title: string;
  min_price: number;
  has_selected?: boolean;
}

const STORAGE_KEY = "CategorySingle";
const CATEGORY_KEY_ID = "categoryId";
const CATEGORY_KEY_NAME = "categoryName";

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

  const [subCategoryList, setSubCategoryList] = useState<
    SubCategoryInterface[]
  >([]);
  const [saveCategoryId, setSaveCategoryId] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<string>("");
  const [subCategoryTitle, setSubCategoryTitle] = useState<string>("");
  const searchParams = useSearchParams();
  const externalId = searchParams.get("external");

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

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

    jumpToNext?.();
  };

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

  useEffect(() => {
    const categoryId = localStorage.getItem("categoryId");
    if (categoryId) {
      const fetchParentCategories = async () => {
        try {
          const response = await fetch(
            `${process.env.NEXT_PUBLIC_API_BASE_URL}/co-creation/sub-category/${categoryId}?session_id=${getUserSessionId()}`,
            {
              cache: "no-store",
            },
          );
          const data = await response.json();
          setSubCategoryList(data.data || []);
          setSelectedCategory(data.selected_category || "");
          localStorage.setItem(
            CATEGORY_KEY_NAME,
            data.selected_category?.title || "",
          );
        } catch (error) {
          console.error("Failed to fetch category options:", error);
        }
      };
      fetchParentCategories();
    }
  }, [saveCategoryId]);



  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">
              {getCategoryName() === "Co-ord Sets" ? "Tops" : getCategoryName()}
            </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, min_price, has_selected }) => {
                    const isSelected = has_selected;

                    return (
                      <label
                        id={`subcategory-${id}`}
                        key={`subcategory_key-${id}`}
                        onClick={() => handleChange(title, id.toString())}
                        className={`relative flex w-full cursor-pointer border border-dashed 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="SubCategoryList"
                          value={title}
                          checked={isSelected}
                          onChange={() => {}}
                          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>
                            {typeof min_price === "number" && min_price > 1 && (
                              <p className="mt-1"> $ {min_price}</p>
                            )}
                          </div>
                        </div>
                      </label>
                    );
                  },
                )}
            </div>
            {subCategoryList.length === 0 && (
              <div className="flex w-full items-center justify-center p-4">
                <p className="text-sm font-light">
                  No{" "}
                  <span className="font-medium">
                    {getCategoryName() === "Co-ord Sets"
                      ? "Tops"
                      : getCategoryName()}{" "}
                  </span>
                  items available at this moment.
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
