import { Pause, Play, RotateCcw } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { bnNum } from "@/lib/utils";

function format(seconds: number) {
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${bnNum(String(m).padStart(2, "0"))}:${bnNum(String(s).padStart(2, "0"))}`;
}

function chime() {
  try {
    const ctx = new AudioContext();
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    osc.type = "sine";
    osc.frequency.value = 784;
    gain.gain.value = 0.08;
    osc.connect(gain);
    gain.connect(ctx.destination);
    osc.start();
    gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.8);
    osc.stop(ctx.currentTime + 0.85);
  } catch {
    /* ignore */
  }
}

export function CookTimer({ minutes, resetKey }: { minutes: number; resetKey: string }) {
  const total = minutes * 60;
  const [left, setLeft] = useState(total);
  const [running, setRunning] = useState(false);
  const tick = useRef<number | null>(null);

  useEffect(() => {
    setLeft(total);
    setRunning(false);
  }, [resetKey, total]);

  useEffect(() => {
    if (!running) {
      if (tick.current) window.clearInterval(tick.current);
      return;
    }
    tick.current = window.setInterval(() => {
      setLeft((n) => {
        if (n <= 1) {
          setRunning(false);
          chime();
          return 0;
        }
        return n - 1;
      });
    }, 1000);
    return () => {
      if (tick.current) window.clearInterval(tick.current);
    };
  }, [running]);

  const done = left === 0;

  return (
    <div className="mt-6 flex flex-col items-center gap-4 rounded-[var(--radius-lg)] bg-bg-warm px-4 py-5">
      <p className="text-xs font-medium tracking-wide text-muted uppercase">টাইমার</p>
      <p
        className={`font-display text-5xl tabular-nums tracking-tight ${done ? "text-spice" : "text-ink"}`}
      >
        {format(left)}
      </p>
      <div className="flex gap-2">
        <Button
          type="button"
          variant={running ? "secondary" : "primary"}
          onClick={() => setRunning((v) => !v)}
          disabled={done}
        >
          {running ? <Pause /> : <Play />}
          {running ? "থামান" : "শুরু"}
        </Button>
        <Button
          type="button"
          variant="ghost"
          onClick={() => {
            setRunning(false);
            setLeft(total);
          }}
          aria-label="রিসেট"
        >
          <RotateCcw />
        </Button>
      </div>
    </div>
  );
}
