import { useState, useEffect } from "react";
import { Timer, Pause, Play } from "lucide-react";

interface LiveTimerProps {
  startedAt: string;
  pausedAt: string | null;
  pausedSeconds: number;
  label: string;
  variant: "red" | "blue";
  onPause: () => void;
  onResume: () => void;
  canControl: boolean;
  isToggling: boolean;
}

/**
 * Real-time elapsed timer that counts up from a given start timestamp,
 * subtracting accumulated pause time. Shows pause/resume controls.
 */
export default function LiveTimer({
  startedAt,
  pausedAt,
  pausedSeconds,
  label,
  variant,
  onPause,
  onResume,
  canControl,
  isToggling,
}: LiveTimerProps) {
  const [elapsed, setElapsed] = useState(0);
  const isPaused = pausedAt !== null;

  useEffect(() => {
    // Backend returns naive UTC datetimes without 'Z'. Force UTC so the
    // browser doesn't misinterpret them as local time (e.g. UTC+2 → 2h off).
    const utcStr = startedAt.endsWith("Z") || startedAt.includes("+") ? startedAt : startedAt + "Z";
    const start = new Date(utcStr).getTime();

    const tick = () => {
      const now = Date.now();
      const grossSeconds = Math.floor((now - start) / 1000);

      let totalPaused = pausedSeconds;
      if (isPaused) {
        const pausedAtUtc = pausedAt!.endsWith("Z") || pausedAt!.includes("+") ? pausedAt! : pausedAt! + "Z";
        const pauseStart = new Date(pausedAtUtc).getTime();
        totalPaused += Math.floor((now - pauseStart) / 1000);
      }

      setElapsed(Math.max(0, grossSeconds - totalPaused));
    };

    tick();
    if (!isPaused) {
      const interval = setInterval(tick, 1000);
      return () => clearInterval(interval);
    }
  }, [startedAt, pausedAt, pausedSeconds, isPaused]);

  const hours = Math.floor(elapsed / 3600);
  const minutes = Math.floor((elapsed % 3600) / 60);
  const seconds = elapsed % 60;
  const pad = (n: number) => String(n).padStart(2, "0");

  const colors = isPaused
    ? "border-yellow-500/40 bg-yellow-900/30 text-yellow-300"
    : variant === "red"
      ? "border-orange-500/40 bg-orange-900/30 text-orange-300"
      : "border-indigo-500/40 bg-indigo-900/30 text-indigo-300";

  const dotColor = isPaused
    ? "bg-yellow-400"
    : variant === "red"
      ? "bg-orange-400"
      : "bg-indigo-400";

  return (
    <div className={`flex items-center gap-2.5 rounded-lg border px-3 py-2 ${colors}`}>
      <div className="relative flex items-center">
        <Timer className="h-4 w-4" />
        <span
          className={`absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full ${dotColor} ${
            isPaused ? "" : "animate-pulse"
          }`}
        />
      </div>
      <div className="flex flex-col">
        <span className="text-[10px] font-medium uppercase tracking-wider opacity-70">
          {label}{isPaused ? " (Paused)" : ""}
        </span>
        <span className="font-mono text-sm font-bold tabular-nums">
          {pad(hours)}:{pad(minutes)}:{pad(seconds)}
        </span>
      </div>
      {canControl && (
        <button
          onClick={isPaused ? onResume : onPause}
          disabled={isToggling}
          className={`ml-1 rounded-md p-1.5 transition-colors disabled:opacity-50 ${
            isPaused
              ? "bg-green-600/20 text-green-400 hover:bg-green-600/30"
              : "bg-yellow-600/20 text-yellow-400 hover:bg-yellow-600/30"
          }`}
          title={isPaused ? "Resume timer" : "Pause timer"}
        >
          {isPaused ? <Play className="h-3.5 w-3.5" /> : <Pause className="h-3.5 w-3.5" />}
        </button>
      )}
    </div>
  );
}
