"use client";

import { useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";

type AuctionUnifiedTimerProps = {
  targetDate: string | number | Date | null | undefined;
  label?: string | null;
  variant?: "overlay" | "surface";
  compact?: boolean;
  expiredText?: string;
  className?: string;
};

type TimerParts = {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
};

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

  if (typeof raw === "number") {
    if (!Number.isFinite(raw)) return null;
    return raw > 1e12 ? raw : raw * 1000;
  }

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

  if (/^\d+$/.test(s)) {
    const n = Number(s);
    if (!Number.isFinite(n)) return null;
    return s.length <= 10 ? n * 1000 : n;
  }

  s = s.replace(/^([0-9]{4})[:\/-]([0-9]{2})[:\/-]([0-9]{2})/, "$1-$2-$3");
  const normalized = s.includes("T") ? s : s.replace(" ", "T");
  const ms = new Date(normalized).getTime();
  return Number.isFinite(ms) ? ms : null;
}

export default function AuctionUnifiedTimer({
  targetDate,
  label,
  variant = "surface",
  compact = false,
  expiredText,
  className = "",
}: AuctionUnifiedTimerProps) {
  const tCountdown = useTranslations("COUNTDOWN");
  const [parts, setParts] = useState<TimerParts | null>(null);
  const [isExpired, setIsExpired] = useState(false);

  const targetMs = useMemo(() => parseTargetMs(targetDate), [targetDate]);

  useEffect(() => {
    if (!targetMs) {
      setParts(null);
      setIsExpired(false);
      return;
    }

    const update = () => {
      const diff = targetMs - Date.now();
      if (diff <= 0) {
        setIsExpired(true);
        setParts({ days: 0, hours: 0, minutes: 0, seconds: 0 });
        return;
      }

      setIsExpired(false);
      const totalSeconds = Math.floor(diff / 1000);
      const days = Math.floor(totalSeconds / 86400);
      const hours = Math.floor((totalSeconds % 86400) / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;
      setParts({
        days,
        hours,
        minutes,
        seconds,
      });
    };

    update();
    const interval = setInterval(update, 1000);
    return () => clearInterval(interval);
  }, [targetMs]);

  if (!targetMs) return null;

  const isOverlay = variant === "overlay";

  const wrapperClass = isOverlay
    ? "rounded-xl bg-black/40 backdrop-blur-[1px] px-2 py-2"
    : `rounded-xl border border-slate-200 bg-slate-50/80 ${
        compact ? "px-2 py-2" : "px-3 py-2.5"
      }`;

  const labelClass = isOverlay
    ? "text-white text-[11px]"
    : `${compact ? "text-[10px]" : "text-[11px]"} text-[#0f5132]`;

  const units = [
    { key: "d", value: parts?.days ?? 0, label: tCountdown("days") },
    { key: "h", value: parts?.hours ?? 0, label: tCountdown("hours") },
    { key: "m", value: parts?.minutes ?? 0, label: tCountdown("minutes") },
    { key: "s", value: parts?.seconds ?? 0, label: tCountdown("seconds") },
  ];

  return (
    <div className={`${wrapperClass} ${className}`}>
      <div className={`${isOverlay ? "flex items-center justify-between gap-2" : "space-y-2"}`}>
        {label ? (
          <span
            className={`inline-flex items-center gap-1 px-1.5 font-semibold whitespace-nowrap ${labelClass} ${
              isOverlay ? "" : "justify-center w-full"
            }`}
          >
            <span
              className={`w-1.5 h-1.5 rounded-full animate-pulse ${
                isOverlay ? "bg-white/80" : "bg-[#0f5132]"
              }`}
            />
            {label}
          </span>
        ) : (
          <span />
        )}

        {isExpired ? (
          <span
            className={`rounded-md border border-slate-200 bg-white px-2 py-1 text-[11px] font-semibold text-slate-600 ${
              isOverlay ? "" : "inline-flex justify-center w-full"
            }`}
          >
            {expiredText || tCountdown("expired")}
          </span>
        ) : (
          <div className={`grid grid-cols-4 ${compact ? "gap-1" : "gap-1.5"}`}>
            {units.map((item) => (
              <div key={item.key}>
                <div
                  className={`relative overflow-hidden rounded-xl border border-[#d4e0d9] bg-white text-gray-800 text-center shadow-[0_3px_10px_rgba(15,81,50,0.12)] font-semibold tabular-nums ${
                    compact ? "px-1 py-1 text-[10px]" : "px-2 py-1.5 text-[11px]"
                  }`}
                >
                  <div className={`${compact ? "mb-0 text-[8px]" : "mb-0.5 text-[9px]"} text-[#5f7e71] font-medium`}>
                    {item.label}
                  </div>
                  <div className={`${compact ? "text-sm" : "text-lg"} font-extrabold text-[#0f5132] leading-tight`}>
                    {String(item.value).padStart(2, "0")}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
