"use client";

import { useMemo, useState } from "react";
import ServiceListingCard from "@/components/service-listing-card/ServiceListingCard";
import ServiceDetailModal, {
  type ServiceDetailInfoRow,
} from "@/components/service-listing-card/ServiceDetailModal";
import { displayServiceField } from "@/components/service-listing-card/detailHelpers";
import DynamicInput from "@/components/input";
import DynamicButton from "@/components/button";
import { motion } from "framer-motion";
import { getProductServices } from "@/actions/services/products";
import { useTranslations, useLocale } from "next-intl";
import { toMoneyNumber } from "@/lib/moneyParse";
import {
  cardThumbnailsFromGallery,
  extractProductImages,
  withServiceImageFallback,
} from "@/lib/serviceMedia";
import { parseServiceLatLng } from "@/lib/serviceGeo";
import type { ServiceMapCoords } from "@/lib/serviceGeo";
import { formatRatingWithMax } from "@/lib/serviceRating";
import type { ReviewableType } from "@/lib/publicReviewsApi";
import type { ServiceDetailPackage } from "@/components/service-listing-card/detailHelpers";

function productContact(p: Record<string, unknown>): {
  phone: string;
  whatsapp: string;
} {
  return {
    phone: String(
      p.phone_number ?? p.contact_phone ?? p.seller_phone ?? "",
    ).trim(),
    whatsapp: String(
      p.whatsapp_number ?? p.contact_whatsapp ?? p.seller_whatsapp ?? "",
    ).trim(),
  };
}

type DetailState = {
  images: string[];
  imageAlt: string;
  infoRows: ServiceDetailInfoRow[];
  description: string;
  mapCoords: ServiceMapCoords | null;
  phone: string;
  whatsapp: string;
  serviceRatingRaw: string | null | undefined;
  reviewableId: string;
  reviewableType: ReviewableType;
  packages?: ServiceDetailPackage[] | null;
} | null;

export default function ClientHorseCamelProducts({ data }: { data: any }) {
  const t = useTranslations("SERVICES_PRODUCTS");
  const tCard = useTranslations("SERVICE_LISTING_CARD");
  const tDetail = useTranslations("SERVICE_DETAIL_MODAL");
  const locale = useLocale();
  const currencySuffix = locale.startsWith("ar") ? " ر.س" : " SAR";
  const [items, setItems] = useState<any[]>(data.data);
  const [meta, setMeta] = useState(data.meta);
  const [detail, setDetail] = useState<DetailState>(null);

  const [filters, setFilters] = useState({
    search: "",
    category: "all",
  });

  const categories = useMemo(() => {
    const base = [{ id: "all", name: t("filters.all_animals") }];
    const unique = new Map<string, string>();
    (data.data || []).forEach((p: any) => {
      const key = String(p.category || "").trim();
      if (!key) return;
      if (!unique.has(key)) unique.set(key, key);
    });
    return [
      ...base,
      ...Array.from(unique.entries()).map(([id, name]) => ({ id, name })),
    ];
  }, [data.data, t]);

  const typeMap: Record<string, string> = {
    tack: t("types.tack"),
    feed: t("types.feed"),
    care: t("types.care"),
    vet: t("types.vet"),
    training: t("types.training"),
  };

  const fetchData = async (
    page = 1,
    append = false,
    overrideFilters?: typeof filters,
  ) => {
    const effective = overrideFilters || filters;
    const params: any = {
      page,
      per_page: meta.per_page,
      search: effective.search,
    };

    if (effective.category && effective.category !== "all") {
      params.category = effective.category;
    }

    const res = await getProductServices(params);

    const newData = res.data;
    setMeta(newData.meta);

    if (append) {
      setItems((prev) => [...prev, ...newData.data]);
    } else {
      setItems(newData.data);
    }
  };

  const handleFilterChange = async (
    key: keyof typeof filters,
    value: string,
  ) => {
    const next = { ...filters, [key]: value };
    setFilters(next);
    await fetchData(1, false, next);
  };

  const handleLoadMore = async () => {
    if (meta.current_page >= meta.last_page) return;
    await fetchData(meta.current_page + 1, true);
  };

  return (
    <main className="bg-[#FBF9F6] min-h-screen">
      <section className="py-4 sm:py-6">
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="filter-container p-3 sm:p-4 space-y-3 sm:space-y-2">
            <div className="flex flex-wrap items-center gap-2">
              {categories.map((cat) => (
                <button
                  key={cat.id}
                  type="button"
                  className={`px-3 py-1.5 rounded-full text-xs sm:text-sm border transition-colors whitespace-nowrap ${
                    filters.category === cat.id
                      ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                      : "bg-white text-slate-700 border-slate-200 hover:bg-slate-50"
                  }`}
                  onClick={() => handleFilterChange("category", cat.id)}
                >
                  {cat.name}
                </button>
              ))}
            </div>

            <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 items-stretch sm:items-end">
              <DynamicInput
                type="text"
                placeholder={t("filters.search_placeholder")}
                field={{
                  name: "search",
                  value: filters.search,
                  onChange: (e: any) =>
                    setFilters((prev) => ({ ...prev, search: e.target.value })),
                }}
                variant="bordered"
                size="sm"
                className="flex-1 w-full"
              />

              <DynamicButton
                className="h-10 sm:h-11 px-5 btn-primary-gradient text-white rounded-xl w-full sm:w-auto"
                onClick={() => handleFilterChange("search", filters.search)}
              >
                {t("filters.search_button")}
              </DynamicButton>
            </div>
          </div>
        </div>
      </section>

      <section className="max-w-7xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
        <motion.div
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 sm:gap-6 lg:gap-8"
          initial="hidden"
          animate="show"
          variants={{
            hidden: {},
            show: { transition: { staggerChildren: 0.15 } },
          }}
        >
          {items.map((p: any, i: number) => {
            const po = p as Record<string, unknown>;
            const { phone, whatsapp } = productContact(po);
            const rawTypeName = p.product_type?.name
              ? String(p.product_type.name)
              : "";
            const typeLabel =
              typeMap[rawTypeName] ||
              (rawTypeName ? rawTypeName : "");
            const priceNum = toMoneyNumber(p.price, 0);
            const priceStr = priceNum.toLocaleString(locale);
            const secondaryVal =
              typeLabel && priceStr
                ? `${typeLabel} · ${priceStr}${currencySuffix}`
                : typeLabel || (priceStr ? `${priceStr}${currencySuffix}` : "") || "—";
            const gallery = extractProductImages(po);
            const cardImages = withServiceImageFallback(
              cardThumbnailsFromGallery(gallery),
            );
            const modalImages = withServiceImageFallback(gallery);
            const priceDisplay =
              priceStr && String(p.price ?? "").trim() !== ""
                ? `${priceStr}${currencySuffix}`
                : null;
            const productTypeDisplay =
              typeLabel ||
              displayServiceField(p.product_type?.name ?? p.product_type);
            const ratingLine = formatRatingWithMax(po.rating);
            const infoRows: ServiceDetailInfoRow[] = [
              {
                label: tCard("label_product"),
                value: displayServiceField(p.name),
              },
              {
                label: tDetail("label_provider"),
                value: displayServiceField(po.provider_name),
              },
              {
                label: tDetail("label_product_type"),
                value: productTypeDisplay,
              },
              {
                label: tDetail("label_category"),
                value: displayServiceField(po.category),
              },
              {
                label: tDetail("label_price"),
                value: priceDisplay ?? "—",
                valueClassName: "text-[#1B7A50] font-extrabold",
              },
              {
                label: tDetail("label_phone"),
                value: displayServiceField(phone),
              },
              {
                label: tDetail("label_whatsapp"),
                value: displayServiceField(whatsapp),
              },
            ];

            return (
              <motion.div
                key={p.id || i}
                variants={{
                  hidden: { opacity: 0, y: 20 },
                  show: { opacity: 1, y: 0, transition: { duration: 0.5 } },
                }}
              >
                <ServiceListingCard
                  images={cardImages}
                  imageAlt={p.name}
                  primaryLabel={tCard("label_product")}
                  primaryValue={p.name}
                  secondaryLabel={tCard("label_category")}
                  secondaryValue={secondaryVal}
                  phone={phone}
                  whatsapp={whatsapp}
                  ratingRaw={po.rating}
                  ratingLine={ratingLine}
                  onDetailsClick={() =>
                    setDetail({
                      images: modalImages,
                      imageAlt: p.name,
                      infoRows,
                      description: String(p.description ?? "").trim(),
                      mapCoords: parseServiceLatLng(po.lat, po.lng),
                      phone,
                      whatsapp,
                      serviceRatingRaw:
                        po.rating != null ? String(po.rating) : undefined,
                      reviewableId: String(p.id),
                      reviewableType: "product",
                      packages: null,
                    })
                  }
                />
              </motion.div>
            );
          })}
        </motion.div>

        {meta.current_page < meta.last_page && (
          <div className="mt-8 text-center">
            <DynamicButton
              onClick={handleLoadMore}
              className="px-6 py-3 rounded-xl text-white bg-[#1B7A50] hover:bg-[#14623c] transition-colors"
            >
              {t("load_more")}
            </DynamicButton>
          </div>
        )}
      </section>

      <ServiceDetailModal
        isOpen={detail != null}
        onOpenChange={(open) => {
          if (!open) setDetail(null);
        }}
        images={detail?.images ?? []}
        imageAlt={detail?.imageAlt ?? ""}
        infoRows={detail?.infoRows ?? []}
        descriptionLabel={tDetail("label_description")}
        description={detail?.description}
        mapCoords={detail?.mapCoords ?? null}
        serviceRatingRaw={detail?.serviceRatingRaw}
        reviewableId={detail?.reviewableId}
        reviewableType={detail?.reviewableType}
        packages={detail?.packages ?? null}
        phone={detail?.phone}
        whatsapp={detail?.whatsapp}
      />
    </main>
  );
}
