"use client";

import { useEffect, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { useRouter, useParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";

type InnerAuctionItem = {
  id: string | number;
  unique_id?: string | number;
  title?: string;
  horse_name?: string;
  horse_number?: string | number;
  animal?: {
    name?: string | null;
    father_name?: string | null;
    mother_name?: string | null;
    mother_father_name?: string | null;
    date_of_birth?: string | null;
    breed?: string | null;
  } | null;
  breed?: string;
  age?: string | number;
  birth_date?: string;
  date_of_birth?: string;
  owner_name?: string;
  stable_name?: string;
  start_time?: string;
  end_time?: string;
  duration_minutes?: number;
  main_image_url?: string;
  main_image?: { url?: string };
  media_files?: { main_image?: { url?: string } };
  winner_name?: string;
  status?: string;
  day?: number;
  animal_type?: string;
};

interface CamelInnerAuctionsTableProps {
  groupId: string | number;
  initialItems?: InnerAuctionItem[];
  initialNextCursor?: string | null;
  maxDays?: number;
  auctionState?: string;
  animalType?: "horse" | "camel";
  sampleLimit?: number;
}

// ===== Demo data helpers (used only when API data is not provided) =====

const DEMO_GALLERY = [
  "https://png.pngtree.com/thumb_back/fh260/background/20230612/pngtree-beautiful-black-horses-pictures-best-of-free-hd-wallpapers-horse-images-image_2951847.jpg",
  "https://blog.ajsrp.com/wp-content/uploads/2025/05/%D8%A7%D9%84%D8%AE%D9%8A%D9%84-%D8%A7%D9%84%D8%A3%D8%AF%D9%87%D9%85-696x398.jpg",
  "https://pbs.twimg.com/profile_images/1381035657611599877/pUb3dVAP_400x400.jpg",
  "https://artic.arabpage.net/wp-content/uploads/2020/02/765dbe37779ce1bca71be08d7c4f93b4.jpg",
];

function demoPickThumb(i: number) {
  return DEMO_GALLERY[i % DEMO_GALLERY.length];
}

function demoHorseName(lot: number) {
  return "الخيل " + lot;
}

function demoHorseAge(lot: number) {
  return `${4 + (lot % 5)} سنوات`;
}

function demoOwnerName(lot: number) {
  const owners = [
    "مربط النخبة",
    "مربط الصفا",
    "مربط العرين",
    "مربط الأصالة",
    "مربط العز",
    "مربط الندى",
  ];
  return owners[lot % owners.length];
}

function demoPickBreed(i: number) {
  const b = [
    "Egyptian",
    "Polish",
    "Straight Egyptian",
    "Desert Bred",
    "KSA Line",
    "Russian",
    "Crabbet",
  ];
  return b[i % b.length];
}

function buildDemoSchedule(): InnerAuctionItem[] {
  const auctionStart = new Date();
  auctionStart.setHours(10, 0, 0, 0);

  const durationMin = 15;
  const totalHorses = 100;
  const days = 3;
  const perDay = [34, 33, 33]; // 100

  const list: InnerAuctionItem[] = [];
  let lot = 101;

  for (let d = 0; d < days; d++) {
    for (let i = 0; i < perDay[d]; i++) {
      const start = new Date(
        auctionStart.getTime() + (d * 24 * 60 + i * durationMin) * 60000,
      );
      const end = new Date(start.getTime() + durationMin * 60000);

      list.push({
        id: lot,
        day: d + 1,
        horse_number: lot,
        title: demoHorseName(lot),
        breed: demoPickBreed(i),
        age: demoHorseAge(lot),
        owner_name: demoOwnerName(lot),
        start_time: start.toISOString(),
        end_time: end.toISOString(),
        duration_minutes: durationMin,
        main_image_url: demoPickThumb(i),
      });

      lot++;
      if (lot > 101 + totalHorses) break;
    }
  }

  return list;
}

function formatTimeRange(
  start?: string,
  end?: string,
  locale: string = "en-EN",
) {
  if (!start && !end) return "-";

  const fmt = new Intl.DateTimeFormat(locale, {
    hour: "2-digit",
    minute: "2-digit",
  });

  const startLabel = start ? fmt.format(new Date(start)) : "";
  const endLabel = end ? fmt.format(new Date(end)) : "";

  if (startLabel && endLabel) return `${startLabel} - ${endLabel}`;
  return startLabel || endLabel || "-";
}

function calcAgeYears(dob: string | null | undefined): number | null {
  if (!dob) return null;
  const d = new Date(dob);
  if (Number.isNaN(d.getTime())) return null;
  const now = new Date();
  let years = now.getFullYear() - d.getFullYear();
  const m = now.getMonth() - d.getMonth();
  if (m < 0 || (m === 0 && now.getDate() < d.getDate())) years -= 1;
  if (years < 0) years = 0;
  return years;
}

function formatBirthDate(
  dob: string | null | undefined,
  locale: string,
): string | null {
  if (!dob) return null;
  const d = new Date(dob);
  if (Number.isNaN(d.getTime())) return null;
  return new Intl.DateTimeFormat(locale || "ar", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(d);
}

function buildAnimalDisplayName(
  item: InnerAuctionItem,
  fallback: string,
): string {
  const parts = [
    item.animal?.name,
    item.animal?.father_name,
    item.animal?.mother_name,
  ]
    .map((x) => (x || "").toString().trim())
    .filter(Boolean);
  return parts.length ? parts.join(" - ") : fallback;
}

function StatusBadge({ state, label }: { state: string; label: string }) {
  const v = state.toLowerCase();
  const map: Record<string, string> = {
    active: "bg-emerald-500 text-white",
    running: "bg-emerald-500 text-white",
    live: "bg-emerald-500 text-white",
    accepted: "bg-emerald-500 text-white",
    pending: "bg-amber-500 text-white",
    upcoming: "bg-amber-500 text-white",
    finished: "bg-slate-500 text-white",
    closed: "bg-slate-500 text-white",
    sold: "bg-slate-700 text-white",
    unsold: "bg-orange-500 text-white",
    skipped: "bg-violet-600 text-white",
    withdrawn: "bg-red-500 text-white",
    pulled: "bg-red-500 text-white",
  };

  const cls = map[v] || "bg-slate-200 text-slate-800";
  const isLive = v === "active" || v === "running";

  return (
    <motion.span
      className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-bold ${cls}`}
      initial={{ scale: 0, opacity: 0 }}
      animate={{ scale: 1, opacity: 1 }}
      whileHover={{ scale: 1.1 }}
      {...(isLive && {
        animate: {
          scale: [1, 1.05, 1],
          boxShadow: [
            "0 0 0 0 rgba(16, 185, 129, 0.4)",
            "0 0 0 8px rgba(16, 185, 129, 0)",
          ],
        },
        transition: { duration: 1.5, repeat: Infinity },
      })}
    >
      {isLive && (
        <motion.span
          className="w-2 h-2 bg-white rounded-full mr-1.5"
          animate={{ opacity: [1, 0.3, 1] }}
          transition={{ duration: 1, repeat: Infinity }}
        />
      )}
      {label || "-"}
    </motion.span>
  );
}

export default function CamelInnerAuctionsTable({
  groupId,
  initialItems = [],
  initialNextCursor,
  maxDays = 0,
  auctionState,
  animalType,
  sampleLimit = 100,
}: CamelInnerAuctionsTableProps) {
  const lang = useLocale();
  const t = useTranslations("INNER_AUCTIONS_TABLE");
  const router = useRouter();
  const params = useParams<{ lang?: string }>();

  const resolveBackendStatus = (raw: string | null | undefined) => {
    const key = (raw || "").toString().trim().toLowerCase();
    if (!key) return { statusKey: "", statusLabel: "" };

    if (key === "accepted")
      return { statusKey: "accepted", statusLabel: t("status.accepted") };
    if (key === "pending" || key === "pendind")
      return { statusKey: "pending", statusLabel: t("status.pending") };
    if (key === "live")
      return { statusKey: "live", statusLabel: t("status.live") };
    if (key === "sold")
      return { statusKey: "sold", statusLabel: t("status.sold") };
    if (key === "skipped" || key === "تم التخطي")
      return { statusKey: "skipped", statusLabel: t("status.skipped") };
    if (key === "unsold" || key === "غير مباع" || key === "لم يتم البيع")
      return { statusKey: "unsold", statusLabel: t("status.unsold") };
    if (key === "withdrawn" || key === "مسحوب")
      return {
        statusKey: "withdrawn",
        statusLabel: t("status.withdrawn"),
      };
    if (key === "pulled")
      return { statusKey: "pulled", statusLabel: t("status.withdrawn") };

    return { statusKey: key, statusLabel: raw || key };
  };

  const isRtl = (lang || "").toLowerCase().startsWith("ar");

  const [items, setItems] = useState<InnerAuctionItem[]>(initialItems || []);
  const [nextCursor, setNextCursor] = useState<string | null | undefined>(
    initialNextCursor,
  );
  const [activeDay, setActiveDay] = useState<number | null>(null); // null = show all, no filter
  const [search, setSearch] = useState("");
  const [loadingItems, setLoadingItems] = useState(false);

  useEffect(() => {
    setItems(initialItems || []);
    setNextCursor(initialNextCursor);
  }, [initialItems, initialNextCursor]);

  // Fetch items from API when day filter is applied
  const fetchItemsByDay = async (dayNumber: number) => {
    setLoadingItems(true);
    try {
      const res = await fetch(
        `https://dev-endpoint.ataya.sa/api/user/group-auctions/${groupId}/auction-groups?day_number=${dayNumber}`,
      );
      const json = await res.json();
      const groups = (json?.data?.data || []) as any[];

      // Fetch single auctions for each group and flatten
      const allItems: InnerAuctionItem[] = [];
      for (const group of groups) {
        try {
          const singleRes = await fetch(
            `https://dev-endpoint.ataya.sa/api/user/group-auctions/${groupId}/single-auctions?auction_group_id=${group.id}`,
          );
          const singleJson = await singleRes.json();
          const singleItems = (singleJson?.data?.data ||
            []) as InnerAuctionItem[];
          allItems.push(...singleItems);
        } catch {
          // ignore individual group fetch errors
        }
      }
      setItems(allItems);
    } catch {
      setItems([]);
    } finally {
      setLoadingItems(false);
    }
  };

  // Handle day button click - only fetch when user clicks a day
  const handleDayClick = (day: number) => {
    setActiveDay(day);
    fetchItemsByDay(day);
  };

  const handleViewDetails = (item: InnerAuctionItem) => {
    const langParam = (params?.lang as string) || lang || "ar";
    const itemId = String(item.id ?? "");

    if (!itemId || itemId === "undefined" || itemId === "null") {
      alert(t("invalid_id"));
      return;
    }

    const url = `/${langParam}/annual-item/${itemId}`;
    window.open(url, "_blank", "noopener,noreferrer");
  };

  const locale = typeof lang === "string" ? lang : "en-EN";

  const totalDays = maxDays > 0 ? maxDays : 0;
  // When activeDay is null, show all items (no filter applied)
  // When activeDay is a number, items are already fetched filtered from API
  const dayItems = items;

  const dayButtons = Array.from({ length: totalDays }, (_, i) => i + 1);

  const normalizedSearch = search.trim().toLowerCase();

  const filteredItems =
    normalizedSearch.length === 0
      ? dayItems
      : dayItems.filter((item) => {
          const fallbackName =
            item.title ||
            item.horse_name ||
            `الخيل ${item.horse_number ?? item.id}`;
          const horseTitle = buildAnimalDisplayName(item, fallbackName);

          const ownerLabel = item.owner_name || item.stable_name || "";
          const breed = item.breed || "";
          const status = (item.status || "").toString();

          const haystack =
            `${horseTitle} ${ownerLabel} ${breed} ${status}`.toLowerCase();
          return haystack.includes(normalizedSearch);
        });

  const resolvedAnimalType = (animalType ||
    (items?.[0]?.animal_type as any) ||
    "horse") as "horse" | "camel";
  const isUpcoming = (auctionState || "").toLowerCase() === "upcoming";
  const entityLabel = t(`entity.${resolvedAnimalType}.plural`);
  const entityLabelSingle = t(`entity.${resolvedAnimalType}.single`);
  const sampleItems = isUpcoming
    ? filteredItems.slice(0, Math.max(0, Number(sampleLimit) || 0))
    : filteredItems;

  const handleExportCsv = () => {
    if (!filteredItems || filteredItems.length === 0) return;

    const delimiter = ";";

    const header = [
      t("export.time"),
      t("export.name"),
      t("export.breed"),
      t("export.age"),
      t("export.birth_date"),
      t("export.owner"),
      t("export.status"),
    ];

    const rows = filteredItems.map((item) => {
      const timeLabel = formatTimeRange(item.start_time, item.end_time, locale);

      const fallbackName =
        item.title ||
        item.horse_name ||
        `الخيل ${item.horse_number ?? item.id}`;
      const displayName = buildAnimalDisplayName(item, fallbackName);

      const breed = item.breed || "-";

      const dob = item.birth_date || item.date_of_birth;
      const ageYears = calcAgeYears(dob);
      const ageLabel =
        ageYears != null ? t("age_years", { count: ageYears }) : "-";
      const birthDateLabel = formatBirthDate(dob, lang) || "-";

      const ownerLabel = item.owner_name || item.stable_name || "-";

      let statusLabel = item.status || "";
      const backendResolved = resolveBackendStatus(item.status);
      if (backendResolved.statusKey) {
        statusLabel = backendResolved.statusLabel;
      }
      if (!statusLabel && item.start_time && item.end_time) {
        const now = new Date();
        const s = new Date(item.start_time);
        const e = new Date(item.end_time);

        if (now >= s && now < e) {
          statusLabel = t("status.running");
        } else if (now < s) {
          statusLabel = t("status.upcoming");
        } else {
          statusLabel = t("status.finished");
        }
      }

      return [
        timeLabel || "-",
        displayName,
        breed,
        ageLabel,
        birthDateLabel,
        ownerLabel,
        statusLabel || "-",
      ];
    });

    const escapeCsv = (value: string) => {
      if (value == null) return "";
      const v = value.toString().replace(/"/g, '""');
      if (new RegExp(`["${delimiter}\n]`).test(v)) {
        return `"${v}"`;
      }
      return v;
    };

    const csvContent = [header, ...rows]
      .map((row) => row.map((cell) => escapeCsv(String(cell))).join(delimiter))
      .join("\n");

    const BOM = "\uFEFF";
    const blob = new Blob([BOM + csvContent], {
      type: "text/csv;charset=utf-8;",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `inner-auctions-day-${activeDay}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <motion.section
      className="bg-white rounded-2xl shadow-md border border-slate-100 overflow-hidden"
      dir={isRtl ? "rtl" : "ltr"}
      initial={{ opacity: 0, y: 30 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.6, ease: [0.22, 1, 0.36, 1] }}
    >
      <motion.header
        className="px-4 md:px-6 pt-4 pb-3 border-b border-slate-100 flex flex-col gap-3 md:flex-row md:items-center md:justify-between"
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <div className="flex flex-col gap-1 text-sm text-slate-600">
          <span className="font-extrabold text-slate-900">
            {t("title_samples", { entity: entityLabel })}
          </span>
          <span className="text-xs text-slate-400">
            {t("subtitle_empty", { entity: entityLabel })}
          </span>
        </div>
        <div
          className={`flex flex-col items-stretch gap-2 ${
            isRtl ? "md:items-end" : "md:items-start"
          }`}
        >
          {totalDays > 0 && dayButtons.length > 0 && (
            <div
              className={`flex items-center gap-2 text-xs md:text-sm text-slate-500 flex-wrap ${
                isRtl ? "justify-end" : "justify-start"
              }`}
            >
              <button
                type="button"
                className={`tab-btn inline-flex items-center justify-center px-3 py-1 rounded-full border text-xs font-bold ${
                  activeDay === null
                    ? "border-emerald-600 text-emerald-700 bg-emerald-50"
                    : "border-slate-200 text-slate-600 bg-white"
                }`}
                onClick={() => {
                  setActiveDay(null);
                  setItems(initialItems || []);
                }}
              >
                {t("tab_all")}
              </button>
              {dayButtons.map((day) => (
                <button
                  key={day}
                  type="button"
                  className={`tab-btn inline-flex items-center justify-center px-3 py-1 rounded-full border text-xs font-bold ${
                    activeDay === day
                      ? "border-emerald-600 text-emerald-700 bg-emerald-50"
                      : "border-slate-200 text-slate-600 bg-white"
                  }`}
                  onClick={() => handleDayClick(day)}
                >
                  {t("day", { day })}
                </button>
              ))}
            </div>
          )}

          <div
            className={`flex flex-col sm:flex-row gap-2 items-stretch sm:items-center ${
              isRtl ? "justify-end" : "justify-start"
            }`}
          >
            <div className="relative w-full sm:w-64">
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full rounded-full border border-slate-200 px-3 py-1.5 text-xs md:text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500/60 focus:border-emerald-500 placeholder:text-slate-400 text-slate-700 bg-white"
                placeholder={t("search_placeholder", {
                  entity: entityLabelSingle,
                })}
              />
            </div>
            <button
              type="button"
              onClick={handleExportCsv}
              className="inline-flex items-center justify-center px-3 py-1.5 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 hover:bg-emerald-100 border border-emerald-100 whitespace-nowrap"
            >
              {t("export_excel")}
            </button>
          </div>
        </div>
      </motion.header>

      {loadingItems ? (
        <div className="py-10 text-center text-sm text-slate-500">
          {t("loading")}
        </div>
      ) : sampleItems.length === 0 ? (
        <div className="py-10 text-center text-sm text-slate-500">
          {t("empty", { entity: entityLabel })}
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[760px]">
            <thead>
              <tr className="bg-slate-50 text-xs text-slate-500">
                <th className="p-3 text-center font-semibold border-b border-slate-100 w-32">
                  {resolvedAnimalType === "horse"
                    ? t("th_id_horse")
                    : t("th_id_camel")}
                </th>
                <th className="p-3 text-start font-semibold border-b border-slate-100 w-64">
                  {t("th_name")}
                </th>
                <th className="p-3 text-center font-semibold border-b border-slate-100 w-28">
                  {t("th_status")}
                </th>
                <th className="p-3 text-center hover:cursor-pointer font-semibold border-b border-slate-100 w-36">
                  {t("th_view_details")}
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {sampleItems.map((item) => {
                const timeLabel = formatTimeRange(
                  item.start_time,
                  item.end_time,
                  locale,
                );

                const fallbackName =
                  item.title ||
                  item.horse_name ||
                  `الخيل ${item.horse_number ?? item.id}`;
                const horseTitle = buildAnimalDisplayName(item, fallbackName);

                const breed = item.breed || (item.animal as any)?.breed || "-";
                const dob =
                  item.birth_date ||
                  item.date_of_birth ||
                  (item.animal as any)?.date_of_birth;
                const ageYears = calcAgeYears(dob);
                const birthDateText = formatBirthDate(dob, lang);

                const imgUrl =
                  item.main_image_url ||
                  item.main_image?.url ||
                  item.media_files?.main_image?.url ||
                  "";

                // حالة الخيل (قادم / جاري / انتهى) بناءً على الوقت إذا لم تأتِ من الـ API
                const backend = resolveBackendStatus(item.status);
                let statusKey = backend.statusKey;
                let statusLabel = backend.statusLabel;

                if (!statusKey && item.start_time && item.end_time) {
                  const now = new Date();
                  const s = new Date(item.start_time);
                  const e = new Date(item.end_time);

                  if (now >= s && now < e) {
                    statusKey = "active";
                    statusLabel = t("status.running");
                  } else if (now < s) {
                    statusKey = "upcoming";
                    statusLabel = t("status.upcoming");
                  } else {
                    statusKey = "finished";
                    statusLabel = t("status.finished");
                  }
                }

                return (
                  <tr
                    key={item.id}
                    className="hover:bg-slate-50/60 transition-colors"
                  >
                    <td className="p-3 text-center align-middle text-xs text-slate-600 whitespace-nowrap font-mono">
                      {item.unique_id || item.id}
                    </td>

                    <td className="p-3 align-middle">
                      <div className="flex items-center gap-3">
                        {imgUrl ? (
                          <div className="w-16 h-12 rounded-lg overflow-hidden bg-slate-100 flex-shrink-0">
                            <img
                              src={imgUrl}
                              alt={horseTitle}
                              className="w-full h-full object-cover"
                            />
                          </div>
                        ) : (
                          <div className="w-16 h-12 rounded-lg bg-slate-100 flex items-center justify-center text-[10px] text-slate-400 flex-shrink-0">
                            {t("no_image")}
                          </div>
                        )}

                        <div className="flex flex-col gap-0.5 min-w-0">
                          <div className="text-sm font-extrabold text-slate-900 truncate">
                            {horseTitle}
                          </div>
                          <div className="text-[11px] text-slate-500 truncate">
                            {t("breed_label")}: {breed}
                          </div>
                          {ageYears != null && (
                            <div className="text-[11px] text-slate-500 truncate">
                              {t("age_label")}:{" "}
                              {t("age_years", { count: ageYears })}
                            </div>
                          )}
                          {birthDateText && (
                            <div className="text-[11px] text-slate-500 truncate">
                              {t("birth_date_label")}: {birthDateText}
                            </div>
                          )}
                        </div>
                      </div>
                    </td>

                    <td className="p-3 text-center align-middle whitespace-nowrap">
                      <StatusBadge
                        state={statusKey || "pending"}
                        label={statusLabel || "-"}
                      />
                    </td>

                    <td className="p-3 text-center align-middle">
                      <button
                        type="button"
                        onClick={() => {
                          console.log("🖱️ Button clicked for item:", item);
                          handleViewDetails(item);
                        }}
                        className="inline-flex items-center justify-center px-3 py-1.5 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 hover:bg-emerald-100 border border-emerald-100 hover:cursor-pointer"
                      >
                        {t("view_details")}
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {isUpcoming && filteredItems.length > sampleItems.length && (
        <div className="px-4 md:px-6 py-3 border-t border-slate-100 text-center text-xs text-slate-500">
          {t("showing_x_of_y", {
            shown: sampleItems.length,
            total: filteredItems.length,
          })}
        </div>
      )}

      {nextCursor && (
        <div className="px-4 md:px-6 py-3 border-t border-slate-100 text-center text-xs text-slate-500">
          {t("loading_rest_live")}
        </div>
      )}
    </motion.section>
  );
}
