"use client";
import React, { useEffect, useState } from "react";
import Image from "next/image";
import axios from "axios";
import {AWS_CDN_URL } from "@/utils/staticValues";

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

const STORAGE_KEY = "categoryBasic";

export default function CategoryBasic({
  updateState,
  setIsStepValid,
  jumpToNext,
  state,
}: Props) {
  const [itemListOptions, setItemListOptions] = useState<
    { id: number; title: string; image: string }[]
  >([]);
  const [selectedOption, setSelectedOption] = useState<string>(
    state?.ItemList || "",
  );

  useEffect(() => {
    const fetchOptions = async () => {
      try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/co-creation/category`, {
          cache: "no-store",
        });
        const data = await response.json();
        setItemListOptions(data.data || []);
      } catch (error) {
        console.error("Failed to fetch category options", error);
      }
    };
    fetchOptions();
  }, []);

  useEffect(() => {
    setIsStepValid(!!selectedOption);
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved && saved !== selectedOption) {
      setSelectedOption(saved);
      updateState?.("categoryBasic", saved);
    }
  }, [updateState, selectedOption, setIsStepValid]);

  const handleChange = (value: string) => {
    setSelectedOption(value);
    updateState?.("categoryBasic", value);
    localStorage.setItem(STORAGE_KEY, value);
    setIsStepValid(true);
    jumpToNext?.();
  };

  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 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">
              {itemListOptions.map(({ title, image }) => (
                <label
                  key={title}
                  onClick={() => handleChange(title)}
                  className={`relative cursor-pointer border-1 border-dashed p-2 transition-all duration-300 hover:bg-gray-100 ${
                    selectedOption === title
                      ? "border-green-400 bg-gray-100"
                      : "border-transparent"
                  }`}
                >
                  {selectedOption === title && (
                    <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="ItemList"
                    value={title}
                    checked={selectedOption === title}
                    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>
    </>
  );
}
