"use client";

import { useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { AuctionType, AuctionStatus } from "@/lib/socket/types";

export default function AuctionTimer({
  auctionType,
  endTimeMs,
  closeAtMs,
  reserveTriggered,
  status,
}: {
  auctionType: AuctionType;
  endTimeMs?: number | null;
  closeAtMs?: number | null;
  reserveTriggered?: boolean;
  status?: AuctionStatus | string;
}) {
  const tAuction = useTranslations("AUCTION");

  const normalizedStatus = status as AuctionStatus | undefined;
  const isEnded =
    normalizedStatus === "ended" ||
    normalizedStatus === "withdrawn" ||
    normalizedStatus === "closed";

  const [now, setNow] = useState(() => Date.now());

  const tickMs = useMemo(() => {
    if (isEnded) return 0;
    // Live rolling timer takes priority
    if (reserveTriggered && closeAtMs) return 200;
    if (auctionType === "electronic" && endTimeMs) return 1000;
    return 0;
  }, [auctionType, reserveTriggered, closeAtMs, endTimeMs, isEnded]);

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

  if (isEnded) {
    const endedLabel =
      normalizedStatus === "withdrawn"
        ? tAuction("status_withdrawn")
        : normalizedStatus === "closed"
          ? tAuction("status_closed")
          : tAuction("status_ended");
    return (
      <div className="auction-timer auction-timer-ended mt-3">
        <input
          readOnly
          value={endedLabel}
          className="w-full rounded-xl border px-3 py-3 text-sm bg-transparent"
        />
      </div>
    );
  }

  // Show live rolling timer FIRST (takes priority) when reserve is triggered and we have a closeAtMs
  // (show regardless of auctionType to handle detection issues)
  if (reserveTriggered && closeAtMs) {
    // 3-Phase countdown logic: 90s total = 3 phases of 30s each
    const TOTAL_DURATION_MS = 90000;
    const PHASE_DURATION_MS = 30000;

    const remainingMs = Math.max(0, closeAtMs - now);
    const elapsedMs = Math.min(TOTAL_DURATION_MS, TOTAL_DURATION_MS - remainingMs);
    const phaseIndex = Math.min(2, Math.floor(elapsedMs / PHASE_DURATION_MS));
    const phaseRemainingMs = PHASE_DURATION_MS - (elapsedMs % PHASE_DURATION_MS);
    const phaseRemainingSeconds = Math.ceil(phaseRemainingMs / 1000);

    // Get phase labels from translations
    const phaseLabels = [
      tAuction("phase_1_label"),
      tAuction("phase_2_label"),
      tAuction("phase_3_label"),
    ];
    const phaseLabel = phaseLabels[phaseIndex];

    // Format phase remaining time as MM:SS
    const mm = Math.floor(phaseRemainingSeconds / 60);
    const ss = phaseRemainingSeconds % 60;
    const text = `${String(mm).padStart(2, "0")}:${String(ss).padStart(2, "0")}`;

    // Show urgent styling when total remaining is ≤ 10s
    const totalSeconds = Math.ceil(remainingMs / 1000);
    const isUrgent = totalSeconds <= 10;

    return (
      <div className="auction-timer auction-timer-live mt-3">
        <div className="text-sm font-bold text-[#0F5132] mb-2">
          {phaseLabel}
        </div>
        <input
          readOnly
          value={text}
          className={[
            "w-full rounded-xl border px-3 py-3 font-mono text-2xl font-extrabold tracking-wide bg-transparent",
            isUrgent ? "auction-timer-urgent" : "",
          ]
            .filter(Boolean)
            .join(" ")}
        />
      </div>
    );
  }

  // Electronic auction timer (only if no live timer is active)
  if (auctionType === "electronic" && endTimeMs) {
    const remaining = Math.max(0, endTimeMs - now);
    const s = Math.floor((remaining / 1000) % 60);
    const m = Math.floor((remaining / (1000 * 60)) % 60);
    const h = Math.floor((remaining / (1000 * 60 * 60)) % 24);
    const d = Math.floor(remaining / (1000 * 60 * 60 * 24));

    const text = `${String(d).padStart(2, "0")}:${String(h).padStart(
      2,
      "0"
    )}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;

    return (
      <div className="auction-timer auction-timer-electronic mt-3">
        <div className="text-xs text-slate-600 mb-1">
          {tAuction("electronic_timer_label")}
        </div>
        <input
          readOnly
          value={text}
          className="w-full rounded-xl border px-3 py-3 font-mono text-lg font-bold tracking-wide bg-transparent"
        />
      </div>
    );
  }

  return null;
}


