"use client";

import { use, useEffect, useState } from "react";
import { motion } from "framer-motion";
import { useLocale, useTranslations } from "next-intl";
import AuctionCard from "@/components/auction-card";
import { getAuctions, getCamelAuctions } from "@/actions/auction";
import HorseFiltersAuction from "./mazadFilter";
import { useGeneralSettings } from "@/lib/clientQueries";

export default function ClientAuctionsPage({
  initialData,
  config,
  animalType = "horse",
}: {
  initialData: any;
  config: any;
  animalType?: "horse" | "camel";
}) {
  const locale = useLocale();
  const isArabic = locale === "ar";
  const t = useTranslations("AUCTIONS_LIST");
  const tFilters = useTranslations("AUCTIONS_FILTERS");
  const tHorsesList = useTranslations("HORSES_LIST");
  const { data: settings } = useGeneralSettings();

  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 =
    animalType === "camel"
      ? settingUrl((settings as any)?.platform_1_image) || "/images/banner.avif"
      : settingUrl((settings as any)?.platform_2_image) ||
      "/images/unnamed.jpg";
  const [auctions, setAuctions] = useState(initialData?.data || []);
  const [status, setStatus] = useState("all");
  const [page, setPage] = useState(1);
  const [cursor, setCursor] = useState(initialData?.meta?.next_cursor || null);
  useEffect(() => {
    console.log(auctions, "auctions");
  }, [auctions]);
  const [isLoading, setIsLoading] = useState(false);
  const [filters, setFilters] = useState<
    { auction_state?: string } & Record<string, any>
  >({
    auction_state: "",
  });

  const [hasMore, setHasMore] = useState(
    Boolean(initialData?.meta?.next_cursor),
  );

  const handleAuctionTypeChange = (value: string | null) => {
    const nextType = value ?? "";
    const nextFilters = {
      ...filters,
      auction_type: nextType,
    };

    setFilters(nextFilters);
    fetchHorsesAuctionClient(null, nextFilters);
  };

  const fetchHorsesAuctionClient = async (
    cursorValue?: string | null,
    newFilters = filters,
  ) => {
    console.log("🚀 fetchHorsesAuctionClient called with:", {
      cursorValue,
      newFilters,
    });
    setIsLoading(true);
    try {
      const queryFn = animalType === "camel" ? getCamelAuctions : getAuctions;

      const res = await queryFn({
        page: 1,
        cursor: cursorValue || null,
        per_page: 12,
        filters: newFilters,
      });

      console.log("📊 API Response:", res);
      console.log("📊 Data length:", res.data?.length);

      if (
        !cursorValue &&
        (newFilters as any)?.auction_state === "live" &&
        Array.isArray(res.data) &&
        res.data.length === 0
      ) {
        const fallbackFilters = {
          ...newFilters,
          auction_state: "active",
        };
        const fallbackRes = await queryFn({
          page: 1,
          cursor: null,
          per_page: 12,
          filters: fallbackFilters,
        });

        setAuctions(fallbackRes.data);
        setCursor(fallbackRes.meta?.next_cursor || null);
        setFilters(fallbackFilters);
        return;
      }

      if (!cursorValue) setAuctions(res.data);
      else setAuctions((prev: any[]) => [...prev, ...res.data]);
      setCursor(res.meta?.next_cursor || null);
    } finally {
      setIsLoading(false);
    }
  };

  const handleQuickStatusChange = (value: string | null) => {
    console.log("🔍 handleQuickStatusChange called with:", value);
    const normalized = value === "active" ? "active" : value;
    const nextStatus = normalized ?? "all";
    const nextFilters = {
      ...filters,
      auction_state: normalized ?? "",
    };

    console.log("🔍 Setting status to:", nextStatus);
    console.log("🔍 Setting filters to:", nextFilters);

    setStatus(nextStatus);
    setFilters(nextFilters);
    fetchHorsesAuctionClient(null, nextFilters);
  };

  const showEmpty =
    !isLoading && Array.isArray(auctions) && auctions.length === 0;

  const resolveAuctionPrice = (auction: any) => {
    const candidates = [
      auction?.current_bid,
      auction?.current_price,
      auction?.highest_bid,
      auction?.market_entry_price,
      auction?.starting_price,
      auction?.price,
      auction?.final_bid_amount,
    ];

    for (const candidate of candidates) {
      const value = Number(candidate);
      if (Number.isFinite(value) && value > 0) {
        return value;
      }
    }

    return null;
  };

  return (
    <main className="max-w-7xl mx-auto px-4 py-8">
      <div className="mb-4">
        <h1 className="text-2xl font-bold flex flex-col gap-1">
          <span>
            {t(animalType === "camel" ? "heading.camel" : "heading.horse")}
          </span>
          <span className="text-sm text-gray-500">
            {t(
              animalType === "camel" ? "subheading.camel" : "subheading.horse",
            )}
          </span>
        </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">
        <p className="text-[11px] text-gray-500 text-center md:text-start">
          {t("hint")}
        </p>

        <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <div
            className={`flex flex-col md:flex-row md:flex-wrap items-start md:items-center gap-2 justify-center w-full ${isArabic
                ? "md:ml-auto md:justify-end"
                : "md:mr-auto md:justify-start"
              }`}
          >
            <span className="text-sm text-gray-700 shrink-0">
              {t("status.label")}
            </span>

            <div className="w-full md:flex-1 md:w-auto">
              {/* Mobile: grid layout */}
              <div className="md:hidden flex items-center gap-2">
                <div className="grid grid-cols-2 gap-2 flex-1 min-w-0">
                  <button
                    type="button"
                    onClick={() => handleQuickStatusChange(null)}
                    className={`px-2 py-1.5 rounded-full text-xs border transition-colors text-center leading-tight ${status === "all"
                        ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                        : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                      }`}
                  >
                    {t("status.all")}
                  </button>

                  <button
                    type="button"
                    onClick={() => handleQuickStatusChange("active")}
                    className={`px-2 py-1.5 rounded-full text-xs border transition-colors text-center leading-tight ${status === "live" || status === "active"
                        ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                        : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                      }`}
                  >
                    {t("status.active")}
                  </button>

                  <button
                    type="button"
                    onClick={() => handleQuickStatusChange("upcoming")}
                    className={`px-2 py-1.5 rounded-full text-xs border transition-colors text-center leading-tight ${status === "upcoming"
                        ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                        : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                      }`}
                  >
                    {t("status.upcoming")}
                  </button>

                  <button
                    type="button"
                    onClick={() => handleQuickStatusChange("ended")}
                    className={`px-2 py-1.5 rounded-full text-xs border transition-colors text-center leading-tight ${status === "ended"
                        ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                        : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                      }`}
                  >
                    {t("status.ended")}
                  </button>
                </div>

                <HorseFiltersAuction
                  config={config}
                  animalType={animalType}
                  onApply={(f) => {
                    const nextFilters = { ...filters, ...f };
                    setFilters(nextFilters);
                    fetchHorsesAuctionClient(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={() => handleQuickStatusChange(null)}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${status === "all"
                      ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                      : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                >
                  {t("status.all")}
                </button>

                <button
                  type="button"
                  onClick={() => handleQuickStatusChange("active")}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${status === "live" || status === "active"
                      ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                      : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                >
                  {t("status.active")}
                </button>

                <button
                  type="button"
                  onClick={() => handleQuickStatusChange("upcoming")}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${status === "upcoming"
                      ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                      : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                >
                  {t("status.upcoming")}
                </button>

                <button
                  type="button"
                  onClick={() => handleQuickStatusChange("ended")}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${status === "ended"
                      ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                      : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                >
                  {t("status.ended")}
                </button>

                {/* فلتر نوع المزاد (مباشر / إلكتروني) */}
                <span className="mx-2 h-5 w-px bg-gray-200" />

                <span className="text-sm text-gray-700 shrink-0">
                  {tFilters("auction_type.label")}
                </span>

                <button
                  type="button"
                  onClick={() => handleAuctionTypeChange(null)}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${!filters.auction_type
                      ? "bg-[#1B7A50] text-white border-[#1B7A50]"
                      : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                >
                  {tHorsesList("all")}
                </button>

                <button
                  type="button"
                  onClick={() => handleAuctionTypeChange("live")}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${filters.auction_type === "live"
                      ? "bg-red-600 text-white border-red-600"
                      : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                >
                  {tFilters("auction_type.live")}
                </button>

                <button
                  type="button"
                  onClick={() => handleAuctionTypeChange("electronic")}
                  className={`px-3 py-1.5 rounded-full text-sm border transition-colors whitespace-nowrap ${filters.auction_type === "electronic"
                      ? "bg-gray-700 text-white border-gray-700"
                      : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100"
                    }`}
                >
                  {tFilters("auction_type.electronic")}
                </button>
              </div>
            </div>
          </div>

          <div
            className={`hidden md:flex justify-center ${isArabic ? "md:justify-start" : "md:justify-end"
              }`}
          >
            <HorseFiltersAuction
              config={config}
              animalType={animalType}
              onApply={(f) => {
                const nextFilters = { ...filters, ...f };
                setFilters(nextFilters);
                fetchHorsesAuctionClient(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.description")}
              </p>
              <div className="mt-6">
                <button
                  type="button"
                  onClick={() => {
                    setStatus("all");
                    setFilters({ auction_state: "" });
                    setHasMore(false);
                    fetchHorsesAuctionClient(null, { auction_state: "" });
                  }}
                  className="px-6 py-3 rounded-xl text-white bg-[#1B7A50] hover:bg-[#14623c] transition-colors"
                >
                  {t("empty.show_all")}
                </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.2 } },
          }}
        >
          {auctions?.map((x: any) => (
            <motion.div
              key={x.id}
              variants={{
                hidden: { opacity: 0, y: 20 },
                show: { opacity: 1, y: 0, transition: { duration: 0.5 } },
              }}
            >
              <AuctionCard
                id={x.id}
                unique_id={x.unique_id}
                title={x.title}
                status={x.auction_state}
                listingStatus={x.status}
                auctionType={x.auction_type}
                animalType={animalType}
                img={x.main_image?.url || platformFallbackImage}
                category={x.animal_usage}
                country={x.country || "—"}
                city={x.state || "—"}
                breed={x.breed || "—"}
                color={x.animal_color || "—"}
                price={x.final_bid_amount}
                timeLeft={x.auction_start_time}
                auctionStartTime={x.auction_start_time}
                auctionEndTime={x.auction_end_time}
                isFavorite={x.is_favorited}
              />
            </motion.div>
          ))}
        </motion.div>
      )}
      {hasMore && (
        <div className="mt-8 text-center">
          <button
            onClick={() => fetchHorsesAuctionClient(cursor)}
            disabled={isLoading}
            className="px-6 py-3 rounded-xl text-white bg-[#1B7A50] hover:bg-[#14623c] transition-colors"
          >
            {isLoading ? t("load_more.loading") : t("load_more.more")}
          </button>
        </div>
      )}
    </main>
  );
}
