"use client";
import { useParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { getService, getServiceProducts } from "@/lib/actions/serviceAction";
import { useAppSelector } from "@/app/store/hooks";
import { useTranslations } from "next-intl";
import { SERVICE_FORM_TYPE, transformCategoryData } from "@/lib/formTypes";
import { IoIosArrowForward } from "react-icons/io";
import Link from "next/link";
import BreadCrumb from "@/components/Breadcrumb";
import ProductSection from "@/components/ProductSection";
import {
  MobileNumber,
  OtherAttribute,
  OtherAttributeMeta,
} from "../../../../../types/common-types";
import { getOtherAttributeImageUrl } from "@/hooks/useImageUrl";
import DataNotFound from "@/components/common/DataNotFound";
import RouteLoader from "@/components/common/RouteLoader";

// interface Creator {
//   email: string;
//   first_name: string;
//   last_name: string;
//   profile_image?: string;
//   _id: string;
// }

// interface ServiceDetail {
//   _id: string;
//   jobTitle: string;
//   jobDescription: string;
//   employmentType: string;
//   salary: string;
//   location: string;
//   cityOrState: string;
//   contactNumber: string;
//   createdAt: string;
//   creator: Creator;
//   image?: string;
// }

type Product = {
  productId: string;
  title: string;
  description: string;
  price: number;
  otherAttribute: {
    content:
      | OtherAttribute<"mobile_number">
      | OtherAttribute<"vehicle_number_plate">;
    meta: OtherAttributeMeta;
    valueType: string;
  } | null;
  file_url: string | null;
  createdAt: string;
  isWishlisted: boolean;
  totalNumberOfViews: number;
  distance: number;
  creator: {
    _id: string;
    first_name: string;
    middle_name: null | string;
    last_name: string;
    email: string;
    profile_image: string | null;
  };
};

type ProductCard = {
  id: string;
  title: string;
  description: string;
  price: string | number;
  time: string;
  location: string;
  imageUrl: string | null;
  slug: string;
  isWishlisted: boolean;
  totalNumberOfViews: number;
  distance: number;
  createdAt: string;
  creator: {
    id: string;
    name: string;
    email: string;
    profileImage: string | null;
  } | null;
  isOtherAttribute: boolean;
  otherAttribute: Product["otherAttribute"];
};

export default function ServiceDetail() {
  const params = useParams();
  const t = useTranslations();
  const { user } = useAppSelector((state) => state.auth);
  const [service, setService] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [products, setProducts] = useState<ProductCard[] | null>(null);

  if (!params.id) {
    return <>{t("no_id_provided")}</>;
  }

  const getPrice = (
    otherAttribute: any,
    price: number,
    valueType: string | undefined
  ) => {
    if (!otherAttribute) {
      return price;
    }

    if (valueType === "mobile_number") {
      let mobileAttr = otherAttribute?.content[0] as MobileNumber;
      return mobileAttr?.price;
    }

    return price;
  };

  const transformProducts = (data: Product[]) => {
    const transformed = data.map((product) => {
      return {
        id: product.productId,
        title: product.title || t("untitled_product"),
        description: product.description || "",
        price: getPrice(
          product.otherAttribute,
          product.price,
          product.otherAttribute?.valueType
        ),

        time: product.createdAt || t("recently_Added"),
        location: t("home_page.location_not_specified"),
        imageUrl: getOtherAttributeImageUrl(product),
        slug: product.productId,
        isWishlisted: product.isWishlisted || false,
        totalNumberOfViews: product.totalNumberOfViews || 0,
        distance: product.distance,
        createdAt: product.createdAt,
        creator: product.creator
          ? {
              id: product.creator._id,
              name: [
                product.creator.first_name,
                product.creator.middle_name,
                product.creator.last_name,
              ]
                .filter(Boolean)
                .join(" "),
              email: product.creator.email,
              profileImage: product.creator.profile_image,
            }
          : null,
        isOtherAttribute: product.otherAttribute ? true : false,
        otherAttribute: product.otherAttribute,
        productType: product.otherAttribute
          ? product.otherAttribute.valueType
          : "product",
      };
    });

    return transformed;
  };

  useEffect(() => {
    const loadService = async () => {
      try {
        setLoading(true);

        const [serviceResponse, productsResponse] = await Promise.all([
          getService({
            serviceId: params.id as string,
          }),
          getServiceProducts(user?.token, {
            serviceId: params.id as string,
          }),
        ]);

        if (serviceResponse?.success) {
          const serviceData = serviceResponse?.data?.service;
          const createdBy = serviceResponse?.data?.createdBy;

          const finalData = transformCategoryData(serviceData);

          (finalData as any).creator = createdBy;

          setService([finalData]);
        }

        if (productsResponse.success) {
          const finalData = transformProducts(productsResponse.data || []);
          if (finalData && finalData.length > 0) {
            setProducts(finalData);
          }
        }
      } catch (err) {
        setError(t("fetch_to_failed_service"));
      } finally {
        setLoading(false);
      }
    };

    loadService();
  }, [params?.id]);

  const isDesktop = typeof window !== "undefined" && window.innerWidth >= 1280;
  const isLaptop = typeof window !== "undefined" && window.innerWidth >= 1024;
  const isTabletPro =
    typeof window !== "undefined" &&
    window.innerWidth >= 768 &&
    window.innerWidth < 1024;
  const isTablet =
    typeof window !== "undefined" &&
    window.innerWidth >= 640 &&
    window.innerWidth < 768;

  const skeletonCount = useMemo(() => {
    if (isDesktop) return 6;
    if (isLaptop) return 5;
    if (isTabletPro) return 3;
    if (isTablet) return 3;
    return 2; // Mobile
  }, [isDesktop, isLaptop, isTabletPro, isTablet]);

  if (loading) {
    return (
      <>
        <div className="px-6">
          <div className="max-w-w1660 mx-auto relative">
            <div className="pt-3 pb-4 animate-pulse">
              <div className="border border-neutrals100 rounded-lg overflow-hidden bg-white dark:bg-card dark:border-card">
                {/* LEFT LOGO SKELETON */}
                <div className="p-6 flex items-center justify-center bg-primary50 dark:bg-primary700">
                  <div className="w-full h-96 max-lg:h-72 max-md:h-60 max-md:mt-0 bg-gray-200 rounded-md dark:bg-gray-700" />
                </div>

                {/* RIGHT DETAILS SKELETON */}
                <div className="p-6 space-y-6">
                  <div className="h-6 bg-gray-200 rounded dark:bg-gray-700 w-1/2" />

                  <div className="grid grid-cols-2 gap-y-3 gap-x-6">
                    {Array.from({ length: 6 }).map((_, i) => (
                      <div
                        key={i}
                        className="h-4 bg-gray-200 rounded dark:bg-gray-700"
                      />
                    ))}
                  </div>

                  <div className="space-y-2">
                    <div className="h-5 bg-gray-200 rounded dark:bg-gray-700 w-1/3" />
                    <div className="h-20 bg-gray-200 rounded dark:bg-gray-700" />
                  </div>

                  <div className="h-5 bg-gray-200 rounded dark:bg-gray-700 w-1/3" />

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2.5 pl-2.5 mt-2.5">
                    {Array.from({ length: 4 }).map((_, i) => (
                      <div
                        key={i}
                        className="h-12 bg-gray-200 rounded dark:bg-gray-700"
                      />
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }
  // if (error) return <p className="text-red-500">{error}</p>;
  if (!service) return <DataNotFound />;

  return (
    <RouteLoader>
      <div className="px-6">
        <div className="max-w-w1660 mx-auto relative">
          <div className="pt-3 pb-4">
            <BreadCrumb
              items={[
                { title: t("header.home"), href: "/" },
                { title: service ? SERVICE_FORM_TYPE : "" },
              ]}
            />
            {service.map((ser: any, index: number) => (
              <div
                key={index}
                className="border border-neutrals100 rounded-lg overflow-hidden bg-white dark:bg-card dark:border-card"
              >
                {/* Left Side: Image or Initial */}
                <div className="flex justify-center items-center bg-primary50 dark:bg-primary700">
                  {ser.image ? (
                    <img
                      src={ser.image}
                      alt={ser.title}
                      onError={(e) => {
                        e.currentTarget.onerror = null;
                        e.currentTarget.src = "/default.jpg";
                      }}
                      className="w-full h-96 border-4 rounded-xl border-white dark:border-neutrals400/20 object-cover m-2 max-lg:h-72 max-md:h-60 max-md:mt-0"
                    />
                  ) : (
                    <div className="w-32 h-32 rounded-full bg-gray-300 flex items-center justify-center text-4xl font-bold text-white mb-4">
                      {ser?.creator?.first_name?.charAt(0)}
                    </div>
                  )}
                </div>

                {/* Right Side: Details */}
                <div className="pt-3 p-4 px-5 max-sm:p-3 max-sm:px-3">
                  <h1 className="text-2xl font-bold mb-2 text-neutrals800 dark:text-white">
                    {ser.title}
                  </h1>
                  {ser.short_description && (
                    <p className="text-sm mb-6 text-neutrals600 dark:text-neutrals400">
                      {ser.short_description}
                    </p>
                  )}

                  {/* Other Details */}
                  {ser?.additional_attributes?.length > 0 && (
                    <div className="mt-4">
                      <h2 className="text-lg font-semibold mb-4 text-neutrals800 dark:text-white">
                        {t("detail_page.other_details")}
                      </h2>

                      <div className="grid grid-cols-2 gap-y-3 gap-x-6">
                        {ser.additional_attributes.map((attr: any) => {
                          const isImageType =
                            attr.type?.includes("image") &&
                            !attr.isFileUploader;
                          const isVideoType =
                            attr.type?.includes("video") &&
                            !attr.isFileUploader;
                          const isFileUploader = !!attr.isFileUploader;

                          return (
                            <div
                              key={attr.field}
                              className={
                                isImageType || isFileUploader
                                  ? "col-span-2"
                                  : ""
                              }
                            >
                              <span className="text-neutrals600 text-sm dark:text-neutrals400 block mb-1">
                                {attr.label?.en}:
                              </span>

                              {isFileUploader && Array.isArray(attr.files) && (
                                <div className="flex flex-wrap gap-2 mt-2">
                                  {attr.files.map(
                                    (file: string, idx: number) => (
                                      <img
                                        key={idx}
                                        src={file}
                                        alt={`${attr.label?.en || "file"} ${
                                          idx + 1
                                        }`}
                                        className="w-16 h-16 object-cover rounded border"
                                        onError={(e) => {
                                          e.currentTarget.onerror = null;
                                          e.currentTarget.src = "/default.jpg";
                                        }}
                                      />
                                    )
                                  )}
                                </div>
                              )}

                              {isImageType &&
                                attr?.processedValue?.selectedOptions?.length >
                                  0 && (
                                  <div className="flex flex-wrap gap-3 mt-2">
                                    {attr?.processedValue?.selectedOptions.map(
                                      (option: any, idx: number) => (
                                        <div
                                          key={idx}
                                          className="flex flex-col items-center text-center"
                                        >
                                          <img
                                            src={option.meta?.fileUrl_en}
                                            alt={option.value?.en}
                                            className="w-16 h-16 object-cover rounded border"
                                            onError={(e) => {
                                              e.currentTarget.onerror = null;
                                              e.currentTarget.src =
                                                "/default.jpg";
                                            }}
                                          />
                                          <span className="text-xs mt-1 text-neutrals600 dark:text-neutrals400">
                                            {option.value?.en}
                                          </span>
                                        </div>
                                      )
                                    )}
                                  </div>
                                )}

                              {isVideoType && attr?.files?.length > 0 && (
                                <div className="flex flex-wrap gap-3 mt-2">
                                  {attr?.files.map(
                                    (option: any, idx: number) => (
                                      <div
                                        key={idx}
                                        className="p-2 bg-gray-100 rounded-xl flex flex-col items-center text-center dark:bg-neutrals400/20"
                                      >
                                        <video
                                          className="w-40 h-full max-h-40"
                                          src={`${process.env.NEXT_PUBLIC_API}${option.location}`}
                                          controls
                                        />
                                      </div>
                                    )
                                  )}
                                </div>
                              )}

                              {!isFileUploader &&
                                !isImageType &&
                                !Array.isArray(attr.value) && (
                                  <strong className="text-neutrals700 font-semibold dark:text-neutrals300 block max-sm:text-sm italic">
                                    {typeof attr.value === "object" &&
                                    attr.value !== null
                                      ? attr.value.displayValue ||
                                        attr.value.value ||
                                        "-"
                                      : attr.value || ""}
                                  </strong>
                                )}

                              {Array.isArray(attr.value) && !isFileUploader && (
                                <div className="flex flex-wrap gap-1 mt-1">
                                  {attr.value.map((val: any, idx: number) => {
                                    // Handle objects with 'value' property (like country/state/city)
                                    if (
                                      typeof val === "object" &&
                                      val !== null &&
                                      "value" in val
                                    ) {
                                      return (
                                        <strong
                                          key={idx}
                                          className="text-xs mt-1 text-neutrals600 dark:text-neutrals400"
                                        >
                                          {val.value}
                                        </strong>
                                      );
                                    }
                                    // Handle plain strings/numbers
                                    return (
                                      <strong
                                        key={idx}
                                        className="text-xs mt-1 text-neutrals600 dark:text-neutrals400"
                                      >
                                        {val}
                                      </strong>
                                    );
                                  })}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {/* Service Description */}
                  {ser?.description && (
                    <div className="mt-6 text-neutrals800 dark:text-neutrals400">
                      <h2 className="text-lg font-semibold">
                        {t("detail_page.service_desc")}:
                      </h2>
                      <div
                        className="text-sm leading-relaxed"
                        dangerouslySetInnerHTML={{ __html: ser.description }}
                      />
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        {products && (
          <ProductSection title="Related Products" items={products} />
        )}
      </div>
    </RouteLoader>
  );
}
