"use client";

import { useEffect, useMemo, useState } from "react";
import { Button } from "@heroui/react";
import AuctionSettingsModal from "@/components/modals/AuctionSettingsModal";
import { useLocale, useTranslations } from "next-intl";
import {
  useAuctions,
  useDeleteAuction,
  type DashboardAuctionsFilters,
} from "@/lib/clientQueries";
import axios from "axios";
import { useSession } from "@/auth/session-provider";
import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { BaseModal } from "@/components/modal";
import DynamicButton from "@/components/button";
import { useAppToast } from "@/app/[lang]/providers";
import { useAuctionsRealtime } from "@/lib/socket/useAuctionsRealtime";
import { Trash2 } from "lucide-react";
import AtayaLoader from "@/components/loaders/AtayaLoader";
import { API_BASE_URL } from "@/lib/axios";

const API_URL = API_BASE_URL;
function Badge({ state }: { state: string }) {
  const t = useTranslations("DASHBOARD.AUCTIONS");

  const classes: Record<string, string> = {
    accepted: "bg-green-500 text-white",
    upcoming: "bg-amber-500 text-white",
    rejected: "bg-red-500 text-white",
    active: "bg-blue-500 text-white",
    sold: "bg-indigo-600 text-white",
    completed: "bg-slate-500 text-white",
    cancelled: "bg-gray-500 text-white",
    withdrawn: "bg-gray-700 text-white",
    unsold: "bg-orange-500 text-white",
    closed: "bg-slate-600 text-white",
    waiting_for_seller: "bg-violet-600 text-white",
  };

  const statusKeys: Record<string, string> = {
    accepted: "status.accepted",
    upcoming: "status.upcoming",
    rejected: "status.rejected",
    active: "status.active",
    sold: "status.sold",
    completed: "status.completed",
    cancelled: "status.cancelled",
    withdrawn: "status.withdrawn",
    unsold: "status.unsold",
    closed: "status.closed",
    waiting_for_seller: "status.waiting_for_seller",
  };

  const translationKey = statusKeys[state];
  const label = translationKey ? t(translationKey) : state;

  return (
    <span
      className={`px-2 py-1 rounded-lg text-xs font-bold ${
        classes[state] || "bg-slate-200"
      }`}
    >
      {label}
    </span>
  );
}

function AuctionType({
  animalType,
  isGroup,
}: {
  animalType: string;
  isGroup: boolean;
}) {
  const t = useTranslations("DASHBOARD.AUCTIONS");

  const animalTypeMap: Record<string, string> = {
    horse: t("animal_horse"),
    camel: t("animal_camel"),
    sheep: t("animal_sheep"),
  };

  return (
    <span>
      {animalTypeMap[animalType] || animalType}
      {isGroup && ` • ${t("group_auction")}`}
    </span>
  );
}

function formatAuctionDate(
  dateString: string,
  locale: string = "ar-EG",
): string {
  try {
    if (!dateString) return "";

    const normalized = dateString.replace(" ", "T");
    const date = new Date(normalized);
    if (isNaN(date.getTime())) {
      return dateString;
    }

    const options: Intl.DateTimeFormatOptions = {
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    };

    return date.toLocaleDateString(locale, options);
  } catch (error) {
    console.error("Error formatting date:", error);
    return dateString;
  }
}

export default function MyAuctionsTable() {
  const t = useTranslations("DASHBOARD.AUCTIONS");
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [filterStatus, setFilterStatus] = useState("");
  const [filterAnimalType, setFilterAnimalType] = useState("");
  const [filterIsGroup, setFilterIsGroup] = useState<"" | "yes" | "no">("");
  const [filterAuctionState, setFilterAuctionState] = useState("");
  const lang = useLocale();
  const session = useSession();
  const router = useRouter();
  const queryClient = useQueryClient();
  const toast = useAppToast();
  const token = session?.access_token;
  const deleteAuction = useDeleteAuction();
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const [withdrawModalOpen, setWithdrawModalOpen] = useState(false);
  const [withdrawAuctionId, setWithdrawAuctionId] = useState<string | null>(
    null,
  );
  const [withdrawSaving, setWithdrawSaving] = useState(false);

  const [enterMarketOpen, setEnterMarketOpen] = useState(false);
  const [enterMarketAuctionId, setEnterMarketAuctionId] = useState<
    string | null
  >(null);
  const [enterMarketAmount, setEnterMarketAmount] = useState<number>(0);
  const [enterMarketSaving, setEnterMarketSaving] = useState(false);

  useEffect(() => {
    const id = window.setTimeout(() => setDebouncedSearch(search.trim()), 400);
    return () => window.clearTimeout(id);
  }, [search]);

  const listFilters: DashboardAuctionsFilters = useMemo(() => {
    const f: DashboardAuctionsFilters = {};
    if (debouncedSearch) f.search = debouncedSearch;
    if (filterStatus)
      f.status = filterStatus as DashboardAuctionsFilters["status"];
    if (filterAnimalType)
      f.animal_type = filterAnimalType as "camel" | "horse";
    if (filterIsGroup === "yes") f.is_group = true;
    if (filterIsGroup === "no") f.is_group = false;
    if (filterAuctionState)
      f.auction_state = filterAuctionState as DashboardAuctionsFilters["auction_state"];
    return f;
  }, [
    debouncedSearch,
    filterStatus,
    filterAnimalType,
    filterIsGroup,
    filterAuctionState,
  ]);

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

  const auctions = data?.pages.flatMap((page) => page.data) || [];

  const clearFilters = () => {
    setSearch("");
    setDebouncedSearch("");
    setFilterStatus("");
    setFilterAnimalType("");
    setFilterIsGroup("");
    setFilterAuctionState("");
  };

  const hasActiveFilters =
    debouncedSearch !== "" ||
    filterStatus !== "" ||
    filterAnimalType !== "" ||
    filterIsGroup !== "" ||
    filterAuctionState !== "";

  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);

  const openWithdrawModal = (auctionId: string) => {
    setWithdrawAuctionId(auctionId);
    setWithdrawModalOpen(true);
  };

  const closeWithdrawModal = () => {
    setWithdrawModalOpen(false);
    setWithdrawAuctionId(null);
  };

  const confirmWithdraw = async () => {
    if (!withdrawAuctionId) return;
    try {
      setWithdrawSaving(true);
      emitWithdraw(String(withdrawAuctionId));
      toast.info(t("withdraw_toast_success"));
      closeWithdrawModal();
    } catch (e: any) {
      console.error(e);
      toast.error(
        e?.response?.data?.message || e?.message || t("withdraw_toast_error"),
      );
    } finally {
      setWithdrawSaving(false);
    }
  };

  const openEnterMarketModal = (auctionId: string) => {
    setEnterMarketAuctionId(auctionId);
    setEnterMarketAmount(0);
    setEnterMarketOpen(true);
  };

  const closeEnterMarketModal = () => {
    setEnterMarketOpen(false);
    setEnterMarketAuctionId(null);
    setEnterMarketAmount(0);
  };

  const confirmEnterMarket = async () => {
    if (!enterMarketAuctionId) return;
    const amt = Number(enterMarketAmount);
    if (!Number.isFinite(amt) || amt <= 0) {
      toast.warning(t("enter_market_invalid_amount"));
      return;
    }
    try {
      setEnterMarketSaving(true);
      // TODO: If backend later supports no-amount event, switch to `auction:enterMarket {auctionId}`.
      emitEnterMarketAmount(String(enterMarketAuctionId), amt);
      toast.info(t("enter_market_toast_success"));
      closeEnterMarketModal();
    } finally {
      setEnterMarketSaving(false);
    }
  };

  const socketAuctionIds = useMemo(() => {
    return auctions.map((a: any) => String(a.id)).slice(0, 50);
  }, [auctions]);

  const {
    realtimeById,
    emitWithdraw,
    emitEnterMarket,
    emitEnterMarketAmount,
    lastError,
  } = useAuctionsRealtime(socketAuctionIds, token);

  useEffect(() => {
    if (!lastError) return;

    // Map error codes to user-friendly messages
    const errorMap: Record<string, string> = {
      FORBIDDEN: t("socket_error_forbidden"),
      MARKET_ALREADY_SET: t("socket_error_market_already_set"),
      AUCTION_NOT_ACTIVE: t("socket_error_auction_not_active"),
      NOT_LIVE: t("socket_error_not_live"),
    };

    const message = errorMap[lastError.code] || lastError.message;
    toast.error(message);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [lastError]);

  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">
              {t("error_loading")}
            </h3>
            <p className="text-gray-600 mb-4">{error.message}</p>
            <Button
              variant="solid"
              color="primary"
              onPress={() => window.location.reload()}
            >
              {t("retry")}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      <BaseModal
        isOpen={withdrawModalOpen}
        onOpenChange={(open) => {
          if (!open) closeWithdrawModal();
        }}
        placement="center"
        title={t("withdraw_modal_title")}
        contentClassName="w-full max-w-[420px] rounded-xl text-primary"
        footer={
          <div className="flex w-full justify-end gap-2">
            <DynamicButton
              className="bg-gray-200 text-gray-800 py-2 px-4 rounded-lg"
              onClick={closeWithdrawModal}
              isDisabled={withdrawSaving}
            >
              {t("withdraw_modal_cancel")}
            </DynamicButton>
            <DynamicButton
              className="bg-red-600 hover:bg-red-700 text-white py-2 px-4 rounded-lg"
              onClick={confirmWithdraw}
              isDisabled={withdrawSaving}
            >
              {withdrawSaving ? "..." : t("withdraw_modal_confirm")}
            </DynamicButton>
          </div>
        }
      >
        <p className="text-sm text-gray-600 text-center">
          {t("withdraw_modal_body")}
        </p>
      </BaseModal>

      <BaseModal
        isOpen={enterMarketOpen}
        onOpenChange={(open) => {
          if (!open) closeEnterMarketModal();
        }}
        placement="center"
        title={t("enter_market_modal_title")}
        contentClassName="w-full max-w-[420px] rounded-xl text-primary"
        footer={
          <div className="flex w-full justify-end gap-2">
            <DynamicButton
              className="bg-gray-200 text-gray-800 py-2 px-4 rounded-lg"
              onClick={closeEnterMarketModal}
              isDisabled={enterMarketSaving}
            >
              {t("enter_market_modal_cancel")}
            </DynamicButton>
            <DynamicButton
              className="bg-primary text-white py-2 px-4 rounded-lg"
              onClick={confirmEnterMarket}
              isDisabled={enterMarketSaving || enterMarketAmount <= 0}
            >
              {enterMarketSaving ? "..." : t("enter_market_modal_confirm")}
            </DynamicButton>
          </div>
        }
      >
        <div className="space-y-3">
          <p className="text-sm text-gray-600 text-center">
            {t("enter_market_modal_body")}
          </p>
          <input
            type="number"
            min={1}
            value={enterMarketAmount || ""}
            onChange={(e) => setEnterMarketAmount(Number(e.target.value || 0))}
            placeholder={t("enter_market_placeholder")}
            className="w-full rounded-xl border px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>
      </BaseModal>

      <div className="space-y-4">
        <div>
          <div className="flex flex-col gap-4 mb-4">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <div>
                <h2 className="text-xl font-extrabold text-primary">
                  {t("title")}
                </h2>
                <div className="text-sm text-slate-500">
                  {t("subtitle")} ({auctions.length})
                </div>
              </div>

              <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto sm:max-w-md">
                <input
                  type="text"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder={t("search_placeholder")}
                  className="flex-1 min-w-[200px] px-3 py-2 border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/40"
                />
                {hasActiveFilters ? (
                  <Button
                    size="sm"
                    variant="flat"
                    className="shrink-0"
                    onPress={clearFilters}
                  >
                    {t("filters_clear")}
                  </Button>
                ) : null}
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
              <label className="flex flex-col gap-1 text-xs font-semibold text-slate-600">
                <span>{t("filters.status")}</span>
                <select
                  value={filterStatus}
                  onChange={(e) => setFilterStatus(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-primary/30"
                >
                  <option value="">{t("filters.all")}</option>
                  <option value="accepted">{t("status.accepted")}</option>
                  <option value="rejected">{t("status.rejected")}</option>
                  <option value="withdrawn">{t("status.withdrawn")}</option>
                  <option value="sold">{t("status.sold")}</option>
                  <option value="unsold">{t("status.unsold")}</option>
                  <option value="waiting_for_seller">
                    {t("status.waiting_for_seller")}
                  </option>
                </select>
              </label>
              <label className="flex flex-col gap-1 text-xs font-semibold text-slate-600">
                <span>{t("filters.animal_type")}</span>
                <select
                  value={filterAnimalType}
                  onChange={(e) => setFilterAnimalType(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-primary/30"
                >
                  <option value="">{t("filters.all")}</option>
                  <option value="camel">{t("animal_camel")}</option>
                  <option value="horse">{t("animal_horse")}</option>
                </select>
              </label>
              <label className="flex flex-col gap-1 text-xs font-semibold text-slate-600">
                <span>{t("filters.is_group")}</span>
                <select
                  value={filterIsGroup}
                  onChange={(e) =>
                    setFilterIsGroup((e.target.value || "") as "" | "yes" | "no")
                  }
                  className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-primary/30"
                >
                  <option value="">{t("filters.all")}</option>
                  <option value="yes">{t("filters.is_group_yes")}</option>
                  <option value="no">{t("filters.is_group_no")}</option>
                </select>
              </label>
              <label className="flex flex-col gap-1 text-xs font-semibold text-slate-600">
                <span>{t("filters.auction_state")}</span>
                <select
                  value={filterAuctionState}
                  onChange={(e) => setFilterAuctionState(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-primary/30"
                >
                  <option value="">{t("filters.all")}</option>
                  <option value="upcoming">{t("status.upcoming")}</option>
                  <option value="active">{t("status.active")}</option>
                  <option value="ended">{t("filters.auction_state_ended")}</option>
                </select>
              </label>
            </div>
          </div>

          {auctions.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">
                {hasActiveFilters ? t("no_auctions_filtered") : t("no_auctions")}
              </h3>
              <p className="text-gray-500">
                {hasActiveFilters
                  ? t("no_auctions_filtered_description")
                  : t("no_auctions_description")}
              </p>
            </div>
          ) : (
            <>
              {/* Cards Grid */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3">
                {auctions.map((auction: any) => {
                  const auctionId = String(auction.id);
                  const rt = realtimeById[auctionId];
                  const mergedStatus: string = String(
                    (rt?.status as any) ?? auction.status ?? "",
                  );
                  const mergedCurrentPrice =
                    typeof rt?.currentPrice === "number"
                      ? rt.currentPrice
                      : Number(
                          auction.current_price ??
                            auction.current_bid ??
                            auction.highest_bid ??
                            0,
                        );
                  const mergedReserveTriggered = Boolean(rt?.reserveTriggered);
                  const mergedCloseAtMs = rt?.closeAtMs ?? null;
                  const remainingSeconds =
                    mergedCloseAtMs && mergedReserveTriggered
                      ? Math.max(0, Math.ceil((mergedCloseAtMs - now) / 1000))
                      : null;
                  const timerText =
                    remainingSeconds != null
                      ? `${String(Math.floor(remainingSeconds / 60)).padStart(2, "0")}:${String(remainingSeconds % 60).padStart(2, "0")}`
                      : null;
                  const auctionTypeRaw = String(
                    auction.auction_type,
                  ).toLowerCase();
                  const isLive =
                    auctionTypeRaw.includes("live") ||
                    auctionTypeRaw.includes("مباشر");
                  const canEnterMarket = isLive && mergedStatus === "active";

                  // Badge styling based on status
                  const badgeConfig: Record<
                    string,
                    { dot: string; border: string; label: string }
                  > = {
                    active: {
                      dot: "bg-red-500",
                      border: "border-red-200",
                      label: t("card.badge_active"),
                    },
                    sold: {
                      dot: "bg-green-500",
                      border: "border-green-200",
                      label: t("card.badge_sold"),
                    },
                    completed: {
                      dot: "bg-green-500",
                      border: "border-green-200",
                      label: t("card.badge_completed"),
                    },
                    cancelled: {
                      dot: "bg-red-500",
                      border: "border-red-200",
                      label: t("card.badge_cancelled"),
                    },
                    withdrawn: {
                      dot: "bg-gray-500",
                      border: "border-gray-300",
                      label: t("card.badge_withdrawn"),
                    },
                    upcoming: {
                      dot: "bg-amber-500",
                      border: "border-amber-200",
                      label: t("card.badge_upcoming"),
                    },
                    accepted: {
                      dot: "bg-green-500",
                      border: "border-green-200",
                      label: t("card.badge_accepted"),
                    },
                    rejected: {
                      dot: "bg-red-500",
                      border: "border-red-200",
                      label: t("card.badge_rejected"),
                    },
                    unsold: {
                      dot: "bg-orange-500",
                      border: "border-orange-200",
                      label: t("card.badge_unsold"),
                    },
                    closed: {
                      dot: "bg-slate-500",
                      border: "border-slate-300",
                      label: t("card.badge_closed"),
                    },
                    waiting_for_seller: {
                      dot: "bg-violet-500",
                      border: "border-violet-200",
                      label: t("card.badge_waiting_for_seller"),
                    },
                  };

                  const badge = badgeConfig[mergedStatus] || {
                    dot: "bg-gray-400",
                    border: "border-gray-200",
                    label: mergedStatus,
                  };

                  return (
                    <article
                      key={auction.id}
                      className="bg-white border border-slate-200/60 rounded-2xl shadow-[0_14px_34px_rgba(2,6,23,0.08)] overflow-hidden"
                    >
                      {/* Media */}
                      <div className="relative h-[170px] bg-slate-100 overflow-hidden">
                        <img
                          src={
                            auction.main_image?.url ||
                            "https://endpoint-dev.diriw.com/storage/images/default/default.webp"
                          }
                          alt={auction.title}
                          className="w-full h-full object-cover"
                        />

                        {/* Top bar: badge + timer */}
                        <div className="absolute top-2.5 left-2.5 right-2.5 flex items-center justify-between gap-2">
                          <div
                            className={`inline-flex items-center gap-2 h-[30px] px-2.5 rounded-full bg-white ${badge.border} border text-xs font-extrabold shadow-[0_10px_18px_rgba(2,6,23,0.10)] whitespace-nowrap`}
                          >
                            <span
                              className={`w-2 h-2 rounded-full ${badge.dot}`}
                            />
                            {badge.label}
                          </div>

                          {mergedStatus === "active" && timerText && (
                            <div className="inline-flex items-center gap-2 h-[30px] px-2.5 rounded-full bg-white border border-slate-200 shadow-[0_10px_18px_rgba(2,6,23,0.10)] text-xs font-extrabold text-slate-500 whitespace-nowrap">
                              {t("card.ends_in_label")}:{" "}
                              <b className="text-red-600 tracking-wide">
                                {timerText}
                              </b>
                            </div>
                          )}
                        </div>

                        {/* Auction number */}
                        <div className="absolute bottom-2.5 right-2.5 bg-white/90 border border-slate-200 rounded-xl px-2 py-1.5 text-xs font-black shadow-[0_10px_18px_rgba(2,6,23,0.10)] whitespace-nowrap">
                          <span className="text-slate-500 font-bold ml-1.5">
                            {t("card.auction_number_label")}:{" "}
                          </span>
                          {auction.unique_id || auctionId.slice(0, 8)}
                        </div>
                      </div>

                      {/* Body */}
                      <div className="p-3">
                        <h3 className="text-lg font-black text-slate-900 leading-tight mb-1 line-clamp-1">
                          {auction.title}
                        </h3>

                        {/* Lineage / description */}
                        <div className="text-xs text-slate-500 leading-relaxed line-clamp-2 mb-2">
                          {auction.description || (
                            <>
                              <div className="line-clamp-2 py-3">
                                لا يوجد وصف حالي
                              </div>

                              {/* <span className="text-slate-400">
                                {t("card.lineage_father")}
                              </span>{" "}
                              <span className="text-slate-800 font-black">
                                {auction.father_name || "—"}
                              </span>
                              <span className="text-slate-300 mx-1.5">•</span>
                              <span className="text-slate-400">
                                {t("card.lineage_mother")}
                              </span>{" "}
                              <span className="text-slate-800 font-black">
                                {auction.mother_name || "—"}
                              </span> */}
                            </>
                          )}
                        </div>

                        {/* Meta row */}
                        <div className="mt-2 flex items-center justify-between gap-2 p-2.5 border border-slate-100 rounded-xl bg-slate-50/50">
                          <div className="flex flex-col gap-0.5 min-w-0">
                            <div className="text-[11px] text-slate-500 font-bold">
                              {t("card.meta_auction_type")}
                            </div>
                            <div className="text-[13px] text-slate-900 font-black truncate">
                              <AuctionType
                                animalType={auction.animal_type}
                                isGroup={auction.is_group}
                              />
                            </div>
                          </div>
                          <div className="flex flex-col gap-0.5 min-w-0 text-left">
                            <div className="text-[11px] text-slate-500 font-bold">
                              {mergedStatus === "sold" ||
                              mergedStatus === "completed"
                                ? t("card.meta_last_price")
                                : t("card.meta_status")}
                            </div>
                            <div
                              className={`text-[13px] font-black truncate ${
                                mergedStatus === "active"
                                  ? "text-red-600"
                                  : mergedStatus === "sold" ||
                                      mergedStatus === "completed"
                                    ? "text-green-600"
                                    : "text-slate-600"
                              }`}
                            >
                              {mergedStatus === "sold" ||
                              mergedStatus === "completed"
                                ? `${mergedCurrentPrice.toLocaleString("en-EG")} ${t("payment.currency")}`
                                : badge.label}
                            </div>
                          </div>
                        </div>

                        {/* Actions */}
                        <div className="mt-2.5 flex flex-wrap gap-2">
                          {/** Delete constraints: cannot delete if unsold & has purchase offers */}
                          {(() => {
                            const isUnsold = mergedStatus === "unsold";
                            const hasPurchaseOffers = Boolean(
                              (auction as any)?.has_purchase_offers,
                            );
                            const canDelete = !(isUnsold && hasPurchaseOffers);

                            return (
                              <button
                                type="button"
                                onClick={async () => {
                                  if (!canDelete) {
                                    toast.warning(
                                      t("cannot_delete_has_offers"),
                                    );
                                    return;
                                  }

                                  if (!confirm(t("confirm_delete"))) return;

                                  try {
                                    setDeletingId(auctionId);
                                    const res = await deleteAuction.mutateAsync(
                                      {
                                        id: auctionId,
                                      },
                                    );
                                    if (res?.success) {
                                      toast.success(t("delete_success"));
                                      queryClient.invalidateQueries({
                                        queryKey: ["auctions"],
                                      });
                                    } else {
                                      toast.error(
                                        (res as any)?.message ||
                                          t("delete_error"),
                                      );
                                    }
                                  } catch (e: any) {
                                    toast.error(
                                      e?.response?.data?.message ||
                                        e?.message ||
                                        t("delete_error"),
                                    );
                                  } finally {
                                    setDeletingId(null);
                                  }
                                }}
                                disabled={
                                  !canDelete || deletingId === auctionId
                                }
                                className="flex-1 min-w-[70px] h-10 rounded-xl border border-red-200 bg-white text-red-600 font-black text-[13px] flex items-center justify-center gap-1 hover:bg-red-50 active:scale-[0.99] transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                <Trash2 className="w-4 h-4" />
                                {deletingId === auctionId
                                  ? t("card.actions.deleting")
                                  : t("card.actions.delete")}
                              </button>
                            );
                          })()}
                          <button
                            onClick={() =>
                              router.push(
                                `/${lang}/dashboard/auctions/${auction.id}/view?tab=auctions`,
                              )
                            }
                            className="flex-1 min-w-[90px] h-10 rounded-xl border border-slate-200 bg-white text-slate-900 font-black text-[13px] flex items-center justify-center gap-2 hover:bg-slate-50 active:scale-[0.99] transition-all"
                          >
                            <svg
                              className="w-[18px] h-[18px]"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            >
                              <path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7z" />
                              <circle cx="12" cy="12" r="3" />
                            </svg>
                            {t("card.actions.view")}
                          </button>

                          <button
                            onClick={() =>
                              router.push(
                                `/${lang}/dashboard/auctions/${auction.id}/edit?tab=auctions`,
                              )
                            }
                            disabled={
                              auction.status === "cancelled" ||
                              auction.status === "completed"
                            }
                            className="flex-1 min-w-[90px] h-10 rounded-xl border border-slate-200 bg-white text-slate-900 font-black text-[13px] flex items-center justify-center gap-2 hover:bg-slate-50 active:scale-[0.99] transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            <svg
                              className="w-[18px] h-[18px]"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            >
                              <path d="M12 20h9" />
                              <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />
                            </svg>
                            {t("card.actions.edit")}
                          </button>

                          {Boolean(auction?.can_edit_status) && (
                            <button
                              onClick={() => openWithdrawModal(auctionId)}
                              disabled={
                                mergedStatus === "cancelled" ||
                                mergedStatus === "completed" ||
                                mergedStatus === "withdrawn"
                              }
                              className="flex-1 min-w-[90px] h-10 rounded-xl border border-slate-200 bg-white text-slate-900 font-black text-[13px] flex items-center justify-center gap-2 hover:bg-slate-50 active:scale-[0.99] transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                              <svg
                                className="w-[18px] h-[18px]"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                              >
                                <path d="M20 6H4" />
                                <path d="M10 11h10" />
                                <path d="M10 15h10" />
                                <path d="M4 10l3 2-3 2" />
                              </svg>
                              {t("card.actions.withdraw")}
                            </button>
                          )}

                          {canEnterMarket && (
                            <button
                              onClick={() => {
                                emitEnterMarket(auctionId);
                                toast.info(t("enter_market_request_sent"));
                              }}
                              disabled={[
                                "cancelled",
                                "completed",
                                "withdrawn",
                                "closed",
                                "ended",
                              ].includes(mergedStatus)}
                              className="flex-1 min-w-[90px] h-10 rounded-xl border border-green-200 bg-white text-green-600 font-black text-[13px] flex items-center justify-center gap-2 hover:bg-green-50 active:scale-[0.99] transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                              {t("card.actions.enter_market")}
                            </button>
                          )}
                        </div>
                      </div>
                    </article>
                  );
                })}
              </div>

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