"use client";
import React, { useCallback, useEffect, useState } from "react";
import LikeBtn from "@/app/components/cards/like-btn";
import Breadcrumb from "@/app/components/product/breadcrumb";
import ProductGallery from "@/app/components/product/product-gallery";
import { FormButton } from "@/app/components/form/forms";
import {AWS_CDN_URL } from "@/utils/staticValues";
import Cookies from "js-cookie";
import PdpRecommedation from "@/app/components/product/PdpRecommedation";
import { useRouter } from "next/navigation";
import ScrollToTop from "@/app/components/ScrollToTop";

interface ProductInterface {
  id: string;
  productId: string;
  production_lead_time_days: string;

  product: {
    product_name: string;
    price: string;
    category: {
      name: string;
    };
  };
  main_item_image: {
    image_url: string;
  };
  design_house: {
    name: string;
  };
  product_name: string;
  price: any;
  main_item_images: any;
  category: {
    name: string;
  };
  sub_category: {
    name: string;
  };
  more_like_product: any;
}

interface ProductClientProps {
  /// productId: string;
  initialData?: any;
  slug: string;
}

interface GalleryImage {
  id: number;
  image_url: string | null;
  alt_text: string | null;
}

export default function TechniqueDetailClient({
  slug,
  initialData,
}: ProductClientProps) {
  const [product, setProduct] = useState<ProductInterface | null>(
    initialData?.data?.product || null,
  );
  const router = useRouter();
  const [data, setData] = useState<any>(initialData?.data?.technique || null);
  const [category, setCategory] = useState<any>(initialData?.data?.category || []);
  const [color, setColor] = useState<any>([]);
  const [silhouetteData, setSilhouetteData] = useState<any>();
  const [relatedProducts, setRelatedProducts] = useState<any[]>(initialData?.data?.related_product || []);

  const [galleryImage, setGalleryImage] = useState<GalleryImage[]>(initialData?.data?.gallery || []);

  const handleCustomizeClick = useCallback(async () => {
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/technique/co-creation/${data?.id}`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        },
      );

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

      const r = await response.json();

      sessionStorage.setItem("session_id", r.data.session_id);

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

      if (!token && typeof window !== "undefined") {
        // redirect with current path
        router.push(`/auth/login?redirect=${encodeURIComponent(r.data.url)}`);
      } else {
        window.location.href = r.data.url;
      }
    } catch (error) {
      console.error("Error fetching category list:", error);
    }
  }, [data, router]);

  const handleEnquirySubmit = async (
    e: React.MouseEvent<HTMLButtonElement>,
  ) => {};

  const getProductList = useCallback(async () => {
    // Only fetch if we don't have initial data
    if (initialData) return;
    
    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/technique/${slug}`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });

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

      const data = await response.json();
      setRelatedProducts(data?.data?.related_product || null);
      setData(data?.data?.technique || null);
      setCategory(data?.data?.category || []);

      setGalleryImage(data?.data?.gallery || []);

      return data;
    } catch (error) {
      console.error("Error fetching category list:", error);
    }
  }, [slug, initialData]);

  useEffect(() => {
    // Only fetch if we don't have initial data
    if (!initialData) {
      getProductList();
    }
  }, [initialData, getProductList]);

  return (
    <>
      <ScrollToTop/>
      <div className="wrapper">
        <div className="grid grid-cols-1 md:grid-cols-3">
          <div className="col-span-2">
            <div className="flex w-full overflow-hidden">
              <div className="relative flex w-screen overflow-hidden">
                <div className="relative flex w-full flex-row gap-0.5 overflow-x-auto">
                  <ProductGallery gallery_image={galleryImage} />
                  <div className="absolute right-1 bottom-1 z-40">
                    <div className="rounded-full bg-white/50">
                      {product && <LikeBtn productId={data?.id} wishType="TECHNIQUE"/>}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className="hidden flex-col md:flex">
              <div className="my-8 grid grid-cols-1 gap-8 md:grid-cols-2 md:gap-16">
                {data?.traditional_origin && (
                  <div className="flex flex-col text-xs">
                    <h4 className="med">Traditional Origin</h4>
                    {data?.traditional_origin}
                  </div>
                )}
                {data?.sustainability_impact && (
                  <div className="flex flex-col text-xs">
                    <h4 className="med">Sustainability Impact</h4>
                    {data?.sustainability_impact}
                  </div>
                )}
                {data?.tooling_requirements && (
                  <div className="flex flex-col text-xs">
                    <h4 className="med">Tooling Requirements</h4>
                    {data?.tooling_requirements}
                  </div>
                )}
              </div>
            </div>
          </div>
          <div className="col-span-1 pl-0 md:pl-8">
            <div className="flex flex-col gap-2">
              <div>
                <div className="hidden md:flex">
                  <Breadcrumb category={category?.[0]?.category_name || ""} />
                </div>
                <div className="flex flex-row items-center justify-between align-middle">
                  <div>
                    <h1 className="productTitle mt-4 md:mt-0">
                      {data?.technique_name}
                    </h1>
                  </div>
                  <div>
                    <div className="hidden md:flex">
                      {product && <LikeBtn productId={product?.id} wishType="TECHNIQUE"/>}
                    </div>
                  </div>
                </div>
              </div>
              <div className="flex flex-col [&>div]:border-b-1 [&>div]:border-dashed [&>div]:border-gray-950/25 [&>div]:py-4">
                <div className="flex flex-col text-sm">
                  <div className="text-xs capitalize">Complexity Level</div>
                  {data?.complexity_level}
                </div>
                <div className="flex flex-col">
                  <div className="text-xs capitalize">Category</div>
                  <div className="grid grid-cols-2 gap-1">
                    {category.length > 0 &&
                      category?.map((cat: any) => (
                        <div className="text-sm" key={cat.id}>
                          {cat.category_name}
                        </div>
                      ))}
                  </div>
                </div>
              </div>
              <div className="flex flex-col gap-4">
                <div>
                  <FormButton
                    id="btn_design_buy"
                    label="Start Co-Creation"
                    type="button"
                    color="gray"
                    hairline="amber"
                    onClick={handleCustomizeClick}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="wrapper">
        <div className="flex flex-col md:hidden">
          <div className="my-8 grid grid-cols-1 gap-8 md:grid-cols-2 md:gap-16">
            {data?.traditional_origin && (
              <div className="flex flex-col text-xs">
                <h4 className="med">Traditional Origin</h4>
                {data?.traditional_origin}
              </div>
            )}
            {data?.sustainability_impact && (
              <div className="flex flex-col text-xs">
                <h4 className="med">Sustainability Impact</h4>
                {data?.sustainability_impact}
              </div>
            )}
            {data?.tooling_requirements && (
              <div className="flex flex-col text-xs">
                <h4 className="med">Tooling Requirements</h4>
                {data?.tooling_requirements}
              </div>
            )}
          </div>
        </div>
      </div>
      {Array.isArray(relatedProducts) && relatedProducts.length > 0 && (
        <div className="wrapper">
          <PdpRecommedation
            relatedProducts={relatedProducts}
            heading_name={data?.technique_name}
          />
        </div>
      )}
    </>
  );
}
