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

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

const STORAGE_KEY = "artworkProminent";
const MORNI_VALUE = "Let Decide Morni";

export default function ArtworkProminent({
  updateState,
  setIsStepValid,
  jumpToNext,
  state,
}: Props) {
  const [selectedOption, setSelectedOption] = useState<string>(
    state?.artworkProminentList || "",
  );
  const [prominentList, setProminentList] = useState<
    { label: string; image: string; price: number; id: string }[]
  >([]);

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

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

  const resetSelection = () => {
    const morniValue = MORNI_VALUE;
    setSelectedOption(morniValue);
    updateState?.("artworkProminentList", morniValue);
    localStorage.setItem(STORAGE_KEY, morniValue);
    jumpToNext?.();
  };

  const isMorniMode = selectedOption === MORNI_VALUE;

  useEffect(() => {
    const fetchProminenceList = async () => {
      const technique = localStorage.getItem("artworkTechniqueChild");
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_BASE_URL}/co-creation/prominence-level?session_id=${getUserSessionId()}&technique=${technique}`,
          {
            cache: "no-store", // optional: if you're using Next.js
          },
        );
        const data = await response.json();
        setProminentList(data.data || []);
        setSelectedOption(data.selected_artwork_prominent_id);
      } catch (error) {
        console.error("Failed to fetch category options:", error);
       
      }
    };
    fetchProminenceList();
  }, []);

  

  return (
    <div className="mx-auto flex w-full flex-col items-center justify-center gap-8 align-middle">
      <div className="mx-auto flex w-full flex-col items-center justify-center gap-2 text-center md:w-3/4">
        <h2 className="vision">
          How <span className="font-medium">prominently</span> should your{" "}
          <span className="font-medium">artwork</span> be displayed ?
        </h2>
        <p className="text-xs/4 font-light md:text-sm">
          Should it be a bold statement or a quiet detail?
        </p>
      </div>

      <div className="cc-vision-wrap">
        <div className="ccvision-scrollcontent">
          <div className="gridItems bottomAlign">
            {prominentList &&
              prominentList.map(({ id, label, image, price }) => {
                const isSelected = selectedOption=== label

                return (
                  <label
                    key={`${label}-${id}`}
                    onClick={() => handleChange(label)}
                    className={`cursor-pointer relative border border-dashed 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="artworkProminentList"
                      value={label}
                      checked={isSelected}
                      onChange={() => {}}
                      className="sr-only"
                    />
                    <div className="flex flex-col items-center p-3">
                      <Image
                        src={`${AWS_CDN_URL}/${image}`}
                        alt={label}
                        width={400}
                        height={400}
                        className="img-responsive"
                        loading="lazy"
                      />
                      <div className="mt-4 items-center justify-center text-center font-light capitalize">
                        <p className="text-sm">{label}</p>
                        <p className="mt-1 text-xs">+ ${price}</p>
                      </div>
                    </div>
                  </label>
                );
              })}
          </div>
        </div>
        {/* MORNI Mode Button */}
        <div className="ccBottomBtnWrap">
          <button
            type="button"
            onClick={resetSelection}
            className={`mt-4 flex w-full flex-col items-center justify-between border-1 border-dashed p-2 text-center transition-all duration-300 ${
              isMorniMode
                ? "border-2 border-green-500 bg-gray-100"
                : "hover:bg-gray-100"
            }`}
          >
            <p className="text-xs/4 font-light">Can{"'"}t pick an option?</p>
            <p className="text-base/4 font-medium uppercase">
              Let MORNI Decide
            </p>
          </button>
        </div>
      </div>
    </div>
  );
}
