"use client";

import { useTranslations, useLocale } from "next-intl";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Select, SelectItem, type Selection } from "@heroui/react";
import { useSearchParams } from "next/navigation";
import AnnualAuctionCardItem, {
  type AnnualAuctionCard,
  type AnnualAuctionCardTheme,
} from "@/components/annaulMazad/AnnualAuctionCardItem";
import { staggerContainer, tabVariants } from "@/lib/animations";
import type { GroupAuctionsPagination } from "@/types/groupAuctionsList";
import { fetchAnnualAuctionsListPage } from "@/actions/annual-auctions-list-page";
import type { GetGroupAuctionsParams } from "@/actions/group-auctions";

const ANNUAL_AUCTIONS_LIST_PER_PAGE = 20;

interface AnnualAuctionsClientProps {
  cards: AnnualAuctionCard[];
  initialPagination: GroupAuctionsPagination;
  usagesByAnimal: {
    horse: { id: string; name: string }[];
    camel: { id: string; name: string }[];
  };
}

export default function ({
  cards: initialCards,
  initialPagination,
  usagesByAnimal,
}: AnnualAuctionsClientProps) {
  const tUi = useTranslations("ANNUAL_AUCTIONS_LIST_UI");
  const locale = useLocale();
  const searchParams = useSearchParams();
  const isRtl = (locale || "").toLowerCase().startsWith("ar");
  const iconColor = "#0f5132";
  const formatCardDate = (value: string | null | undefined) => {
    if (!value) return "-";
    const v = String(value);
    const hasTime = /T\d{2}:\d{2}/.test(v) || /\s\d{2}:\d{2}/.test(v);

    const d = new Date(v);
    if (Number.isNaN(d.getTime())) return v;

    try {
      if (hasTime) {
        return new Intl.DateTimeFormat(locale === "ar" ? "ar-SA" : "en-US", {
          dateStyle: "medium",
          timeStyle: "short",
        }).format(d);
      }

      return new Intl.DateTimeFormat(locale === "ar" ? "ar-SA" : "en-US", {
        dateStyle: "medium",
      }).format(d);
    } catch {
      return hasTime ? d.toLocaleString() : d.toLocaleDateString();
    }
  };

  const formatLiveCardDate = (value: string | null | undefined) => {
    if (!value) return "-";
    // Keep the old behavior for date-only values, but never show raw ISO with 'T'
    return formatCardDate(value);
  };

  const AUCTION_STATUS = {
    upcoming: {
      label: tUi("status.upcoming"),
      color: "amber",
      bg: "bg-amber-500",
      bgLight: "bg-amber-50",
      border: "border-amber-300",
      text: "text-amber-600",
    },
    live: {
      label: tUi("status.live"),
      color: "red",
      bg: "bg-red-600",
      bgLight: "bg-red-50",
      border: "border-red-300",
      text: "text-red-600",
    },
    ended: {
      label: tUi("status.ended"),
      color: "slate",
      bg: "bg-slate-500",
      bgLight: "bg-slate-100",
      border: "border-slate-300",
      text: "text-slate-700",
    },
  };

  const [activeTab, setActiveTab] = useState<"all" | "horse" | "camel">("all");
  const [statusFilter, setStatusFilter] = useState<
    "all" | "upcoming" | "live" | "ended"
  >("all");
  const [usageFilter, setUsageFilter] = useState<string>("all");

  useEffect(() => {
    const qp = (searchParams?.get("animal") || "").toString().toLowerCase();
    if (qp === "horse" || qp === "camel") {
      setActiveTab(qp);
    }
  }, [searchParams]);

  const onUsageSelectionChange = (keys: Selection) => {
    const value = (Array.from(keys).at(0) as string | undefined) ?? "all";
    setUsageFilter(value);
  };

  const usageOptions = useMemo(() => {
    if (activeTab === "horse") return usagesByAnimal.horse;
    if (activeTab === "camel") return usagesByAnimal.camel;
    return [];
  }, [activeTab, usagesByAnimal]);

  const usageSelectItems = useMemo(
    () => [
      { key: "all", label: tUi("filters.all") },
      ...usageOptions.map((u) => ({ key: u.name, label: u.name })),
    ],
    [usageOptions, tUi],
  );

  const shouldShowUsageFilter = activeTab !== "all" && usageOptions.length > 0;

  useEffect(() => {
    setUsageFilter("all");
  }, [activeTab]);

  const [cards, setCards] = useState<AnnualAuctionCard[]>(initialCards);
  const [pagination, setPagination] =
    useState<GroupAuctionsPagination>(initialPagination);
  const [loadingMore, setLoadingMore] = useState(false);
  const [loadMoreError, setLoadMoreError] = useState(false);
  const [filtersLoading, setFiltersLoading] = useState(false);
  const skipInitialServerFilterRefetch = useRef(true);

  const serverListParams = useMemo((): Pick<
    GetGroupAuctionsParams,
    "animal_type" | "auction_state"
  > => {
    return {
      ...(activeTab === "horse" || activeTab === "camel"
        ? { animal_type: activeTab }
        : {}),
      ...(statusFilter !== "all" ? { auction_state: statusFilter } : {}),
    };
  }, [activeTab, statusFilter]);

  useEffect(() => {
    setCards(initialCards);
    setPagination(initialPagination);
    setLoadMoreError(false);
  }, [initialCards, initialPagination]);

  useEffect(() => {
    if (skipInitialServerFilterRefetch.current) {
      skipInitialServerFilterRefetch.current = false;
      return;
    }
    let cancelled = false;
    void (async () => {
      setFiltersLoading(true);
      setLoadMoreError(false);
      const res = await fetchAnnualAuctionsListPage({
        per_page: ANNUAL_AUCTIONS_LIST_PER_PAGE,
        page: 1,
        ...serverListParams,
      });
      if (cancelled) return;
      setFiltersLoading(false);
      if (!res.ok) {
        setLoadMoreError(true);
        return;
      }
      setCards(res.cards);
      setPagination(res.pagination);
    })();
    return () => {
      cancelled = true;
    };
  }, [activeTab, statusFilter, serverListParams]);

  const loadMore = useCallback(async () => {
    if (!pagination.has_more || loadingMore || filtersLoading) return;
    setLoadingMore(true);
    setLoadMoreError(false);
    const res = await fetchAnnualAuctionsListPage({
      per_page: pagination.per_page,
      ...serverListParams,
      ...(pagination.next_cursor
        ? { cursor: pagination.next_cursor }
        : { page: pagination.current_page + 1 }),
    });
    setLoadingMore(false);
    if (!res.ok) {
      setLoadMoreError(true);
      return;
    }
    const seen = new Set(cards.map((c) => c.id));
    const merged = [...cards];
    for (const c of res.cards) {
      if (!seen.has(c.id)) {
        seen.add(c.id);
        merged.push(c);
      }
    }
    setCards(merged);
    const next = res.pagination;
    const newCurrent = pagination.current_page + 1;
    const usedCursor = Boolean(pagination.next_cursor);
    setPagination({
      ...next,
      current_page: newCurrent,
      last_page: next.has_more
        ? Math.max(next.last_page, newCurrent + 1)
        : newCurrent,
      total: usedCursor ? merged.length : next.total,
    });
  }, [pagination, loadingMore, filtersLoading, cards, serverListParams]);

  const filteredCards = useMemo(() => {
    let filtered = cards;
    // animal_type + auction_state are applied via API; usage stays client-only (name match)
    if (shouldShowUsageFilter && usageFilter !== "all") {
      filtered = filtered?.filter((c) => (c.animalUsage ?? "") === usageFilter);
    }
    return filtered;
  }, [usageFilter, shouldShowUsageFilter, cards]);

  const showEmptyState = !filteredCards || filteredCards.length === 0;

  const handleResetFilters = () => {
    setActiveTab("all");
    setStatusFilter("all");
    setUsageFilter("all");
  };

  const getCardTheme = (badgeColor: string): AnnualAuctionCardTheme => {
    if (badgeColor === "live") {
      return {
        accentBar: "bg-red-500",
        badge: "bg-red-50 text-red-700 border-red-200",
      };
    }

    if (badgeColor === "upcoming") {
      return {
        accentBar: "bg-amber-500",
        badge: "bg-amber-50 text-amber-700 border-amber-200",
      };
    }

    return {
      accentBar: "bg-slate-400",
      badge: "bg-slate-100 text-slate-700 border-slate-200",
    };
  };

  const getAnimalsCountLabel = (animalType?: "horse" | "camel") =>
    animalType === "camel"
      ? tUi("card_labels.camel_count")
      : tUi("card_labels.horse_count");

  return (
    <main
      className="md:min-h-screen text-[#333] overflow-x-hidden bg-gradient-to-b from-gray-50 to-white"
      dir={isRtl ? "rtl" : "ltr"}
    >
      <section className="px-4 sm:px-6 pt-6 pb-6 max-w-6xl mx-auto">
        {/* Filters Section */}
        <motion.div
          className="bg-white/95 backdrop-blur-sm rounded-xl shadow-[0_12px_35px_rgba(15,81,50,0.14)] border border-[#0f5132]/12 p-4 sm:p-5 mb-6 md:sticky md:top-0 z-20"
          initial="hidden"
          animate="visible"
          variants={staggerContainer}
        >
          <div className="flex flex-col lg:flex-row lg:flex-nowrap lg:items-stretch lg:justify-between gap-4">
            {/* Animal Type Filter */}
            <div className="flex-1 lg:flex-none  rounded-2xl border border-[#0f5132]/10 bg-[#0f5132]/[0.03] p-3">
              <h3 className="text-sm font-semibold text-[#0f5132] mb-2 flex items-center gap-2">
                <span className="w-1.5 h-1.5 bg-[#0f5132] rounded-full"></span>
                {tUi("filters.animal_type")}
              </h3>
              <div className="grid grid-cols-3 gap-2">
                {(["all", "horse", "camel"] as const).map((tab) => (
                  <motion.button
                    key={tab}
                    type="button"
                    onClick={() => setActiveTab(tab)}
                    variants={tabVariants}
                    // whileHover={{ scale: 1.01 }}
                    whileTap={{ scale: 0.99 }}
                    className={`w-full px-3 py-2 rounded-full text-xs sm:text-sm font-medium border transition-all duration-200 leading-tight cursor-pointer ${
                      activeTab === tab
                        ? "bg-[#0f5132] text-white border-[#0f5132] shadow-[0_6px_16px_rgba(15,81,50,0.35)]"
                        : "bg-white text-slate-700 border-slate-200 hover:border-[#0f5132]/35 hover:bg-[#0f5132]/[0.05]"
                    }`}
                  >
                    {tab === "all"
                      ? tUi("filters.all")
                      : tab === "horse"
                        ? tUi("filters.horse")
                        : tUi("filters.camel")}
                  </motion.button>
                ))}
              </div>
            </div>

            {/* Status Filter */}
            <div className="flex-1 lg:flex-none  rounded-2xl border border-[#0f5132]/10 bg-[#0f5132]/[0.03] p-3">
              <h3 className="text-sm font-semibold text-[#0f5132] mb-2 flex items-center gap-2">
                <span className="w-1.5 h-1.5 bg-[#0f5132] rounded-full"></span>
                {tUi("filters.auction_status")}
              </h3>
              {/* Status chips (all breakpoints) */}
              <div className="flex flex-wrap gap-2">
                {(["all", "upcoming", "live", "ended"] as const).map((status) => {
                  const cfg = status === "all" ? null : AUCTION_STATUS[status];
                  const activeClass =
                    status === "all"
                      ? "bg-[#0f5132] text-white border-[#0f5132] shadow-[0_6px_16px_rgba(15,81,50,0.28)]"
                      : status === "upcoming"
                        ? "bg-amber-500 text-white border-amber-500 shadow-[0_6px_16px_rgba(245,158,11,0.28)]"
                        : status === "live"
                          ? "bg-red-500 text-white border-red-500 shadow-[0_6px_16px_rgba(239,68,68,0.28)]"
                          : "bg-slate-500 text-white border-slate-500 shadow-[0_6px_16px_rgba(100,116,139,0.24)]";
                  const idleClass =
                    status === "all"
                      ? "bg-white text-slate-700 border-slate-200 hover:border-[#0f5132]/35 hover:bg-[#0f5132]/[0.05]"
                      : `${cfg!.bgLight} ${cfg!.text} ${cfg!.border} hover:brightness-95`;

                  return (
                    <motion.button
                      key={status}
                      type="button"
                      onClick={() => setStatusFilter(status)}
                      className={`px-4 py-2 rounded-full text-xs sm:text-sm font-medium border transition-all whitespace-nowrap cursor-pointer ${
                        statusFilter === status ? activeClass : idleClass
                      }`}
                    >
                      {status === "all" ? tUi("filters.all_statuses") : cfg!.label}
                    </motion.button>
                  );
                })}
              </div>
            </div>

            {/* Usage Filter */}
            {shouldShowUsageFilter && (
              <div className="flex-1 min-w-0 rounded-2xl border border-[#0f5132]/10 bg-[#0f5132]/[0.03] p-3">
                <h3 className="text-sm font-semibold text-[#0f5132] mb-2 flex items-center gap-2">
                  <span className="w-1.5 h-1.5 bg-[#0f5132] rounded-full"></span>
                  {tUi("filters.usage")}
                </h3>
                {/* Mobile/Tablet: Select */}
                <Select
                  label={tUi("filters.usage")}
                  labelPlacement="outside"
                  selectedKeys={[usageFilter]}
                  onSelectionChange={onUsageSelectionChange}
                  variant="bordered"
                  size="sm"
                  className="w-full lg:hidden"
                  classNames={{
                    label: "text-[#0f5132] font-semibold text-xs py-1",
                    trigger:
                      "border rounded-xl border-[#0f5132]/20 bg-white px-3 h-11 py-2 focus-within:ring-2 focus-within:ring-[#0f5132]/35",
                    value: "text-sm text-slate-700",
                    listboxWrapper: "bg-white rounded-lg shadow-md border border-[#0f5132]/12",
                  }}
                  items={usageSelectItems}
                >
                  {(u) => (
                    <SelectItem key={u.key} textValue={u.label}>
                      {u.label}
                    </SelectItem>
                  )}
                </Select>

                {/* Desktop: chips */}
                <div
                  className="hidden lg:flex flex-nowrap gap-2 overflow-x-auto min-w-0 hide-scrollbar pb-1"
                  dir={isRtl ? "rtl" : "ltr"}
                >
                  <motion.button
                    key="usage_all"
                    type="button"
                    onClick={() => setUsageFilter("all")}
                    className={`px-4 py-2 rounded-full text-sm font-medium border transition-all whitespace-nowrap cursor-pointer
        ${
          usageFilter === "all"
            ? "bg-[#0f5132] text-white border-[#0f5132] shadow-[0_6px_16px_rgba(15,81,50,0.28)]"
            : "bg-white text-slate-700 border-slate-200 hover:border-[#0f5132]/35 hover:bg-[#0f5132]/[0.05]"
        }
      `}
                  >
                    {tUi("filters.all")}
                  </motion.button>

                  {usageOptions.map((u) => (
                    <motion.button
                      key={u.id}
                      type="button"
                      onClick={() => setUsageFilter(u.name)}
                      className={`px-4 py-2 rounded-full text-sm font-medium border transition-all whitespace-nowrap cursor-pointer
        ${
          usageFilter === u.name
            ? "bg-[#0f5132] text-white border-[#0f5132] shadow-[0_6px_16px_rgba(15,81,50,0.28)]"
            : "bg-white text-slate-700 border-slate-200 hover:border-[#0f5132]/35 hover:bg-[#0f5132]/[0.05]"
        }
      `}
                    >
                      {u.name}
                    </motion.button>
                  ))}
                </div>
              </div>
            )}
          </div>
        </motion.div>

        {filtersLoading ? (
          <div className="flex justify-center py-16">
            <p className="text-sm text-slate-600">{tUi("pagination.loading")}</p>
          </div>
        ) : showEmptyState ? (
          <div className="bg-white rounded-xl shadow-md border border-slate-100 px-6 py-10 sm:px-10 sm:py-12 flex items-center justify-center">
            <div className="max-w-xl text-center space-y-6">
              <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-emerald-50 text-emerald-500 shadow-sm">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.8"
                  className="h-8 w-8"
                >
                  <circle cx="11" cy="11" r="6" />
                  <path d="m16 16 3.5 3.5" strokeLinecap="round" />
                </svg>
              </div>

              <div className="space-y-2">
                <h2 className="text-2xl sm:text-3xl font-extrabold text-slate-900">
                  {tUi("empty.title")}
                </h2>
                <p className="text-sm sm:text-base text-slate-600 leading-relaxed">
                  {tUi("empty.description")}
                </p>
              </div>

              <div className="flex flex-wrap items-center justify-center gap-3 pt-2">
                <button
                  type="button"
                  onClick={handleResetFilters}
                  className="inline-flex items-center gap-2 rounded-full px-6 py-2.5 bg-gradient-to-r from-emerald-500 to-emerald-600 text-white text-sm font-semibold shadow-md hover:shadow-lg transition-shadow"
                >
                  {tUi("empty.reset")}
                </button>

                <button
                  type="button"
                  className="inline-flex items-center gap-2 rounded-full px-6 py-2.5 border border-slate-200 bg-white text-sm font-semibold text-slate-700 hover:border-emerald-300 hover:text-emerald-700 transition-colors"
                >
                  {tUi("filters.change")}
                </button>
              </div>

              <div className="pt-2 flex items-center justify-center gap-2 text-xs sm:text-sm text-emerald-700">
                <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                <span>{tUi("empty.hint_updating")}</span>
              </div>
            </div>
          </div>
        ) : null}

        {!filtersLoading && !showEmptyState ? (
          <AnimatePresence mode="wait">
            <motion.div
              key={`${activeTab}-${statusFilter}-${usageFilter}`}
              className="grid gap-3 sm:gap-6 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 items-stretch"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.25, ease: "easeOut" }}
            >
              {filteredCards?.map((card) => {
                const theme = getCardTheme(card.badgeColor);
                const countLabel = getAnimalsCountLabel(card.animalType);

                return (
                  <AnnualAuctionCardItem
                    key={card.id}
                    card={card}
                    theme={theme}
                    countLabel={countLabel}
                    iconColor={iconColor}
                    formatCardDate={formatCardDate}
                    formatLiveCardDate={formatLiveCardDate}
                  />
                );
              })}
            </motion.div>
          </AnimatePresence>
        ) : null}

        {pagination.has_more && !showEmptyState && !filtersLoading ? (
          <div className="flex flex-col items-center gap-2 pt-4 pb-2">
            {loadMoreError ? (
              <p className="text-sm text-red-600">{tUi("pagination.load_error")}</p>
            ) : null}
            <button
              type="button"
              onClick={() => void loadMore()}
              disabled={loadingMore || filtersLoading}
              className="inline-flex items-center justify-center rounded-full px-8 py-3 text-sm font-semibold text-white bg-[#0f5132] shadow-md hover:bg-[#0c4028] disabled:opacity-60 disabled:pointer-events-none transition-colors"
            >
              {loadingMore ? tUi("pagination.loading") : tUi("pagination.load_more")}
            </button>
            <p className="text-xs text-slate-500">
              {tUi("pagination.showing_page", {
                page: pagination.current_page,
                last: pagination.last_page,
                total: pagination.total,
              })}
            </p>
          </div>
        ) : null}
      </section>
    </main>
  );
}
