"use client";
import { use, useEffect, useState, Suspense, lazy, useCallback } from "react";
import Image from "next/image";
import Link from "next/link";
import { AWS_CDN_URL } from "@/utils/staticValues";
import Cookies from "js-cookie";
import "@/app/components/design-houses/dhStyle.css";
import { useRouter } from "next/navigation";
import { getCoCreationUrl } from "./actions";
const StoreThumbs = lazy(
  () => import("@/app/components/co-creation/cc-store-thumbs"),
);

const ImageSwiperDH = lazy(
  () => import("@/app/components/design-houses/dh-img-swipter"),
);
const DHTeam = lazy(() => import("@/app/components/design-houses/dh-team"));

const CcDesignHouseList = lazy(
  () => import("@/app/components/co-creation/cc-design-house-list"),
);

interface dhDTO {
  id: any;
  name: any;
  pieces_bio: any;
  logo: any;
  profile_images: any;
  based_in_city: any;
  bio_image: any;
  bio: any;
  herobgfrom: string;
  herolbgvia: string;
  herolbgto: string;
  pageBg: string;
  font_color: string;
  primary_color: string;
  secondary_color: string;
  hlgtColor: string;
  hexcode_for_bg: string;
  hexcode_for_button: string;
  hero_bg_from: string;
  hero_bg_to: string;
  hero_bg_via: string;
  high_light_color: string;
  organization_id: string;
  thumbnail_image: string;
}
export default function DesignHouseDeails(props: any) {
  const router = useRouter();
  const [dh, setDh] = useState<dhDTO>();
  const [artisan, setArtisan] = useState([]);
  const [products, setProducts] = useState([]);
  const [hallMark, setHallMark] = useState<string[]>([]);
  const [otherDesignHouse, setOtherDesignHouse] = useState([]);

  const { initialData } = props;
  console.log("props:", props);
  // const getDesignHouseProfile = useCallback(async () => {
  //   try {
  //     alert('Fetching design house profile...');
  //     const response = await fetch(
  //       `${API_BASE_URL}/design-detail?slug=${slug}`,
  //       {
  //         method: "GET",
  //         headers: { "Content-Type": "application/json" },
  //       },
  //     );

  //     if (!response.ok) {
  //       throw new Error(`Error: ${response.status} - ${response.statusText}`);
  //     }

  //     const data = await response.json();
  //     setDh(data.data.design_house);
  //     setProducts(data.data.products);
  //     setArtisan(data.data.artisans);
  //     setOtherDesignHouse(data.data.other_design_house);

  //     //console.log(data);

  //     const hallmarks = data?.data?.design_house?.hallmarks ?? "";
  //     const items = hallmarks.split(",").map((item: string) => item.trim());
  //     setHallMark(items);
  //   } catch (error) {
  //     console.error("Error fetching category list:", error);
  //   }
  // }, [slug]); // Add slug as a dependency for useCallback

  useEffect(() => {
    if (initialData) {
      setDh(initialData.data.design_house);
      setProducts(initialData.data.products);
      setArtisan(initialData.data.artisans);
      setOtherDesignHouse(initialData.data.other_design_house);

      const hallmarks = initialData?.data?.design_house?.hallmarks ?? "";
      const items = hallmarks.split(",").map((item: string) => item.trim());
      setHallMark(items);
    }
  }, [initialData]);

  // useEffect(() => {
  //   getDesignHouseProfile();
  // }, [getDesignHouseProfile]);

  const pageBg = dh?.hexcode_for_bg || "#ffffff";
  const herobgfrom = dh?.hero_bg_from || "#F3F2D7";
  const herolbgto = dh?.hero_bg_to || "#F3F2D7";
  const herolbgvia = dh?.hero_bg_via || "#F3F2D7";
  const primaryColor = dh?.primary_color || "#F3F2D7";
  const secondaryColor = dh?.secondary_color || "#F3F2D7";
  const fontColor = dh?.font_color || "#121212";
  const hlgtColor = dh?.high_light_color || "#F3F2D7";
  const btnColor = dh?.hexcode_for_button || "#F3F2D7";

  const handleCocreation = useCallback(async () => {
    if (!dh?.id) return;
    try {
      const result = await getCoCreationUrl(dh.organization_id);

      if (!result.success) {
        console.error("Error fetching co-creation URL:", result.error);
        return;
      }

      sessionStorage.setItem("session_id", result.sessionId);

      const token = Cookies.get("token");

      if (!token && typeof window !== "undefined") {
        router.push(`/auth/login?redirect=${encodeURIComponent(result.url)}`);
      } else {
        window.location.href = result.url;
      }
    } catch (error) {
      console.error("Error handling co-creation:", error);
    }
  }, [dh?.id, dh?.organization_id, router]);

  const exploreMorePieces = () => {
    router.push(`/category?design_house=${dh?.name}`);
  };

  return (
    <>
      <div
        className="pageWrap flex flex-col overflow-hidden pt-12"
        style={
          {
            "--hero-bg-from": herobgfrom,
            "--hero-bg-via": herolbgvia,
            "--hero-bg-to": herolbgto,
            "--page-bg": pageBg,
            "--primary-color": primaryColor,
            "--secondary-color": secondaryColor,
            "--font-color": fontColor,
            "--btn-color": btnColor,
            "--hlgt-color": hlgtColor,
          } as React.CSSProperties
        }
      >
        <div className="dh-hero relative">
          <div className="mob-noise absolute top-0 left-0 h-full w-full"></div>
          <div className="wrapper relative z-30">
            <div className="btnLink mt-2 inline-flex">
              <Link
                href="/co-creation"
                id="link_view_all_design-house"
                className="inline-flex py-2 text-xs underline underline-offset-6 duration-300"
              >
                View all design houses
              </Link>
            </div>
            <div className="mx-auto flex h-full w-full flex-col items-center justify-center gap-2 pb-20 md:w-[75%]">
              {dh?.logo && (
                <div>
                  <Image
                    src={`${AWS_CDN_URL}/${dh.logo}`}
                    width={128}
                    height={128}
                    alt="logo"
                    className="img-responsive"
                  />
                </div>
              )}
              <h1 className="hero-title">{dh?.name}</h1>
              <div className="font-bogart hero-sub-title text-md align-middle">
                <span className="top:0 relative mr-1 md:top-0.5">
                  <i className="icon-[bx--map]"></i>
                </span>
                {dh?.based_in_city}
              </div>
              <ul className="list-chips mt-5 tracking-wider *:text-sm/5">
                {hallMark &&
                  hallMark.map((item, index) => <li key={index}>{item}</li>)}
              </ul>
              <div className="flex w-full pt-5 md:w-[30%]">
                <div className="btn-hairline relative flex w-full flex-col">
                  <button
                    className="relative z-20 flex h-12 w-full justify-center px-6 py-3 align-middle font-medium tracking-wider uppercase duration-300"
                    onClick={() => handleCocreation()}
                  >
                    Create with us
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <Suspense>
          <ImageSwiperDH dhGallery={dh?.profile_images} />
        </Suspense>

        <div className="dh-intro-highlight relative py-16">
          <div className="mob-noise absolute top-0 left-0 z-10 h-full w-full"></div>
          <div className="wrapper">
            <div className="relative z-20 grid grid-cols-1 items-center md:grid-cols-2">
              <div className="mx-auto flex w-full flex-col">
                <p className="font-bogart text-lg/6 font-light tracking-wide md:text-2xl/6">
                  {dh?.bio}
                </p>
              </div>
              <div className="flex w-full items-end justify-end">
                <div className="flex w-6/10 flex-col">
                  <div className="border border-gray-950">
                    {dh?.thumbnail_image && (
                      <Image
                        src={`${AWS_CDN_URL}/${dh.thumbnail_image}`}
                        height={640}
                        width={640}
                        alt="motif"
                        className="img-responsive"
                      />
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="sec-feature-collection relative flex w-full flex-col">
          <div className="mob-noise absolute top-0 left-0 h-full w-full"></div>
          <div className="relative z-20 py-15 md:py-25">
            <div className="wrapper sec-collection">
              <div className="mx-auto flex w-full flex-col gap-8 text-center md:w-[60%]">
                <h1>
                  Featured
                  <br />
                  pieces
                </h1>
                <p className="font-bogart text-xl font-light">
                  {dh?.pieces_bio}
                </p>
              </div>
            </div>
            <div className="wrapper mt-10">
              <div className="grid grid-cols-1 gap-20 md:grid-cols-3">
                <Suspense>
                  <StoreThumbs products={products} />
                </Suspense>
              </div>
              <div className="mt-8 flex w-full flex-col items-center justify-center align-middle">
                <div className="btn-hairline relative">
                  <button
                    className="relative z-20 flex h-12 w-full justify-center px-6 py-3 align-middle font-medium tracking-wider uppercase duration-300"
                    onClick={() => exploreMorePieces()}
                  >
                    Explore more pieces
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="sec-dh-team relative flex w-full flex-col py-10 md:py-25">
          <div className="mob-noise absolute top-0 left-0 h-full w-full"></div>
          <div className="relative z-20 mx-auto flex w-full flex-col justify-between gap-8 md:flex-row">
            <div className="mx-auto flex w-full flex-col gap-4 px-[10%] text-center md:w-[30%] md:px-0 md:pl-[10%] md:text-left">
              <p className="heading-title team-heading font-light">
                Meet the team
              </p>
              <p className="team-subHeading text-sm">
                Get to know the minds, hearts, and hands who craft your pieces.
              </p>
            </div>
            <div className="flex w-full items-center justify-center md:w-[70%]">
              <Suspense>
                <DHTeam teamMembers={artisan} />
              </Suspense>
            </div>
          </div>
        </div>

        <div className="designHouseWrap relative">
          <div className="mob-noise absolute top-0 left-0 h-full w-full"></div>
          <div className="wrapper relative z-20 py-20">
            <div className="heading-title">
              EXPLORE OTHER
              <br />
              Design HOUSES
            </div>
            <Suspense>
              <CcDesignHouseList otherCoCreator={otherDesignHouse} />
            </Suspense>
          </div>
        </div>
      </div>
    </>
  );
}
