"use client";

import Image from "next/image";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState, type MouseEvent } from "react";
import { useSession } from "@/auth/session-provider";
import { useGeneralSettings, useToggleFavorite } from "@/lib/clientQueries";
import { useLocale, useTranslations } from "next-intl";
import AuctionUnifiedTimer from "@/components/count/AuctionUnifiedTimer";

type Auction = {
  id: string;
  title: string;
  /** `auction_state` from API (active | upcoming | ended | …). */
  status?: string | null;
  /** Listing sale outcome, API `status` (e.g. unsold). */
  listingStatus?: string | null;
  category?: string;
  img?: string;
  animalType?: "horse" | "camel";
  auctionType?: string | null;
  country?: string;
  city?: string;
  unique_id?: string;
  breed?: string;
  color?: string;
  bids?: number;
  winner?: string;
  timeLeft?: string;
  auctionStartTime?: string;
  auctionEndTime?: string;
  price?: string | number | null;
  isFavorite?: boolean;
  onToggleFavorite?: (id: string) => void;
};

type CardTheme = {
  accentBar: string;
  badge: string;
};

const reviewStatusTheme: Record<string, CardTheme> = {
  pending: {
    accentBar: "bg-amber-500",
    badge: "bg-amber-50 text-amber-700 border-amber-200",
  },
  accepted: {
    accentBar: "bg-emerald-500",
    badge: "bg-emerald-50 text-emerald-700 border-emerald-200",
  },
  rejected: {
    accentBar: "bg-red-500",
    badge: "bg-red-50 text-red-700 border-red-200",
  },
  null: {
    accentBar: "bg-slate-400",
    badge: "bg-slate-100 text-slate-700 border-slate-200",
  },
};

const auctionStateTheme: Record<string, CardTheme> = {
  active: {
    accentBar: "bg-red-500",
    badge: "bg-red-50 text-red-700 border-red-200",
  },
  upcoming: {
    accentBar: "bg-amber-500",
    badge: "bg-amber-50 text-amber-700 border-amber-200",
  },
  ended: {
    accentBar: "bg-slate-400",
    badge: "bg-slate-100 text-slate-700 border-slate-200",
  },
  unsold: {
    accentBar: "bg-orange-400",
    badge: "bg-orange-50 text-orange-800 border-orange-200",
  },
};

const DEFAULT_SAR_ICON = "/Riyal.svg";

function isUnsoldListingStatus(raw: unknown): boolean {
  const rawStr = String(raw ?? "").trim();
  if (!rawStr) return false;
  const s = rawStr.toLowerCase().replace(/\s+/g, "_");
  if (s === "unsold" || s === "not_sold" || s === "notsold") return true;
  if (rawStr.includes("غير مباع") || rawStr.includes("لم يتم البيع"))
    return true;
  return false;
}

export default function AuctionCard({
  id,
  title,
  unique_id,
  status,
  listingStatus,
  category,
  img,
  animalType,
  auctionType,
  country,
  city,
  breed,
  color,
  bids,
  winner,
  timeLeft,
  auctionStartTime,
  auctionEndTime,
  price,
  isFavorite,
  onToggleFavorite,
}: Auction) {
  const router = useRouter();
  const params = useParams();
  const lang = (params?.lang as string) || "";
  const session = useSession();
  const { data: settings } = useGeneralSettings();
  const toggleFavoriteMutation = useToggleFavorite();
  const locale = useLocale();
  const t = useTranslations("AUCTION_CARD");
  const isRtl = (locale || "").toLowerCase().startsWith("ar");
  const [favoriteState, setFavoriteState] = useState(Boolean(isFavorite));
  const canShowFavorite = Boolean(session?.access_token);

  const settingUrl = (value: any): string | undefined => {
    if (!value) return undefined;
    if (typeof value === "string") return value;
    if (typeof value === "object" && typeof value.url === "string")
      return value.url;
    return undefined;
  };
  const platformFallbackImage =
    animalType === "camel"
      ? settingUrl((settings as any)?.platform_1_image) || "/images/banner.avif"
      : animalType === "horse"
        ? settingUrl((settings as any)?.platform_2_image) ||
        "/images/unnamed.jpg"
        : "/images/placeholder.jpg";

  const [timerLabel, setTimerLabel] = useState<string | null>(null);
  const [timerTarget, setTimerTarget] = useState<number | null>(null);
  const isSaleUnsold =
    isUnsoldListingStatus(listingStatus) || isUnsoldListingStatus(status);
  const priceDisplay =
    price != null && String(price).trim() !== "" ? String(price) : null;
  const showPriceRow = Boolean(priceDisplay) || isSaleUnsold;

  useEffect(() => {
    setFavoriteState(Boolean(isFavorite));
  }, [isFavorite]);

  const parseTargetMs = (raw: any): number | null => {
    if (!raw) return null;
    if (raw instanceof Date) {
      const ms = raw.getTime();
      return Number.isFinite(ms) ? ms : null;
    }

    let s = String(raw).trim();
    if (!s) return null;

    // Numeric timestamps: seconds (10 digits) or milliseconds (13+ digits)
    if (/^\d+$/.test(s)) {
      const n = Number(s);
      if (!Number.isFinite(n)) return null;
      const ms = s.length <= 10 ? n * 1000 : n;
      return Number.isFinite(ms) ? ms : null;
    }

    // Normalize some backend formats:
    // - "YYYY:MM:DD HH:mm:ss"  -> "YYYY-MM-DD HH:mm:ss"
    // - "YYYY/MM/DD HH:mm"     -> "YYYY-MM-DD HH:mm"
    s = s.replace(/^([0-9]{4})[:\/-]([0-9]{2})[:\/-]([0-9]{2})/, "$1-$2-$3");

    // Common API format: "YYYY-MM-DD HH:mm:ss" -> ISO "YYYY-MM-DDTHH:mm:ss"
    const normalized = s.includes(" ") ? s.replace(" ", "T") : s;
    const ms = new Date(normalized).getTime();
    return Number.isFinite(ms) ? ms : null;
  };

  // نحدد هل status تمثّل حالة مزاد (من الباك) أو حالة مراجعة
  const isAuctionState = ["active", "upcoming", "ended", "unsold"].includes(
    status ?? "",
  );

  const badgeLabel = isAuctionState
    ? t(`auction_state.${status ?? "ended"}`)
    : t(`review_status.${status ?? "null"}`);

  const theme = isAuctionState
    ? (auctionStateTheme[status ?? "ended"] ?? auctionStateTheme.ended)
    : (reviewStatusTheme[status ?? "null"] ?? reviewStatusTheme.null);

  const auctionTypeRaw = String(auctionType || "").toLowerCase();
  const isLiveAuction = auctionTypeRaw.includes("live");
  const isElectronicAuction = auctionTypeRaw.includes("electronic");

  const auctionTypeLabel = isLiveAuction
    ? t("auction_type.live")
    : isElectronicAuction
      ? t("auction_type.electronic")
      : null;

  // تايمر بسيط (يبدأ بعد / ينتهي بعد) حسب حالة المزاد
  useEffect(() => {
    if (!isAuctionState) {
      setTimerLabel(null);
      setTimerTarget(null);
      return;
    }

    const startMs = parseTargetMs(auctionStartTime);
    const endMs = parseTargetMs(auctionEndTime);
    const now = Date.now();
    let effectiveStatus = status as string | undefined;
    let target: number | null = null;

    if (status === "upcoming") {
      // قبل البداية: نعدّ لوقت البداية
      target = startMs ?? parseTargetMs(timeLeft);
      effectiveStatus = "upcoming";
    } else if (status === "active") {
      if (isLiveAuction) {
        // المباشر: إذا ما في وقت نهاية من الباك نعتبره 24 ساعة من وقت البداية
        if (startMs) {
          const syntheticEnd = endMs ?? startMs + 24 * 60 * 60 * 1000;

          if (now < startMs) {
            // التايمر: يبدأ بعد (لبداية المزاد)
            target = startMs;
            effectiveStatus = "upcoming";
          } else if (now < syntheticEnd) {
            // التايمر: ينتهي بعد (حتى نهاية الـ 24 ساعة أو endMs لو موجود)
            target = syntheticEnd;
            effectiveStatus = "active";
          } else {
            // انتهت الـ 24 ساعة أو الوقت المحدد → إخفاء التايمر
            setTimerLabel(null);
            setTimerTarget(null);
            return;
          }
        } else if (endMs) {
          // احتياط: لو في نهاية بدون بداية
          target = endMs;
          effectiveStatus = "active";
        }
      } else {
        // إلكتروني أو أنواع أخرى: نعتمد على start/end من الباك
        if (!endMs && startMs && now < startMs) {
          // active لكن فعليًا لسه ما بدأ → نعتبره قادم
          target = startMs;
          effectiveStatus = "upcoming";
        } else {
          target = endMs ?? parseTargetMs(timeLeft);
          effectiveStatus = "active";
        }
      }
    }

    if (!target || !Number.isFinite(target)) {
      setTimerLabel(null);
      setTimerTarget(null);
      return;
    }

    const label =
      effectiveStatus === "upcoming"
        ? t("timer.starts_in")
        : effectiveStatus === "active"
          ? t("timer.ends_in")
          : null;
    setTimerLabel(label);
    setTimerTarget(target);
  }, [
    auctionStartTime,
    auctionEndTime,
    timeLeft,
    status,
    isAuctionState,
    isLiveAuction,
  ]);

  const handleCardClick = () => {
    if (lang) {
      router.push(`/${lang}/auctions/${id}`);
    } else {
      router.push(`/auctions/${id}`);
    }
  };

  const toggleFavorite = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();

    const next = !favoriteState;
    setFavoriteState(next);

    if (onToggleFavorite) {
      onToggleFavorite(id);
      return;
    }

    toggleFavoriteMutation.mutate(
      { id: String(id), type: "auction" },
      {
        onError: () => {
          setFavoriteState(!next);
        },
      },
    );
  };

  const formatPrice = (value: number) => value.toLocaleString("en-US");

  const FavoriteIcon = () => (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      className={`h-5 w-5 ${favoriteState ? "fill-current text-red-500" : ""}`}
      viewBox="0 0 24 24"
      fill={favoriteState ? "currentColor" : "none"}
      stroke="currentColor"
      strokeWidth="1.5"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.125 9 12 9 12s9-4.875 9-12z"
      />
    </svg>
  );

  return (
    <article
      className="group bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 relative cursor-pointer border border-slate-200 md:h-full flex flex-col"
      onClick={handleCardClick}
      dir={isRtl ? "rtl" : "ltr"}
    >
      <div className={`h-1.5 w-full ${theme.accentBar}`} />

      <div className="relative overflow-hidden h-56">
        <Image
          src={img || platformFallbackImage}
          alt={title}
          fill
          sizes="(max-width: 768px) 100vw, 33vw"
          className="object-cover transition-transform duration-500 group-hover:scale-105"
        />

        {canShowFavorite ? (
          <button
            type="button"
            className={`absolute top-3 z-10 h-10 w-10 rounded-full border border-slate-200 bg-white/95 grid place-items-center text-slate-600 shadow-sm transition-all duration-200 hover:shadow-md ${isRtl ? "left-3" : "right-3"
              }`}
            onClick={toggleFavorite}
            aria-label={
              favoriteState
                ? t("remove_favorite", { defaultValue: "إزالة من المفضلة" })
                : t("add_favorite", { defaultValue: "إضافة إلى المفضلة" })
            }
            title={
              favoriteState
                ? t("remove_favorite", { defaultValue: "إزالة من المفضلة" })
                : t("add_favorite", { defaultValue: "إضافة إلى المفضلة" })
            }
          >
            <FavoriteIcon />
          </button>
        ) : null}
      </div>

      <div className="p-4 text-start flex flex-col gap-3 flex-1">
        <div className="flex items-start justify-between gap-2">
          <h3 className="font-bold text-base text-[#0f5132] leading-snug line-clamp-2">
            {title}
          </h3>
          <span
            className={`inline-flex items-center absolute top-3 start-3 px-2.5 py-1 rounded-full border text-xs font-semibold whitespace-nowrap ${theme.badge}`}
          >
            {badgeLabel}
          </span>
        </div>

        <div className="flex flex-wrap items-center gap-2 text-xs">
          {category ? (
            <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 font-semibold text-slate-700">
              {category}
            </span>
          ) : null}

          {auctionTypeLabel ? (
            <span
              className={`rounded-full border px-2.5 py-1 font-semibold ${isLiveAuction
                  ? "border-red-200 bg-red-50 text-red-700"
                  : "border-slate-200 bg-slate-50 text-slate-700"
                }`}
            >
              {auctionTypeLabel}
            </span>
          ) : null}
        </div>

        <div className="text-xs text-slate-500 truncate">
          {country || "—"}، {city || "—"}
        </div>

        <div className="flex flex-wrap gap-2 text-xs text-slate-700">
          {breed ? (
            <span className="rounded-lg bg-slate-100 px-2.5 py-1">
              <strong>{t("labels.breed")}:</strong> {breed}
            </span>
          ) : null}

          {color ? (
            <span className="rounded-lg bg-slate-100 px-2.5 py-1">
              <strong>{t("labels.color")}:</strong> {color}
            </span>
          ) : null}
        </div>

        <div className="mt-auto space-y-2.5">
          {isAuctionState && timerLabel && timerTarget ? (
            <AuctionUnifiedTimer
              targetDate={timerTarget}
              label={timerLabel}
              variant="surface"
              compact
            />
          ) : null}
        </div>
        {showPriceRow ? (
          <div className="flex flex-wrap items-center justify-end gap-2">
            {priceDisplay ? (
              <div className="inline-flex items-center gap-1.5 text-sm font-bold text-[#0f5132]">
                {priceDisplay}
                <Image
                  src={DEFAULT_SAR_ICON}
                  width={16}
                  height={16}
                  alt={t("sar_alt", { defaultValue: "ريال سعودي" })}
                />
              </div>
            ) : null}
            {isSaleUnsold ? (
              <span className="rounded-full border border-orange-200 bg-orange-50 px-2.5 py-0.5 text-xs font-bold text-orange-800 whitespace-nowrap">
                {t("unsold_chip")}
              </span>
            ) : null}
          </div>
        ) : null}
      </div>
    </article>
  );
}
