"use client";

import { useEffect, useState, useMemo } from "react";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { useFormatDateTime } from "@/lib/utils/dateTimeUtils";
import { useAppSelector } from "@/app/store/hooks";
import { fetchServicesAction } from "@/lib/actions/serviceAction";
import { Service } from "@/app/(kanzy)/service/Services";


interface ServiceSectionProps {
  title?: string;
  category?: string;
  is_view_more?: boolean;
}

export default function ServiceSection({
  title,
  category,
  is_view_more = true,
}: ServiceSectionProps) {
  const [services, setServices] = useState<Service[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const t = useTranslations();
  const { formatDateTime } = useFormatDateTime();
  const { user } = useAppSelector((state: any) => state.auth);

  const initialCount = 5;
  const visibleItems = useMemo(
    () => services.slice(0, initialCount),
    [services]
  );

  const getViewMoreUrl = () => {
    if (category && category.trim()) {
      return `/service?category=${encodeURIComponent(category.trim())}`;
    }
    return "/service";
  };

  const transformServices = (data: any) => {
    const fetchedServices = data;

    const imageMap: Record<string, string> = {};
    if (Array.isArray(fetchedServices)) {
      fetchedServices.forEach((item: any) => {
        const imgAttr = item.attributes.find(
          (attr: any) => attr.type === "singleimageuploader"
        );
        if (imgAttr) {
          const imageLocation = imgAttr?.meta?.files?.[0]?.location;
          if (imageLocation) imageMap[item._id] = imageLocation;
        }
      });
    }

    const merged = fetchedServices.map((srv: any) => {
      let title = '';
      let description = '';

      srv.attributes?.forEach((attr: any) => {
        const slug = attr.attributeSlug;
        const value = attr.value;

        switch (slug) {
          case 'title':
            title = value;
            break;
          case 'short-description':
            description = value;
            break;
        }
      });

      // Create the service object matching the simplified interface
      const service = {
        _id: srv._id,
        title,
        description,
        createdAt: srv.createdAt,
        creator: srv.creator,
        image: imageMap[srv._id] || null,
      };

      return service;
    });

    setServices(merged);
  }

  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        const serviceRes = await fetchServicesAction({ limit: 20 }, "en");
        // const listingRes = await indexListing(user?.token, {
        //   formType: "services",
        // });

        if (serviceRes.success && serviceRes.data?.services) {
          const fetchedServices = serviceRes.data.services;

          transformServices(fetchedServices);
        } else {
          setError(serviceRes.message || "Failed to load services");
        }
      } catch (err) {
        setError("Failed to load services");
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [user?.token]);

  if (loading) {
    return (
      <div className="grid md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-5 2xl:grid-cols-6 gap-5 max-md:grid-cols-2 max-[500px]:grid-cols-1">
        {[...Array(initialCount)].map((_, index) => (
          <div
            key={index}
            className="flex-shrink-0 overflow-hidden border rounded-lg bg-white animate-pulse"
          >
            <div className="p-4 pb-4">
              <div className="h-40 bg-gray-200 rounded mb-2"></div>
              <div className="h-4 bg-gray-300 rounded w-3/4 mb-1"></div>
              <div className="h-4 bg-gray-300 rounded w-1/2"></div>
            </div>
          </div>
        ))}
      </div>
    );
  }

  if (error || services.length === 0) return null;

  return (
    <>
      {/* Header with View More link */}
      <div className="flex justify-between items-center border-b border-neutrals100 pb-2.5 mb-5 dark:border-darkborder max-md:mb-4">
        <h2 className="text-base font-semibold text-neutrals800 dark:text-white">
          {title || t("services_availability")}
        </h2>
        {is_view_more && (
          <Link
            href={getViewMoreUrl()}
            className="text-sm font-semibold text-primary500 hover:underline dark:text-primary400"
          >
            {t("post_availability_section.view_more")}
          </Link>
        )}
      </div>

      {/* Service Cards */}
      <div className="grid md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-5 2xl:grid-cols-6 gap-5 max-md:grid-cols-2 max-[500px]:grid-cols-1">
        {visibleItems.map((service: Service) => (
          <Link key={service?._id} href={`/service/${service?._id}`}>
            <div className="relative h-full flex-shrink-0 overflow-hidden border border-neutrals100 rounded-lg bg-white dark:bg-card dark:border-card pb-12">
              {service?.image && (
                <img
                  src={`${process.env.NEXT_PUBLIC_API}${service?.image}`}
                  alt={service?.title}
                  className="w-full h-40 object-cover"
                  onError={(e) => {
                    e.currentTarget.onerror = null;
                    e.currentTarget.src = "/default.jpg";
                  }}
                />
              )}
              <div className="p-4 pb-4">
                <div className="flex justify-between items-center mb-4">
                  <div className="flex items-center gap-2">
                    <img
                      src={`${process.env.NEXT_PUBLIC_API}/${service?.creator?.profile_image}`}
                      alt={service?.creator?.first_name}
                      className="w-8 h-8 rounded-full object-cover"
                      onError={(e) => {
                        e.currentTarget.onerror = null;
                        e.currentTarget.src = "/profile-avatar.png";
                      }}
                    />
                    <p className="text-sm font-semibold text-primary500 dark:text-white capitalize line-clamp-1">
                      {service?.creator?.first_name}{" "}
                      {service?.creator?.last_name}
                    </p>
                  </div>
                </div>
                <p className="text-base font-semibold text-neutrals900 leading-tight mb-1 dark:text-neutrals400 line-clamp-2">{service?.title}</p>
                <p className="text-sm text-neutrals500 line-clamp-2">{service?.description}</p>
              </div>
              <div className="absolute left-0 bottom-0 w-full flex items-center justify-between bg-neutrals50 text-xs py-2 px-4 text-neutrals500 dark:bg-cardfooter">
                <div className="flex items-center gap-1">
                  <span className="text-sm text-neutrals800 dark:text-neutrals400">
                    {/* {service?.cityOrState} */}
                  </span>
                </div>
                <span className="text-sm text-neutrals800 dark:text-neutrals400">
                  {formatDateTime(service?.createdAt)}
                </span>
              </div>
            </div>
          </Link>
        ))}
      </div>
    </>
  );
}
