"use client";
import Image from "next/image";
import React, { useEffect, useState } from "react";
import { useWizardContext } from "../wizardContext";
import type { StepComponentProps } from "../wizardTypes";
import {AWS_CDN_URL } from "@/utils/staticValues";
import clsx from "clsx";
import { getUserSessionId } from "@/utils/helper";
import { useSearchParams } from "next/navigation";

interface CategoryOption {
  id: number;
  image: string;
  title: string;
  piece_type: string;
}

export default function Category({
  jumpToNext,
  setIsStepValid,
}: StepComponentProps) {
  const { updateState } = useWizardContext();
  const [selectedCategory, setSelectedCategory] = useState<string>("");
  const [categoryOptions, setCategoryOptions] = useState<CategoryOption[]>([]);
  const [loading, setLoading] = useState(true);
  const searchParams = useSearchParams();
  const externalId = searchParams.get("external");

  useEffect(() => {
    async function fetchCategories() {
     
      try {
        const res = await fetch(
          `${process.env.NEXT_PUBLIC_API_BASE_URL}/co-creation/category?session_id=${getUserSessionId()}&externalId=${externalId}`,
          {
            method: "GET",
            headers: { "Content-Type": "application/json" },
          },
        );
        const data = await res.json();
        const cleanData = (data.data || data).filter(
          (item: CategoryOption) => item.piece_type && item.title,
        );
        setSelectedCategory(data.selected_category_id?.toString() || "");
        setCategoryOptions(cleanData);
      } catch (error) {
        console.error("Error fetching categories:", error);
      } finally {
        setLoading(false);
      }
    }
    fetchCategories();
  }, [externalId]);

  const handleCategoryClick = (option: CategoryOption) => {
    setSelectedCategory(option.id.toString());
    updateState("CategoryType", option.piece_type);

    localStorage.setItem("categoryName", option.title);
    localStorage.setItem("CategoryType", option.piece_type);
    localStorage.setItem("categoryId", option.id.toString());

    jumpToNext();
  };

  useEffect(() => {
    setIsStepValid(!!selectedCategory);
  }, [selectedCategory, setIsStepValid]);

  if (loading) return <div>Loading...</div>;

  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 are you looking to <span className="font-medium">create</span>?
        </h2>
      </div>

      <div className="cc-vision-wrap fullHeight">
        <div className="ccvision-scrollcontent noBottomBtn">
          <div className="gridItems bottomAlign">
            {categoryOptions.map((option) => {
              const isSelected = selectedCategory === option.id.toString();

              return (
                <button
                  key={option.id}
                  type="button"
                  onClick={() => handleCategoryClick(option)}
                  className={clsx(
                    "relative flex flex-col items-center border border-dashed p-2 text-center transition-all duration-300 focus:outline-none",
                    isSelected
                      ? "border-green-500 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>
                  )}
                  <Image
                    src={`${AWS_CDN_URL}/${option.image}`}
                    alt={option.title}
                    width={600}
                    height={1000}
                    className="h-auto w-full rounded object-contain"
                  />
                  <div className="mt-2 text-xs md:text-sm font-light capitalize">
                    {option.title}
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}
