"use client";

import { useState } from "react";
import { Button } from "@heroui/react";
import { useLocale, useTranslations } from "next-intl";
import { usePathname, useRouter } from "next/navigation";
import { useAnnualGroupAuctions } from "@/lib/clientQueries";
import AtayaLoader from "@/components/loaders/AtayaLoader";

function formatDateTime(value: string | null, locale: string = "ar-EG") {
  if (!value) return "—";
  try {
    // date-only: 2026-01-17
    if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
      const d = new Date(`${value}T00:00:00`);
      if (Number.isNaN(d.getTime())) return value;
      return d.toLocaleDateString(locale, {
        year: "numeric",
        month: "short",
        day: "numeric",
      });
    }

    const normalized = value.replace(" ", "T");
    const d = new Date(normalized);
    if (Number.isNaN(d.getTime())) return value;
    return d.toLocaleString(locale, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return value ?? "—";
  }
}

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",
    withdrawn: "bg-red-500 text-white",
    pulled: "bg-red-500 text-white",
  };

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

  return (
    <span
      className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-bold ${cls}`}
    >
      {label || "-"}
    </span>
  );
}

export default function AnnualGroupAuctionsTable() {
  const tDash = useTranslations("DASHBOARD");
  const t = useTranslations("DASHBOARD.MAZAYADATY");
  const lang = useLocale();
  const router = useRouter();
  const pathname = usePathname();

  const langPrefix = pathname?.startsWith(`/${lang}/`) ? `/${lang}` : "";

  const [activeDay, setActiveDay] = useState<1 | 2 | 3>(1);

  const formatAnimalType = (value: any) => {
    const v = String(value || "").toLowerCase();
    if (v === "horse") return t("animal.horse");
    if (v === "camel") return t("animal.camel");
    return value ?? "—";
  };

  const formatAuctionState = (value: any) => {
    const v = String(value || "").toLowerCase();
    const map: Record<string, string> = {
      upcoming: t("state.upcoming"),
      active: t("state.active"),
      ended: t("state.ended"),
      withdrawn: t("state.withdrawn"),
      closed: t("state.closed"),
      finished: t("state.finished"),
      live: t("state.live"),
      running: t("state.running"),
      pending: t("state.pending"),
      accepted: t("state.accepted"),
    };
    return map[v] || (value ?? "—");
  };

  const {
    data,
    isLoading,
    error,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useAnnualGroupAuctions();

  const items = data?.pages.flatMap((p) => p.data) ?? [];

  if (isLoading) {
    return <AtayaLoader />;
  }

  if (error) {
    return (
      <div className="space-y-4">
        <div>
          <div className="text-center p-8">
            <div className="text-red-500 text-6xl mb-4">⚠️</div>
            <h3 className="text-lg font-bold text-red-600 mb-2">
              {tDash("AUCTIONS.error_loading")}
            </h3>
            <p className="text-gray-600 mb-4">{error.message}</p>
            <Button
              variant="solid"
              color="primary"
              onPress={() => window.location.reload()}
            >
              {tDash("DASHBOARD.AUCTIONS.retry")}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div>
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-xl font-extrabold text-primary">
              {tDash("mazayadaty")}
            </h2>
            <div className="text-sm text-slate-500">
              {t("subtitle", { count: items.length })}
            </div>
          </div>
        </div>

        {/*   <div className="flex items-center gap-2 mb-4">
          {[1, 2, 3].map((day) => {
            const isActive = activeDay === day;
            return (
              <button
                key={day}
                type="button"
                onClick={() => setActiveDay(day as 1 | 2 | 3)}
                className={`px-4 py-1.5 rounded-full border text-sm transition-colors ${
                  isActive
                    ? "bg-[#0F5132] text-white border-[#0F5132]"
                    : "bg-white text-slate-700 border-slate-200 hover:bg-slate-50"
                }`}
              >
                اليوم {day}
              </button>
            );
          })}
        </div> */}

        {items.length === 0 ? (
          <div className="text-center p-8">
            <div className="text-gray-400 text-6xl mb-4">🎪</div>
            <h3 className="text-lg font-bold text-gray-600 mb-2">
              {tDash("AUCTIONS.no_auctions")}
            </h3>
            <p className="text-gray-500">
              {tDash("AUCTIONS.no_auctions_description")}
            </p>
          </div>
        ) : (
          <>
            <div className="overflow-auto">
              <table className="w-full text-sm border rounded-2xl overflow-hidden">
                <thead>
                  <tr className="text-center bg-slate-50">
                    <th className="p-3 border">{t("columns.index")}</th>
                    <th className="p-3 border">{t("columns.logo")}</th>
                    <th className="p-3 border">{t("columns.title")}</th>
                    <th className="p-3 border">{t("columns.location")}</th>
                    <th className="p-3 border">{t("columns.animal_type")}</th>
                    <th className="p-3 border">{t("columns.state")}</th>
                    {/*                     <th className="p-3 border">{t("columns.premium_uses")}</th>
                     */}{" "}
                    <th className="p-3 border">{t("columns.auction_start")}</th>
                    <th className="p-3 border">
                      {t("columns.auction_details")}
                    </th>
                    <th className="p-3 border">
                      {t("columns.participation_details")}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {items.map((item: any, index: number) => (
                    <tr key={item.id} className="border-b hover:bg-slate-50">
                      <td className="p-3 border text-center">{index + 1}</td>
                      <td className="p-3 border text-center">
                        <img
                          src={
                            item.logo?.url ||
                            "https://endpoint-dev.diriw.com/storage/images/default/default.webp"
                          }
                          alt={item.title}
                          className="h-10 w-14 object-cover rounded-lg mx-auto"
                        />
                      </td>
                      <td className="p-3 border text-start max-w-xs">
                        <div className="font-medium text-gray-900">
                          {item.title}
                        </div>
                        <div className="text-gray-500 text-xs mt-1 line-clamp-2">
                          {item.description}
                        </div>
                      </td>
                      <td className="p-3 border text-center">
                        {item.country} - {item.state}
                      </td>
                      <td className="p-3 border text-center">
                        {formatAnimalType(item.animal_type)}
                      </td>
                      <td className="p-3 border text-center">
                        <StatusBadge
                          state={item.auction_state}
                          label={formatAuctionState(item.auction_state)}
                        />
                      </td>

                      <td className="p-3 border text-center">
                        {formatDateTime(item.auction_start_date, lang)}
                      </td>
                      <td className="p-3 border text-center">
                        <Button
                          size="sm"
                          variant="flat"
                          onPress={() => {
                            router.push(
                              `${langPrefix}/annual-auctions/${item.id}`,
                            );
                          }}
                        >
                          {t("actions.view")}
                        </Button>
                      </td>
                      <td className="p-3 border text-center">
                        <Button
                          size="sm"
                          variant="flat"
                          onPress={() => {
                            router.push(
                              `${langPrefix}/dashboard/my-group-auctions/${item.id}`,
                            );
                          }}
                        >
                          {t("actions.my_participation")}
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {hasNextPage && (
              <div className="flex justify-center mt-4">
                <Button
                  variant="solid"
                  color="primary"
                  onPress={() => fetchNextPage()}
                  isLoading={isFetchingNextPage}
                >
                  {isFetchingNextPage
                    ? tDash("AUCTIONS.loading_more")
                    : tDash("AUCTIONS.load_more")}
                </Button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
