"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Cookies from "js-cookie";
import { FormButton } from "@/app/components/form/forms";
import CCPageBg from "@/app/components/coCreationJourney/pageBg";
import ConfirmExitModal from "@/app/components/coCreationJourney/ConfirmExitModal";

import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination } from "swiper/modules";
import "swiper/css";
import "swiper/css/pagination";
import withAuth from "@/app/hook/withAuth";
import { getUserFromCookie } from "@/utils/helper";
import { getApiClient } from "@/utils/apiClient";

const journeyLimit = 10;

function DesignJournery() {
  const router = useRouter();
  const [name, setName] = useState<string | null>(null);
  const [pastRecords, setPastRecords] = useState<any[]>([]);
  const [savedJourney, setSavedJourney] = useState<string>("");
  const [showExitModal, setShowExitModal] = useState(false);
  const [selectedOptionId, setSelectedOptionId] = useState<string | null>(null);

  useEffect(() => {
    // Get the cookie value
    const userCookie = Cookies.get("getUser");

    if (userCookie) {
      try {
        const userObj = JSON.parse(userCookie);
        setName(userObj.name);
      } catch (error) {
        console.error("Failed to parse user cookie:", error);
      }
    }
  }, []);

  const handleJourney = (id: string, path: string, session_id: string) => {
    sessionStorage.setItem("session_id", session_id);
    setSavedJourney(id);
    router.push(path);
  };

  useEffect(() => {
    const user = getUserFromCookie();
    historyRecords();
  }, []);

  const historyRecords = async () => {
    try {
      const records = await getApiClient("co-creation/index");

      setPastRecords(records);
    } catch (error) {
      //console.error("Error fetching past records:", error);
      setPastRecords([]);
    }
  };

  const handleGetStarted = () => {
    const keysToRemove: string[] = [
      "DefineVibe",
      "genderExpression",
      "categoryName",
      "CategoryType",
      "categoryId",
      "CategorySingle",
      "subcategoryId",
      "silhouette",
      "categorySingleChild",
      "bottomSilhouetteId",
      "bottomCategoryId",
      "outwearCategoryId",
      "CategoryTwoPiece",
      "piece_imagine",
      "artworkPlacement",
      "CategoryTwoPiece",
      "CategoryThreePieceTop",
      "CategoryThreePieceBottom",
      "CategoryThreePieceVest",
      "preferredColor",
      "fabricFamily",
      "preferredFabric",
      "artworkMode",
      "MorniPickPiece",
      "technique_category",
      "ImageData_ArtworkHighlight",
      "preferredFabric",
      "artworkMode",
      "MorniArtCollection",
      "artworkProminent",
      "artworkPlacement",
      "piece_imagine",
      "categoryBasic",
      "ImageData_visionReferenceImages",
      "shareReferenceNote",
      "DesribeVision",
      "more_inspiration_links",
    ];

    Object.keys(localStorage).forEach((key) => {
      if (keysToRemove.includes(key)) {
        localStorage.removeItem(key);
      }
    });

    const sessionId = generateSessionId();

    router.push("/design-journey");
  };

  const generateSessionId = () => {
    const sessionId = crypto.randomUUID(); // Or any random generator
    sessionStorage.setItem("session_id", sessionId);
    return sessionId;
  };

  return (
    <>
      <CCPageBg />
      <div className="inset fixed top-0 left-0 z-60 flex h-lvh w-full flex-col items-center justify-center align-middle">
        <div className="mx-auto flex w-[94%] flex-col gap-6 md:w-[50%]">
          <div className="mx-auto flex w-full flex-col items-center justify-center gap-2 text-center">
            <div className="icon-thread-eye h-18 w-20 bg-gray-950 md:h-22 md:w-24"></div>
            <h1 className="med font-light">
              Welcome to your co-creation journey{", "}
              {name ? name : ""}
            </h1>
            <h4 className="font-light">
              Let{"'"}s shape something uniquely yours.
            </h4>
          </div>
          <div className="mx-auto flex w-full flex-col items-center justify-between gap-2 text-center text-xs/4">
            <p className="font-light">
              We believe the most meaningful{" "}
              <span className="font-medium text-blue-600">
                pieces begin with a story — yours
              </span>
              . This form is a space for you to share what inspires you, what
              moves you, and what you dream of wearing.
            </p>
            <p className="font-light">
              It{"'"}s a gentle beginning to a thoughtful process — one where{" "}
              <span className="font-medium text-blue-600">
                your vision leads, and our craftsmanship follows
              </span>
              .
            </p>
          </div>
          <div className="flex w-full">
            <Swiper
              slidesPerView={1.25}
              spaceBetween={4}
              breakpoints={{
                640: { slidesPerView: 2.125, spaceBetween: 16 },
              }}
              modules={[Pagination]}
              pagination={{ clickable: true }}
              className="fabricCatNavItem"
            >
              {pastRecords &&
                pastRecords.map((option, index) => (
                  <SwiperSlide key={option.id} className="relative mb-8">
                    <button
                      type="button"
                      onClick={() => {
                        setSelectedOptionId(option.id);
                        setShowExitModal(true);
                      }}
                      className="absolute -top-0 -right-1 z-10 flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border-gray-950/25 bg-gray-100 align-middle"
                    >
                      <i className="icon-[mingcute--close-fill]"></i>
                    </button>
                    <label className="relative mt-4 flex cursor-pointer border-1 border-dashed border-gray-950/25 bg-gray-100/50 transition-all duration-200 hover:border-gray-950 hover:bg-gray-100">
                      <input
                        type="radio"
                        name="navigation"
                        value={option.id}
                        checked={savedJourney === option.id}
                        onChange={() =>
                          handleJourney(
                            option.id,
                            option.redirection_path,
                            option.session_id,
                          )
                        }
                        className="sr-only"
                      />

                      <span
                        className="absolute top-0 left-0 h-1 w-full bg-green-400"
                        style={{ width: option.finishPercent + "%" }}
                      ></span>
                      <div className="flex w-full flex-col">
                        <div className="flex flex-col p-4 pt-6">
                          <div className="flex flex-row justify-between align-middle">
                            <div className="font-bogart text-base uppercase">
                              {option.co_creation_invoice_id}
                            </div>
                            <div className="text-xs font-medium -tracking-wider underline underline-offset-4">
                              Finish Now!
                            </div>
                          </div>
                          <div className="flex flex-col pt-1 text-xs">
                            <div className="flex flex-row justify-between gap-2 capitalize">
                              <span className="font-medium">vibe</span>
                              <p>{option.vibes}</p>
                            </div>
                            {/* <div className="flex flex-row justify-between gap-2 capitalize">
                              <span className="font-medium">
                                Gender Expression
                              </span>
                              <p>{option.gender}</p>
                            </div> */}
                            <div className="flex flex-row justify-between gap-2 capitalize">
                              <span className="font-medium">Category</span>
                              <p>{option.category_data?.name}</p>
                            </div>
                            <div className="flex flex-row justify-between gap-2 capitalize">
                              <span className="font-medium">Sub Category</span>
                              <p>{option.category_tree?.[1]?.name || "N/A"}</p>
                            </div>
                            <div className="flex flex-row justify-between gap-2 capitalize">
                              <span className="font-medium">Last Modified</span>
                              <p>{option.last_modified_date}</p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </label>
                  </SwiperSlide>
                ))}
            </Swiper>
          </div>

          {pastRecords && pastRecords.length <= journeyLimit - 1 ? (
            <div className="flex flex-col items-center justify-center text-center">
              <p className="text-sm">
                You can create up to {journeyLimit} co-creations.
              </p>
              <FormButton
                id="btn_save_new_address"
                label="Get Started"
                type="button"
                color="gray"
                hairline="blue"
                disabled={false}
                onClick={handleGetStarted}
              />
            </div>
          ) : (
            <p className="text-center text-xs/4 font-light">
              Looks like you{"'"}ve reached your{" "}
              <span className="font-medium text-blue-600">
                {journeyLimit}-journey limit
              </span>
              . Complete a current journey to unlock space for a new one.
            </p>
          )}
        </div>
      </div>
      <ConfirmExitModal
        isOpen={showExitModal}
        headingText="Delete this Vision Board"
        title=""
        cancelText="Do Not delete"
        confirmText="Yes, Confirm"
        message="Are you sure? Deleting your vision board will permanently erase this vision board design and data."
        onConfirm={async () => {
          if (!selectedOptionId) return;
          try {
            await getApiClient(`co-creation/del/${selectedOptionId}`);
            setPastRecords((prev) =>
              prev.filter((item) => item.id !== selectedOptionId),
            );
          } catch (error) {
            console.error("Delete failed:", error);
          }
          setShowExitModal(false);
        }}
        onCancel={() => {
          console.log("Cancelled:", selectedOptionId);
          setShowExitModal(false);
        }}
      />
    </>
  );
}

export default withAuth(DesignJournery);
