"use client";
import Image from "next/image";
import Cookies from "js-cookie";
import { useWizardContext } from "./wizardContext";
import { FormButton } from "@/app/components/form/forms";
import React, { useState, useEffect, useCallback, useMemo } from "react";
import {AWS_CDN_URL } from "@/utils/staticValues";
import { getApiClient } from "@/utils/apiClient";
import { getUserSessionId } from "@/utils/helper";
import { useSearchParams } from "next/navigation";

interface VisionBoardProps {
  jumpToStepId: (stepId: string) => void;
  jumpToNext?: (stepId: string) => void;
}

export interface CategoryItem {
  id?: number;
  name: string;
  slug?: string;
  piece_type: "single" | "twopiece" | "threepiece";
  silhouette?: VBSilhouette;
}

export interface VBSilhouette {
  silhouette_id: number;
  silhouette_name: string;
  silhouette_image: string;
}

export interface SilhouetteItem {
  name: string;
  piece_type: string;
  silhouette: VBSilhouette;
}

export interface VBItem {
  id: number;
  image: string;
  name: string;
}

export interface VBFabric {
  id: number;
  image: string;
  fabric_name: string;
}

export interface TechniqueFamily {
  id: number;
  category_name: string;
  image: string;
}

export interface ArtData {
  id: number;
  preview: string;
  name: string;
  artist_name: string;
}

export interface VisionBoardOption {
  fabric?: VBFabric[];
  technique_family?: TechniqueFamily[];
  prominence?: VBItem;
  silhouette?: SilhouetteItem[];
  color?: string;
  vibe?: VBItem[];
  piece_imagine?: string;
  art_data: ArtData[];
  category?: CategoryItem[];
}

export default function VisionBoard({
  jumpToStepId,
  jumpToNext,
}: VisionBoardProps) {
  const { updateState, state } = useWizardContext();

  const [name, setName] = useState<string | null>(null);
  const [mvbVisible, setMvbVisible] = useState(false);
  const [hasButtonAllowToJumpPayment, setHasButtonAllowToJumpPayment] =
    useState("NO");
  const [artworkMode, setArtworkMode] = useState<string | null>(null);
  const [vbOption, setVbOption] = useState<VisionBoardOption | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [pendingStep, setPendingStep] = useState<string | null>(null);

  const searchParams = useSearchParams();
  const externalId = searchParams.get("external");
  //const externalId = useMemo(() => searchParams.get("external"), [searchParams]);
  const vbShow = useMemo(
    () => searchParams.get("vbshow") === "true",
    [searchParams],
  );

  useEffect(() => {
    const userCookie = Cookies.get("getUser");

    if (userCookie) {
      try {
        const userObj = JSON.parse(userCookie);

        const firstName =
          typeof userObj.name === "string"
            ? userObj.name.trim().split(" ")[0]
            : "";

        setName(firstName);
      } catch (error) {
        console.error("Failed to parse user cookie:", error);
      }
    }
  }, []);

  const fetchVisionBoard = useCallback(async () => {
    if (!externalId) return;

    try {
      setLoading(true);
      const apiData = await getApiClient(
        `co-creation/vision-board?session_id=${getUserSessionId()}&externalId=${externalId}`,
      );

      if (apiData && typeof apiData === "object" && !Array.isArray(apiData)) {
        setVbOption(apiData);
        setHasButtonAllowToJumpPayment(apiData.has_ready_jump_payment_page);

       
      } else {
        console.error("Unexpected API data format:", apiData);
      }
    } catch (error) {
      console.error("Error fetching vision board data:", error);
    } finally {
      setLoading(false);
    }
  }, [externalId]);

  useEffect(() => {
    if (externalId && vbShow) {
      fetchVisionBoard();
      setMvbVisible(true);
    }
  }, [externalId, vbShow, fetchVisionBoard]);

  // Load artwork mode from localStorage
  useEffect(() => {
    const storedArtworkMode = localStorage.getItem("artworkMode");
    setArtworkMode(storedArtworkMode);
  }, []);

  const toggleVisionBoard = () => {
    fetchVisionBoard();
    setMvbVisible((prev) => !prev);
  };

  const hideVisionBoard = () => setMvbVisible(false);

  // ================ start code for display name  ======================
  const fabricColor = vbOption?.color || "#ffffff";
  const silhouetteLength = vbOption?.silhouette?.length || 0;
  //const catName = vbOption?.category?.[0]?.name;
  const piece_type = vbOption?.category?.[0]?.piece_type;
  const silhouetteName = vbOption?.category?.[1]?.silhouette?.silhouette_name;

  const displayName = useMemo(() => {
    if (!vbOption?.silhouette?.length) return "";

    const mainCategory = vbOption.silhouette[0];
    const piece_type = mainCategory?.piece_type ?? "";

    const silhouetteNames: string[] = vbOption.silhouette
      .map((cat) => cat.silhouette?.silhouette_name)
      .filter((name): name is string => !!name); // filter out undefined

    if (piece_type === "single") {
      return silhouetteNames[0] ?? "";
    } else if (piece_type === "twopiece" || piece_type === "threepiece") {
      return silhouetteNames.join(", ");
    }

    return "";
  }, [vbOption]);
  //=============== end code for display name  ====================================
  //=================== start code for handle silhouette =====================
  const piece_id = vbOption?.category?.[1]?.id;
  const handleSilhouetteFlow = () => {
    updateState("CategoryType", piece_type);
    // Add this line to save piece_id to localStorage as subcategoryId
    if (piece_id) {
      localStorage.setItem("subcategoryId", piece_id.toString());
    }

    let targetStepId = "";
    if (piece_type === "twopiece") {
      localStorage.setItem(
        "CategorySingle",
        vbOption?.category?.[1]?.name.toString() || "",
      );
      localStorage.setItem(
        "categoryId",
        vbOption?.category?.[0]?.id?.toString() || "",
      );
      targetStepId = "category_two_piece_top";
    } else if (piece_type === "threepiece") {
      targetStepId = "category_three_piece";
    } else {
      targetStepId = "category_single_child";
    }

    setPendingStep(targetStepId); //// Will trigger jump after context updates
  };

  useEffect(() => {
    if (pendingStep) {
      const timer = setTimeout(() => {
        jumpToStepId(pendingStep);
        setPendingStep(null);
      }, 150);
      return () => clearTimeout(timer);
    }
  }, [pendingStep, jumpToStepId]);

  console.log(
    "hasButtonAllowToJumpPayment:",
    hasButtonAllowToJumpPayment,
    hasButtonAllowToJumpPayment.toString().toLowerCase() === "yes",
  );

  //==================== end code for handle silhouette =====================

  return (
    <>
      <div
        className={`fixed inset-0 top-0 left-0 z-70 flex h-lvh w-full transition-all duration-500 ${
          mvbVisible
            ? "rotate-0 items-center justify-center align-middle"
            : "top-[92vh] left-[6%] -rotate-4 items-start justify-end align-top md:left-[28%] md:-rotate-6"
        }`}
      >
        <div className="mx-auto w-full flex-col border-1 border-gray-950 bg-gray-100 shadow-xl shadow-gray-950/25 transition-all duration-500 md:w-[35%]">
          <div className="grid grid-cols-10 items-center align-middle">
            <div className="col-span-1 flex items-center justify-center align-middle">
              {mvbVisible && (
                <button type="button" className="p-5" onClick={hideVisionBoard}>
                  <span>
                    <i className="icon-[vaadin--close-big]"></i>
                  </span>
                </button>
              )}
            </div>
            <div
              className="col-span-9 cursor-pointer items-end justify-end p-3 md:p-4"
              onClick={toggleVisionBoard}
            >
              <div className="flex w-full justify-end">
                <div className="flex flex-row gap-1 border-b-2 border-gray-950/50 align-bottom">
                  <div className="font-bogart text-sm md:text-lg/6">
                    <span className="capitalize">{name ? name : ""}</span>
                    {"'s"}
                  </div>
                  <div className="w-16 md:w-25">
                    <Image
                      src="/images/morni-logo-black.svg"
                      alt=""
                      width={280}
                      height={60}
                      className="img-responive"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          {loading ? (
            <p></p>
          ) : vbOption ? (
            <div className="relative flex flex-col items-center justify-center gap-4 p-[2vh] align-middle md:gap-0">
              <div className="justify-cente mx-auto grid w-[80%] grid-cols-8 items-center align-middle md:w-[75%]">
                <div className="col-span-3">
                  <div className="relative top-4 flex w-[80%] flex-col">
                    <div className="font-macropolo absolute -top-4.5 -left-0.5 text-sm/3 font-light -tracking-wide capitalize md:text-base/3">
                      Fabric
                    </div>
                    <div
                      className="relative flex w-full cursor-pointer border-1 border-dashed p-1 hover:border-blue-600 hover:bg-blue-100"
                      onClick={() => {
                        hideVisionBoard();
                        jumpToStepId?.("preferred_fabric");
                      }}
                    >
                      {vbOption.fabric && vbOption.fabric.length > 1 && (
                        <div className="absolute -top-2.5 -right-3 z-60 flex h-5 w-5 flex-col items-center justify-center rounded-full border-1 border-dashed bg-gray-100 align-middle text-gray-950">
                          <span className="text-[10px]/3 font-medium">
                            {vbOption.fabric.length === 1 ? null : (
                              <>+{vbOption.fabric.length - 1}</>
                            )}
                          </span>
                        </div>
                      )}

                      <div className="absolute top-0 -right-2 z-50 rotate-45">
                        <Image
                          src="/custom_product/fabric-sticky.png"
                          alt="Fabric Sticky"
                          width={240}
                          height={240}
                          className="img-responsive"
                        />
                      </div>
                      <div className="relative z-10 flex min-h-10 -rotate-2 items-center justify-center text-center align-middle">
                        {vbOption.fabric &&
                        vbOption.fabric.length > 0 &&
                        vbOption.fabric[0].image?.trim() !== "" ? (
                          <Image
                            src={`${AWS_CDN_URL}/${vbOption.fabric[0].image}`}
                            alt={
                              vbOption.fabric[0].fabric_name?.trim() || "fabric"
                            }
                            width={240}
                            height={240}
                            className="img-responsive"
                          />
                        ) : (
                          <span className="flex items-center justify-center align-middle text-[10px]/2">
                            Fabric not chosen
                          </span>
                        )}
                      </div>
                      <div className="absolute -bottom-2 -left-3 z-60 rotate-45">
                        <Image
                          src="/custom_product/fabric-sticky.png"
                          alt="Fabric Sticky"
                          width={240}
                          height={240}
                          className="img-responsive"
                        />
                      </div>
                    </div>
                    <div className="relative z-60 flex w-full flex-col items-center justify-center py-1 text-center">
                      {vbOption.fabric && vbOption.fabric.length > 0 && (
                        <span className="line-clamp-2 text-[10px]/3">
                          {vbOption.fabric[0].fabric_name}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
                <div className="col-span-5">
                  <div className="relative top-[1.5vh] left-10 flex w-1/2 flex-col">
                    <div className="font-macropolo absolute -top-6 left-4 w-[20vh] text-sm/3 font-light -tracking-wide capitalize md:text-base/3">
                      Highlight Artwork
                    </div>
                    <div className="icon-bud-flower-thread absolute -top-4 -left-4 mx-auto h-8 w-8 items-center justify-center bg-gray-950"></div>
                    <div
                      className="flex cursor-pointer flex-row items-center justify-center gap-1 border-1 border-dashed px-4 py-2 align-middle hover:border-blue-600 hover:bg-blue-100"
                      onClick={() => {
                        hideVisionBoard();
                        //handleArtworkMode();
                        jumpToStepId?.("choose_artwork_mode");
                      }}
                    >
                      {vbOption.art_data && vbOption.art_data.length > 1 && (
                        <div className="absolute -top-2 -right-3 z-60 flex h-5 w-5 flex-col items-center justify-center rounded-full border-1 border-dashed bg-gray-100 align-middle text-gray-950">
                          <span className="text-[10px]/3 font-medium">
                            {vbOption.art_data.length === 1 ? null : (
                              <>+{vbOption.art_data.length - 1}</>
                            )}
                          </span>
                        </div>
                      )}
                      <div className="flex min-h-16 w-full -rotate-10 flex-col items-center justify-center text-center">
                        {vbOption.art_data &&
                        vbOption.art_data.length > 0 &&
                        vbOption.art_data[0].preview?.trim() !== "" ? (
                          <div className="flex max-w-full md:max-w-[75%]">
                            <Image
                              src={`${AWS_CDN_URL}/${vbOption.art_data[0].preview}`}
                              alt={
                                vbOption.art_data[0].name?.trim() || "artwork"
                              }
                              width={240}
                              height={240}
                              className="img-responsive"
                            />
                          </div>
                        ) : (
                          <span className="flex items-center justify-center align-middle text-[10px]/2">
                            Artwork not chosen
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="relative z-60 flex w-full flex-col items-center justify-center py-1 text-center">
                      {vbOption.art_data && vbOption.art_data.length > 0 && (
                        <span className="line-clamp-2 text-[10px]/3">
                          {vbOption.art_data[0].name}
                        </span>
                      )}
                    </div>
                    <div className="absolute -right-8 -bottom-[8vh] h-full w-1/3 -rotate-24 md:-right-1/4 md:-bottom-[1vh] md:h-1/3 md:w-1/3">
                      <Image
                        src="/custom_product/line-spiral-arrow.svg"
                        alt="Artwork connect spiral line"
                        width={200}
                        height={300}
                        className="img-responsive"
                      />
                    </div>
                  </div>
                </div>
              </div>
              <div className="flex w-full flex-row items-center justify-center align-middle">
                <div className="relative flex w-1/4 flex-col">
                  <div className="font-macropolo absolute -top-4.5 -left-0.5 text-sm/3 font-light -tracking-wide capitalize md:text-base/3">
                    Vibe
                  </div>
                  <div
                    className="flex w-full cursor-pointer flex-row items-center justify-center border-1 border-dashed p-2 text-center align-middle text-xs/3 hover:border-blue-600 hover:bg-blue-100"
                    onClick={() => {
                      hideVisionBoard();
                      jumpToStepId?.("define_vibe");
                    }}
                  >
                    {vbOption.vibe && vbOption.vibe.length > 0 ? (
                      vbOption.vibe.map((item) => item.name).join(", ")
                    ) : (
                      <span className="text-[10px]/2">Vibe not chosen.</span>
                    )}
                  </div>
                </div>
                <div className="flex w-1/2 flex-col">
                  <div
                    className="relative grid w-full cursor-pointer grid-cols-9 border border-dashed border-transparent p-1 hover:border-blue-600 hover:bg-blue-100 md:top-4"
                    onClick={() => {
                      hideVisionBoard();
                      handleSilhouetteFlow();
                    }}
                  >
                    <div className="relative col-span-2 flex items-center justify-center">
                      <div className="relative flex h-full w-full items-center justify-center overflow-visible">
                        <div className="absolute top-1/2 left-1/2 flex -translate-x-1/2 -translate-y-1/2 rotate-[-90deg]">
                          <div className="font-bogart line-clamp-2 max-h-[5vh] w-[25vh] overflow-hidden px-6 text-center text-xs leading-tight font-light capitalize md:px-3 md:text-sm/4">
                            {displayName}
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="col-span-7">
                      <div className="vBSilhouetteWrapper relative flex h-[20vh] w-full flex-col items-center justify-center align-middle md:h-[30vh]">
                        {vbOption.silhouette && silhouetteLength > 0 ? (
                          vbOption.silhouette.map((s, index) => {
                            const silhouette = s.silhouette;
                            if (!silhouette) return null;

                            const {
                              silhouette_id,
                              silhouette_name,
                              silhouette_image,
                            } = silhouette;

                            const imageUrl = `${AWS_CDN_URL}/${silhouette_image}`;

                            return (
                              <div
                                key={silhouette_id || index}
                                className={`absolute mx-auto ${
                                  silhouetteLength === 2
                                    ? "vBSilhouette w-1/2 md:w-[48%]"
                                    : "w-[90%]"
                                }`}
                              >
                                <Image
                                  src={imageUrl}
                                  alt={silhouette_name}
                                  width={600}
                                  height={1000}
                                  className="img-responsive"
                                />
                              </div>
                            );
                          })
                        ) : (
                          <span className="font-hasiant flex min-h-40 w-full items-center justify-center text-center align-middle text-6xl/4">
                            Silhouette
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="relative flex w-1/4 flex-col items-end justify-end gap-1 align-middle md:gap-0">
                  <div
                    className="relative top-0 mx-auto flex w-full flex-col border-1 border-dashed p-1 hover:border-blue-600 hover:bg-blue-100 md:-top-[4vh] md:w-4/5"
                    onClick={() => {
                      hideVisionBoard();
                      jumpToStepId?.("technique");
                    }}
                  >
                    <div className="font-macropolo absolute -top-[2vh] -left-1 text-sm/3 font-light -tracking-wide capitalize md:-top-[2vh] md:text-base/3">
                      Technique
                    </div>
                    <div className="absolute -top-2 -right-2 z-2 w-[40%]">
                      <div>
                        <Image
                          src="/custom_product/fabric-sticky.png"
                          alt="Fabric Sticky"
                          width={240}
                          height={240}
                          className="img-responsive"
                        />
                      </div>
                    </div>
                    <div className="relative mx-auto flex cursor-pointer flex-col gap-1 text-center shadow-xs">
                      {vbOption.technique_family &&
                        vbOption.technique_family.length > 1 && (
                          <div className="absolute -top-4 -right-4 z-60 flex h-5 w-5 flex-col items-center justify-center rounded-full border-1 border-dashed bg-gray-100 align-middle text-gray-950">
                            <span className="text-[10px]/3 font-medium">
                              {vbOption.technique_family.length === 1 ? null : (
                                <>+{vbOption.technique_family.length - 1}</>
                              )}
                            </span>
                          </div>
                        )}
                      <div className="flex w-full bg-white p-1 shadow-sm">
                        {vbOption.technique_family &&
                        vbOption.technique_family.length > 0 ? (
                          <Image
                            src={`${AWS_CDN_URL}/${vbOption.technique_family[0].image}`}
                            alt={
                              vbOption.technique_family[0].category_name ||
                              "Craft family"
                            }
                            width={240}
                            height={240}
                            className="img-responsive"
                          />
                        ) : (
                          <span className="flex min-h-10 items-center justify-center align-middle text-[10px]/2"></span>
                        )}
                      </div>
                      <span className="text-[10px]/3">
                        {vbOption.technique_family &&
                        vbOption.technique_family.length > 0
                          ? vbOption.technique_family[0].category_name
                          : ""}
                      </span>
                    </div>
                  </div>
                  <div className="relative flex flex-col gap-2 md:gap-0">
                    <div className="absolute -top-[1vh] -right-2 h-[10%] w-[10%] rotate-12 md:-top-[3.5vh] md:right-3">
                      <Image
                        src="/custom_product/curve-down-arrow.svg"
                        alt="Curve Arrow technique connect"
                        width={200}
                        height={200}
                        className="img-responsive"
                      />
                    </div>
                    <div
                      className="relative mx-auto flex w-full cursor-pointer gap-0 border-1 border-dashed p-1 hover:border-blue-600 hover:bg-blue-100 md:w-4/5"
                      onClick={() => {
                        hideVisionBoard();
                        jumpToStepId?.("artwork_prominent");
                      }}
                    >
                      <div className="flex min-h-20 w-full flex-col items-center justify-center gap-1 text-center">
                        {vbOption.prominence &&
                        vbOption.prominence.name?.trim() !== "" ? (
                          <>
                            <div>
                              <Image
                                src={`${AWS_CDN_URL}/${vbOption.prominence.image}`}
                                alt={vbOption.prominence.name}
                                width={240}
                                height={400}
                                className="img-responsive"
                              />
                            </div>
                            <span className="text-[10px]/2">
                              {vbOption.prominence.name}
                            </span>
                          </>
                        ) : (
                          <span className="text-[10px]/2">
                            Artwork prominence not chosen.
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="font-macropolo absolute -bottom-[3vh] w-[20vh] text-sm/3 font-light -tracking-wide capitalize md:-bottom-[2.5vh] md:left-2 md:text-base/3">
                      Artwork
                      <br />
                      Prominence
                    </div>
                  </div>
                </div>
              </div>
              <div className="mx-auto flex w-full flex-row items-center justify-center gap-2 align-middle">
                <div
                  className="relative -top-[6vh] -left-[5vh] flex cursor-pointer flex-col px-4"
                  onClick={() => {
                    hideVisionBoard();
                    jumpToStepId?.("preferred_fabric_color");
                  }}
                >
                  <div className="ml-[3vh] h-20 w-20 border-1 border-dashed p-1 hover:border-blue-600 hover:bg-blue-100 md:ml-[8%] md:h-25 md:w-25">
                    <div className="relative h-full w-full overflow-hidden">
                      <div>
                        <Image
                          src="/custom_product/bg-fabric-flower.png"
                          alt="Fabric Color"
                          width={200}
                          height={200}
                          className="img-responsive"
                        />
                      </div>
                      <div className="absolute top-[8.5%] left-[7.5%] isolate z-10 h-[94%] w-[95%]">
                        <div
                          className="icon-cc-fabric-flower h-[100%] w-[100%]"
                          style={{
                            backgroundColor: fabricColor,
                            mixBlendMode: "multiply",
                            opacity: 0.88,
                          }}
                        ></div>
                      </div>
                    </div>
                  </div>
                  <div className="font-macropolo absolute -bottom-4 left-[4.5vh] text-sm/3 font-light -tracking-wide capitalize md:left-5.5 md:text-base/3">
                    Fabric Color
                  </div>
                </div>
                <div className="relative top-[3vh] -left-[4vh] flex w-[60%] flex-col md:top-[2vh] md:left-0">
                  <div className="font-macropolo relative -top-1 -left-1 text-sm/3 font-light -tracking-wide capitalize md:text-base/3">
                    Where do you want to wear this?
                  </div>
                  <div
                    className="flex w-full cursor-pointer flex-col items-center justify-center border-1 border-dashed p-2 text-center align-middle text-[10px]/2.5 font-light -tracking-wider hover:border-blue-600 hover:bg-blue-100"
                    onClick={() => {
                      hideVisionBoard();
                      jumpToStepId?.("piece_imagine_artwork");
                    }}
                  >
                    <span className="line-clamp-3">
                      {vbOption.piece_imagine &&
                      vbOption.piece_imagine.trim() !== ""
                        ? vbOption.piece_imagine
                        : "Not added yet"}
                    </span>
                  </div>
                </div>
              </div>

              {hasButtonAllowToJumpPayment === "YES" ? (
                <div className="mx-auto flex w-full items-center justify-center align-middle">
                  <div className="relative flex w-1/2 pb-4">
                    <FormButton
                      id="btn_cc_save-preferred_color"
                      label="Finalize"
                      type="button"
                      color="gray"
                      hairline="blue"
                      onClick={() => {
                        hideVisionBoard();
                        jumpToStepId?.("guidance_order_summary");
                      }}
                    />
                  </div>
                  <button
                    type="button"
                    className="hidden bg-gray-950 px-10 py-1 text-white uppercase"
                  >
                    Create enabled
                  </button>
                </div>
              ) : (
                <div className="mx-auto flex w-full items-center justify-center align-middle">
                  <div className="relative flex w-1/2 pb-4">
                    <FormButton
                      id="btn_cc_save-preferred_color"
                      label="Create Disabled"
                      type="button"
                      color="gray"
                      hairline="blue"
                    />
                  </div>
                  <button
                    type="button"
                    className="hidden bg-gray-950 px-10 py-1 text-white uppercase"
                    disabled
                    title="You need to complete the previous steps before creating your vision board."
                  >
                    Finalize
                  </button>
                </div>
              )}
            </div>
          ) : (
            <p className="pt-4 pb-8 text-center text-xs font-light">
              No vision board data available.
            </p>
          )}
        </div>
      </div>
    </>
  );
}
