"use client";

import { Chip } from "@heroui/react";
import { useLocale, useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { useUserPaddles } from "@/lib/clientQueries";
import PurchasePremiumPaddleModal from "@/components/paddles/PurchasePremiumPaddleModal";
import DynamicButton from "@/components/button";
import { useAppToast } from "@/app/[lang]/providers";
import AtayaLoader from "@/components/loaders/AtayaLoader";

const toNumber = (v: string | number | null | undefined) => {
  if (typeof v === "number") return v;
  if (!v) return 0;
  const n = Number(v);
  return Number.isNaN(n) ? 0 : n;
};

/** Resolve auction/group_auction image URL from API (image, main_image, or logo). */
function getAuctionImageUrl(auction: any): string | null {
  if (!auction) return null;
  const img = auction.image;
  if (img && typeof img === "string") return img;
  if (img?.url) return img.url;
  if (auction.main_image?.url) return auction.main_image.url;
  if (auction.logo?.url) return auction.logo.url;
  const mf = auction.media_files;
  if (mf?.main_image?.url) return mf.main_image.url;
  if (mf?.logo?.url) return mf.logo.url;
  return null;
}

export default function ParticipatedAuctionsSection() {
  const t = useTranslations("DASHBOARD.PARTICIPATED_AUCTIONS");
  const locale = useLocale();
  const router = useRouter();
  const isRtl = locale === "ar";
  const [premiumModalOpen, setPremiumModalOpen] = useState(false);
  const toast = useAppToast();

  const { data, isLoading, isError } = useUserPaddles({ per_page: 20 });
  const items = useMemo(() => {
    return ((data as any)?.data?.data ?? (data as any)?.data ?? []) as any[];
  }, [data]);

  const statusMeta = (state?: string) => {
    if (state === "live") {
      return {
        label: t("status_live"),
        className: "bg-emerald-50 text-emerald-700",
      };
    }
    if (state === "ended") {
      return {
        label: t("status_ended"),
        className: "bg-slate-100 text-slate-700",
      };
    }
    return {
      label: t("status_other"),
      className: "bg-amber-50 text-amber-700",
    };
  };

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

  if (isError) {
    return <div className="text-sm text-rose-600">{t("error")}</div>;
  }

  if (!items.length) {
    return (
      <div className="space-y-2">
        <h3 className="font-bold text-green-800 text-lg">{t("title")}</h3>
        <div className="text-sm text-slate-600">{t("empty")}</div>
      </div>
    );
  }

  const normalizePaddleType = (type?: string) =>
    String(type ?? "")
      .toLowerCase()
      .trim();

  const getTypeBadge = (type?: string) => {
    switch (normalizePaddleType(type)) {
      case "vip":
        return (
          <Chip className="bg-purple-100 text-purple-700 border-0 text-xs font-bold">
            {t("type_vip")}
          </Chip>
        );
      case "premium":
        return (
          <Chip className="bg-blue-100 text-blue-700 border-0 text-xs font-bold">
            {t("type_premium")}
          </Chip>
        );
      case "normal":
      default:
        return (
          <Chip className="bg-gray-100 text-gray-700 border-0 text-xs font-bold">
            {t("type_normal")}
          </Chip>
        );
    }
  };

  const getStatusBadge = (status?: string) => {
    switch (status) {
      case "active":
        return (
          <Chip className="bg-emerald-100 text-emerald-700 border-0 text-xs">
            {t("subscription_active")}
          </Chip>
        );
      case "consumed":
        return (
          <Chip className="bg-amber-100 text-amber-700 border-0 text-xs">
            {t("subscription_consumed")}
          </Chip>
        );
      case "expired":
        return (
          <Chip className="bg-red-100 text-red-700 border-0 text-xs">
            {t("subscription_expired")}
          </Chip>
        );
      default:
        return null;
    }
  };

  const getTypeLabel = (type?: string) => {
    const raw = normalizePaddleType(type);
    if (raw === "vip") return t("type_text.vip");
    if (raw === "premium") return t("type_text.premium");
    if (raw === "normal") return t("type_text.normal");
    return t("type_text.default");
  };

  const getStatusTextKey = (status?: string) => {
    if (!status) return "default";
    const allowed = new Set(["active", "consumed", "expired", "pending"]);
    return allowed.has(status) ? status : "default";
  };

  const formatDate = (dateString: string | null | undefined): string => {
    if (!dateString) return "";
    try {
      const date = new Date(dateString);
      return new Intl.DateTimeFormat("en-EN", {
        year: "numeric",
        month: "long",
        day: "numeric",
      }).format(date);
    } catch {
      return dateString;
    }
  };

  /**
   * Build href for "Enter auction" based on AuctionPaddleSubscriptionResource auction payload:
   * - type 'auction' → /{locale}/auctions/{id}
   * - type 'group_auction':
   *   - auction_state 'live' → /{locale}/annual-auctions/{id}/live
   *   - auction_state 'upcoming' → /{locale}/annual-auctions/{id}
   *   - auction_state 'ended' → /{locale}/annual-auctions/{id}/results
   */
  const getAuctionHref = (a: any, localePrefix: string): string | null => {
    if (!a?.id) return null;
    const locale = (localePrefix || "ar").split("-")[0] || "ar";
    const rawType = String(a?.type ?? a?.auction_type ?? "").toLowerCase();
    const isGroupAuction =
      rawType === "group_auction" ||
      rawType === "annual" ||
      rawType === "group" ||
      Boolean(a?.is_group);

    if (!isGroupAuction) {
      return `/${locale}/auctions/${a.id}`;
    }

    const state = String(a?.auction_state ?? "").toLowerCase();
    if (state === "live") return `/${locale}/annual-auctions/${a.id}/live`;
    if (state === "ended") return `/${locale}/annual-auctions/${a.id}/results`;
    // upcoming or any other state → show page
    return `/${locale}/annual-auctions/${a.id}`;
  };

  return (
    <div className="space-y-5" dir={isRtl ? "rtl" : "ltr"}>
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div>
          <p className="text-xs text-slate-500">{t("subtitle")}</p>
          <h3 className="font-extrabold text-lg text-[#0F5132]">
            {t("title")}
          </h3>
        </div>
        {/*  <DynamicButton
          variant="bordered"
          onClick={() => setPremiumModalOpen(true)}
          className="px-4 py-2 rounded-full text-sm border-[#0F5132] text-[#0F5132]"
        >
          {t("buy_premium_paddle")}
        </DynamicButton> */}
      </div>

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
        {items.map((p,index) => {
          console.log(`"P:" ${index}`,p)
          const a = p.auction || p.current_reservation?.auction;
          const href = a ? getAuctionHref(a, locale) : null;
          const participants = toNumber(a?.participation_count);
          const status = statusMeta(a?.auction_state);
          const uniqueId = a?.auction_unique_id || a?.unique_id;
          const title = a?.title || t("no_auction_title");
          const location = a?.animal_type
            ? `${t(`animal.${a.animal_type as "horse" | "camel"}`)} • ${
                a?.city || t("unknown_city")
              }`
            : t("unknown_city");
          const imageUrl = getAuctionImageUrl(a);

          return (
            <article
              key={p.id}
              className="bg-white border rounded-xl shadow-sm overflow-hidden flex flex-col"
            >
              <div className="relative h-40 bg-slate-100">
                {imageUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={imageUrl}
                    alt={title}
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full bg-gradient-to-br from-slate-100 via-slate-200 to-slate-50" />
                )}
                <div
                  className={`absolute top-3 ${isRtl ? "left-3" : "right-3"}`}
                >
                  <Chip
                    className={`${status.className} border-0 text-xs font-bold`}
                  >
                    {status.label}
                  </Chip>
                </div>
              </div>

              <div className="flex-1 p-4 space-y-4">
                <div className="flex items-start justify-between gap-3">
                  <div className="space-y-1 flex-1">
                    <span className="text-xs text-slate-400">
                      #{uniqueId ?? "—"}
                    </span>
                    <h4 className="text-base font-bold text-slate-900 line-clamp-2">
                      {title}
                    </h4>
                    <p className="text-xs text-slate-500 line-clamp-1">
                      {location}
                    </p>
                  </div>
                  <div className="flex flex-col gap-1 text-end">
                    {getTypeBadge(p.type)}
                    {getStatusBadge(p.status)}
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3 text-sm text-slate-600">
                  <div>
                    <div className="text-xs text-slate-400">
                      {t("columns.paddle")}
                    </div>
                    <div className="font-extrabold text-[#0F5132]">
                      #{p.paddle_number || p.unique_id || "—"}
                    </div>
                  </div>
                  <div>
                    <div className="text-xs text-slate-400">
                      {t("participants_label")}
                    </div>
                    <div className="font-semibold">
                      {participants
                        ? t("participants", { count: participants })
                        : t("participants", { count: 0 })}
                    </div>
                  </div>
                  <div>
                    <div className="text-xs text-slate-400">
                      {t("type_label")}
                    </div>
                    <div className="font-semibold capitalize">
                      {getTypeLabel(p.type)}
                    </div>
                  </div>
                  <div>
                    <div className="text-xs text-slate-400">
                      {t("status_label")}
                    </div>
                    <div className="font-semibold">
                      {t(`status_text.${getStatusTextKey(p.status)}`)}
                    </div>
                  </div>
                </div>

                <div className="flex flex-col gap-2 sm:flex-row">
                  {/*  <button
                    type="button"
                    onClick={() => toast.info(t("invoice_unavailable"))}
                    className="px-4 py-2 rounded-xl border border-slate-200 text-sm font-medium text-slate-700 hover:border-slate-300"
                  >
                    {t("paddle_invoice")}
                  </button> */}
                  <DynamicButton
                    onClick={() => {
                      if (!href) {
                        toast.warning(t("auction_unavailable"));
                        return;
                      }
                      router.push(href);
                    }}
                    isDisabled={!href}
                    className="flex-1"
                  >
                    {t("enter_auction")}
                  </DynamicButton>
                </div>
              </div>
            </article>
          );
        })}
      </div>

      <PurchasePremiumPaddleModal
        open={premiumModalOpen}
        onClose={() => setPremiumModalOpen(false)}
      />
    </div>
  );
}
