"use client";

import { useEffect, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { motion } from "framer-motion";
import { getCamelOffers, getHorses } from "@/actions/auction";
import HorseCard from "@/components/hourse-card";
import HorseFilters from "./horsesFilter";
import { useGeneralSettings } from "@/lib/clientQueries";

export default function ClientHorsesPage({
  initialData,
  config,
  basePath = "horses",
}: any) {
  const locale = useLocale();
  const isArabic = locale === "ar";
  const tHorses = useTranslations("HORSES_LIST");
  const tCamels = useTranslations("CAMELS_LIST");
  const { data: settings } = useGeneralSettings();

  const isCamelsPage = basePath === "camels";
  const t = isCamelsPage ? tCamels : tHorses;

  const settingUrl = (value: any): string | undefined => {
    if (!value) return undefined;
    if (typeof value === "string") return value;
    if (typeof value === "object" && typeof value.url === "string")
      return value.url;
    return undefined;
  };

  const platformFallbackImage =
    basePath === "camels"
      ? settingUrl((settings as any)?.platform_1_image) || "/images/banner.avif"
      : settingUrl((settings as any)?.platform_2_image) ||
        "/images/unnamed.jpg";
  const [horses, setHorses] = useState(initialData?.data || []);
  const [cursor, setCursor] = useState(initialData?.meta?.next_cursor || null);
  const [filters, setFilters] = useState<Record<string, any>>({});
  const [quickUsage, setQuickUsage] = useState<string | "all">("all");
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const usageId = filters?.animal_usage_id;
    if (!usageId) {
      if (quickUsage !== "all") setQuickUsage("all");
      return;
    }
    if (quickUsage !== String(usageId)) {
      setQuickUsage(String(usageId));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters?.animal_usage_id]);

  const fetchHorsesClient = async (
    cursorValue?: string | null,
    newFilters = filters,
  ) => {
    setIsLoading(true);
    try {
      const queryFn = basePath === "camels" ? getCamelOffers : getHorses;
      const res = await queryFn({
        page: 1,
        cursor: cursorValue || null,
        per_page: 12,
        filters: newFilters,
      });
      if (!cursorValue) setHorses(res.data);
      else setHorses((prev: any[]) => [...prev, ...res.data]);
      setCursor(res.meta?.next_cursor || null);
    } finally {
      setIsLoading(false);
    }
  };

  const handleQuickUsageChange = (usageId: string | null) => {
    const nextQuick = usageId ?? "all";
    const nextFilters = {
      ...filters,
      animal_usage_id: usageId ?? "",
    };
    setQuickUsage(nextQuick);
    setFilters(nextFilters);
    fetchHorsesClient(null, nextFilters);
  };

  const showEmpty = !isLoading && Array.isArray(horses) && horses.length === 0;
  return (
    <main className="max-w-7xl mx-auto px-4 py-8">
      <div className="mb-4">
        <h1 className="text-2xl font-bold">
          {isCamelsPage
            ? tCamels("title", {
                defaultValue: isArabic
                  ? "منصة الإبل 🐪"
                  : "Camels Marketplace 🐪",
              })
            : tHorses("title", {
                defaultValue: isArabic
                  ? "منصة الخيول 🐎"
                  : "Horses Marketplace 🐎",
              })}
        </h1>
      </div>

      <section className="mb-8 rounded-2xl bg-white shadow-sm px-4 py-3 flex flex-col gap-2 md:static sticky top-16 z-20">
        <div
          className={`flex flex-col gap-3 md:flex-row md:items-center md:justify-between ${
            isArabic ? "" : "md:flex-row-reverse"
          }`}
        >
          <div
            className={`flex flex-col md:flex-row md:flex-wrap items-start md:items-center gap-2 justify-center w-full ${
              isArabic ? "md:justify-end" : "md:justify-start"
            }`}
          >
            <span className="text-sm text-gray-700 shrink-0">
              {t("category_label", {
                defaultValue: isArabic ? "التصنيف:" : "Category:",
              })}
            </span>

            <div
              className={`w-full md:flex-1 md:w-auto ${
                isArabic
                  ? "md:ml-auto md:justify-end"
                  : "md:mr-auto md:justify-start"
              }`}
            >
              {/* Mobile: chips + filter icon in same row */}
              <div
                className={`md:hidden flex items-center gap-2 ${
                  isArabic ? "flex-row" : "flex-row-reverse"
                }`}
              >
                <div className="grid grid-cols-3 gap-2 flex-1 min-w-0">
                  <button
                    type="button"
                    onClick={() => handleQuickUsageChange(null)}
                    className={`px-2 py-1.5 rounded-full text-xs border transition-colors text-center leading-tight ${
                      quickUsage === "all"
                        ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                        : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                  >
                    {t("all", { defaultValue: isArabic ? "الكل" : "All" })}
                  </button>

                  {config?.usages?.map((u: any) => (
                    <button
                      key={u.id}
                      type="button"
                      onClick={() => handleQuickUsageChange(String(u.id))}
                      className={`px-2 py-1.5 rounded-full text-xs border transition-colors text-center leading-tight ${
                        quickUsage === String(u.id)
                          ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                          : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                      }`}
                    >
                      {u.name}
                    </button>
                  ))}
                </div>

                <HorseFilters
                  config={config}
                  initialFilters={filters}
                  onApply={(f) => {
                    const nextFilters = {
                      ...filters,
                      ...f,
                      animal_usage_id:
                        f?.animal_usage_id === "" ||
                        f?.animal_usage_id === undefined
                          ? (filters?.animal_usage_id ?? "")
                          : f.animal_usage_id,
                    };
                    setFilters(nextFilters);
                    fetchHorsesClient(null, nextFilters);
                  }}
                />
              </div>

              {/* Desktop: flex row */}
              <div
                className={`hidden md:flex flex-nowrap items-center gap-2 min-w-max py-1 ${
                  isArabic ? "justify-start" : "justify-start"
                }`}
              >
                <button
                  type="button"
                  onClick={() => handleQuickUsageChange(null)}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${
                    quickUsage === "all"
                      ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                      : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                  }`}
                >
                  {t("all", { defaultValue: isArabic ? "الكل" : "All" })}
                </button>

                {config?.usages?.map((u: any) => (
                  <button
                    key={u.id}
                    type="button"
                    onClick={() => handleQuickUsageChange(String(u.id))}
                    className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${
                      quickUsage === String(u.id)
                        ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                        : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                  >
                    {u.name}
                  </button>
                ))}
              </div>
            </div>
          </div>

          <div
            className={`hidden md:flex justify-center ${
              isArabic ? "md:justify-start" : "md:justify-end"
            }`}
          >
            <HorseFilters
              config={config}
              initialFilters={filters}
              onApply={(f) => {
                const nextFilters = {
                  ...filters,
                  ...f,
                  animal_usage_id:
                    f?.animal_usage_id === "" ||
                    f?.animal_usage_id === undefined
                      ? (filters?.animal_usage_id ?? "")
                      : f.animal_usage_id,
                };
                setFilters(nextFilters);
                fetchHorsesClient(null, nextFilters);
              }}
            />
          </div>
        </div>
      </section>

      {showEmpty ? (
        <div className="bg-white rounded-2xl shadow-sm p-6 md:p-10">
          <div className="grid gap-8 md:grid-cols-2 items-center">
            <div className="order-2 md:order-1">
              <h2 className="text-2xl md:text-3xl font-extrabold text-gray-900">
                {t("empty_title")}
              </h2>
              <p className="mt-2 text-gray-500 leading-relaxed">
                {t("empty_desc")}
              </p>
              <div className="mt-6">
                <button
                  type="button"
                  onClick={() => {
                    setFilters({});
                    setQuickUsage("all");
                    fetchHorsesClient(null, {});
                  }}
                  className="px-6 py-3 rounded-xl text-white bg-[#1B7A50] hover:bg-[#14623c] transition-colors"
                >
                  {t("empty_reset")}
                </button>
              </div>
            </div>

            <div className="order-1 md:order-2">
              <div className="relative w-full overflow-hidden rounded-2xl border bg-gray-50">
                <img
                  src={platformFallbackImage}
                  alt=""
                  className="w-full h-[220px] md:h-[280px] object-cover"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/40 via-black/10 to-transparent" />
              </div>
            </div>
          </div>
        </div>
      ) : (
        <motion.div
          key={JSON.stringify(filters)}
          className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
          initial={false}
          animate="show"
          variants={{
            hidden: {},
            show: { transition: { staggerChildren: 0.15 } },
          }}
        >
          {horses?.map((h: any) => (
            <motion.div
              key={h.id}
              className="h-full"
              variants={{
                hidden: { opacity: 0, y: 20 },
                show: { opacity: 1, y: 0, transition: { duration: 0.3 } },
              }}
            >
              <HorseCard
                sarIcon="/Riyal.svg"
                basePath={basePath}
                horse={{
                  id: h.id,
                  title: h.title,
                  type:
                    h.animal_usage ||
                    t("type_unknown", { defaultValue: "غير محدد" }),
                  img: h.main_image?.url || platformFallbackImage,
                  price: Number(h.price),
                  breed: h.breed || "—",
                  city: h.state || "—",
                  country: h.country || "—",
                  coat: h.animal_color || "—",
                  saleType: h.is_group
                    ? t("sale_group", { defaultValue: "مجموعة" })
                    : t("sale_single", { defaultValue: "فردي" }),
                }}
              />
            </motion.div>
          ))}
        </motion.div>
      )}

      {cursor && (
        <div className="mt-8 text-center">
          <button
            onClick={() => fetchHorsesClient(cursor)}
            disabled={isLoading}
            className="px-6 py-3 rounded-xl text-white bg-[#1B7A50] hover:bg-[#14623c]"
          >
            {isLoading
              ? t("loading", { defaultValue: "جار التحميل..." })
              : t("load_more", { defaultValue: "تحميل المزيد" })}
          </button>
        </div>
      )}
    </main>
  );
}
