"use client";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import TechniqueCheckboxCard from "./../TechniqueCheckboxCard";
import { TechniqueProps } from "./../data/techniqueTypes";
import { FormButton } from "@/app/components/form/forms";
import { getVibeData } from "./../data/vibeData";
import { postFormData } from "@/utils/postFormData";
import { useSearchParams } from "next/navigation";

import { getApiClient } from "@/utils/apiClient";
import { getUserSessionId } from "@/utils/helper";
import withAuth from "@/app/hook/withAuth";

interface Props {
  state: { ItemList?: string };
}

const STORAGE_KEY = "DefineVibe";
const limit = 3;

export default function InspiredDefineVibe({ state }: Props) {
  const [selectedLabels, setSelectedLabels] = useState<string[]>(() => {
    if (typeof window === "undefined") return [];
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      const parsed = JSON.parse(stored || "");
      return Array.isArray(parsed) ? parsed : [];
    } catch {
      return [];
    }
  });

  ///const [selectedLabels, setSelectedLabels] = useState<string[]>([]);

  const [vibeData, setVibeData] = useState<TechniqueProps[]>([]);
  const [loading, setLoading] = useState(true);
  const searchParams = useSearchParams();
  const externalId = searchParams.get("external");

  useEffect(() => {
    getVibeData()
      .then(setVibeData)
      .catch((err) => console.error(err.message || "Failed to load"))
      .finally(() => setLoading(false));
  }, []);

  const [hoveredItem, setHoveredItem] = useState<TechniqueProps | null>(null);

  useEffect(() => {
    if (externalId) {
      fetchExternalWizardData(externalId);
    }
  }, [externalId]);

  const fetchExternalWizardData = async (id: string) => {
    try {
      const apiData = await getApiClient(
        `co-creation/wizard/${id}?session_id=${getUserSessionId()}`,
      );

      if (apiData) {
        const v = apiData.vibes;
        const vv = v?.split(",");
        localStorage.setItem("DefineVibe", JSON.stringify(vv));
        setSelectedLabels(vv);
      }

     
    } catch (error) {
      console.error("Failed to fetch wizard data:", error);
    }
  };

  // Persist vibe data
  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(selectedLabels));
  }, [selectedLabels]);

  const toggleSelection = (label: string) => {
    setSelectedLabels((prevRaw) => {
      const prev = Array.isArray(prevRaw) ? prevRaw : [];
      return prev.includes(label)
        ? prev.filter((l) => l !== label)
        : prev.length < limit
          ? [...prev, label]
          : prev;
    });
  };

  const isDisabled = (label: string) =>
    (Array.isArray(selectedLabels) ? selectedLabels.length : 0) >= limit &&
    !(Array.isArray(selectedLabels) && selectedLabels.includes(label));

  //=========== start code for redirect on store  ============
  const handleStoreLink = () => {
    if (!selectedLabels.length) return;
    const vibeString = selectedLabels.join(",");
    const url = `/category?vibe=${encodeURIComponent(vibeString)}`;
    window.open(url, "_blank", "noopener,noreferrer");
  };

  //=========== end code for redirect on store  =============


  const selectedItems = vibeData.filter((item) =>
    selectedLabels.includes(item.label),
  );

  const handleRemoveChip = (label: string) => {
    setSelectedLabels((prev: string[]) =>
      prev.filter((item) => item !== label),
    );
  };

  return (
    <>
      <div className="mx-auto flex w-full flex-col items-center justify-center text-center md:w-2/3">
        <h2 className="vision">
          Define the <span className="font-medium">vibe</span> of piece
        </h2>
        <p className="text-xs/4 font-light md:text-sm">
          Describe the overall style or intention behind your piece? Select up
          to {limit}.
        </p>
        <div
          className="h-9 w-full overflow-x-auto overflow-y-hidden py-1"
          style={{
            WebkitOverflowScrolling: "touch",
          }}
        >
          <div className="flex min-w-max flex-nowrap gap-1 items-center justify-center">
            {selectedItems.map((item) => (
              <div key={item.id} className="closeable-chip">
                <span className="chip-label">{item.label}</span>
                <button
                  onClick={() => handleRemoveChip(item.label)}
                  className="close-icon"
                >
                  <i className="icon-[iconamoon--close]" />
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="cc-vision-wrap">
        <div className="ccvision-scrollcontent">
          <div className="bottomAlign grid grid-cols-2 gap-2 md:grid-cols-6 md:gap-8">
            {vibeData.length > 0 &&
              vibeData.map((item) => (
                <div
                  key={item.id}
                  className="technique-animbox relative overflow-hidden transition-all duration-100"
                >
                  <TechniqueCheckboxCard
                    item={item}
                    isChecked={
                      Array.isArray(selectedLabels) &&
                      selectedLabels.includes(item.label)
                    }
                    onToggle={() => toggleSelection(item.label)}
                    onHover={setHoveredItem}
                    disabled={isDisabled(item.label)}
                  />
                </div>
              ))}
          </div>
        </div>

        <div className="ccBottomBtnWrap">
          <FormButton
            id="btn_cc_save-preferred_color"
            label="Visit Morni's store"
            type="submit"
            color="gray"
            hairline="blue"
            disabled={
              !Array.isArray(selectedLabels) || selectedLabels.length === 0
            }
            onClick={handleStoreLink}
          />
        </div>
      </div>
    </>
  );
}
