"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 { state, updateState } = useWizardContext();
  const [selectedCategory, setSelectedCategory] = useState("");

  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.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 handleCategoryChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    clickCategory: any,
  ) => {
    const value = e.target.value;
    updateState("CategoryType", value);
    console.log("Selected category:", value, clickCategory);

    localStorage.setItem("categoryName", clickCategory.title);
    localStorage.setItem("CategoryType", value);
    localStorage.setItem("categoryId", clickCategory.id);

    jumpToNext();
  };

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

  if (loading) return <div>Loading categories...</div>;
  console.log("selectedCategory", selectedCategory);
  return (
    <div>
      <div className="grid grid-cols-2 gap-4 md:grid-cols-6">
        {categoryOptions.map((option) => {
          const isSelected = selectedCategory === option.id.toString();

          return (
            <label
              key={option.id}
              className={clsx(
                "cursor-pointer rounded border px-4 py-2 text-center transition-all",
                isSelected
                  ? "border-green-500 bg-white text-black"
                  : "border-gray-300 bg-white text-black hover:border-black",
              )}
            >
              <input
                type="radio"
                name="categoryType"
                value={option.piece_type}
                checked={isSelected}
                onChange={(e) => handleCategoryChange(e, option)}
                className="sr-only"
              />
              <div>
                <Image
                  src={`${AWS_CDN_URL}/${option.image}`}
                  alt={option.title}
                  width={600}
                  height={1000}
                  className="img-responsive"
                />
              </div>
              <div className="text-sm font-light capitalize">
                {option.title}
              </div>
            </label>
          );
        })}
      </div>
    </div>
  );
}
