import { useState, useEffect } from "react";
import styles from "./TorchTimer.module.css";

const TORCH_DURATION_MS = 60 * 60 * 1000; // 60 minutes

interface TorchTimerProps {
  torchLitAt: string | null;
  onToggle: () => void;
}

export default function TorchTimer({ torchLitAt, onToggle }: TorchTimerProps) {
  const [remaining, setRemaining] = useState<number | null>(null);

  useEffect(() => {
    if (!torchLitAt) {
      setRemaining(null);
      return;
    }

    function tick() {
      const elapsed = Date.now() - new Date(torchLitAt!).getTime();
      const left = TORCH_DURATION_MS - elapsed;
      setRemaining(left > 0 ? left : 0);
    }

    tick();
    const interval = setInterval(tick, 1000);
    return () => clearInterval(interval);
  }, [torchLitAt]);

  const isLit = torchLitAt !== null && remaining !== null && remaining > 0;
  const isBurnedOut = torchLitAt !== null && remaining === 0;

  let urgency = "";
  if (isLit && remaining !== null) {
    const mins = remaining / 60000;
    if (mins <= 1) urgency = styles.critical;
    else if (mins <= 5) urgency = styles.danger;
    else if (mins <= 10) urgency = styles.warning;
  }

  function formatTime(ms: number): string {
    const totalSec = Math.ceil(ms / 1000);
    const m = Math.floor(totalSec / 60);
    const s = totalSec % 60;
    if (m === 0) return `${s}s`;
    return `${m}m`;
  }

  return (
    <button
      className={`${styles.torch} ${isLit ? styles.lit : ""} ${isBurnedOut ? styles.out : ""} ${urgency}`}
      onClick={onToggle}
      title={
        isLit
          ? `Torch: ${formatTime(remaining!)} remaining (click to extinguish)`
          : isBurnedOut
            ? "Torch burned out (click to light a new one)"
            : "Light a torch (1 hour)"
      }
    >
      <span className={styles.icon}>
        {isLit ? "\uD83D\uDD25" : "\uD83E\uDE94"}
      </span>
      {isLit && remaining !== null && (
        <span className={styles.time}>{formatTime(remaining)}</span>
      )}
    </button>
  );
}
