import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useTTSStore } from "@/stores/tts-store";
import { Clock3 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";

const PRESET_MINUTES = [15, 30, 45, 60] as const;

function formatRemainingLabel(endsAt: number | null): string | null {
  if (!endsAt) return null;
  const remainingMs = Math.max(0, endsAt - Date.now());
  if (remainingMs <= 0) return null;
  const totalSeconds = Math.max(1, Math.ceil(remainingMs / 1000));
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  if (hours > 0) {
    return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
  }
  return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}

export function TTSSleepTimerPanel() {
  const { t } = useTranslation();
  const sleepTimerEndsAt = useTTSStore((s) => s.sleepTimerEndsAt);
  const sleepTimerDurationMinutes = useTTSStore((s) => s.sleepTimerDurationMinutes);
  const setSleepTimer = useTTSStore((s) => s.setSleepTimer);
  const clearSleepTimer = useTTSStore((s) => s.clearSleepTimer);
  const [now, setNow] = useState(Date.now());
  const [customMinutes, setCustomMinutes] = useState(
    sleepTimerDurationMinutes ? String(sleepTimerDurationMinutes) : "30",
  );

  useEffect(() => {
    if (!sleepTimerEndsAt) return;
    setNow(Date.now());
    const timer = window.setInterval(() => {
      setNow(Date.now());
    }, 1000);
    return () => window.clearInterval(timer);
  }, [sleepTimerEndsAt]);

  useEffect(() => {
    setCustomMinutes(sleepTimerDurationMinutes ? String(sleepTimerDurationMinutes) : "30");
  }, [sleepTimerDurationMinutes]);

  const remainingLabel = useMemo(() => {
    void now;
    return formatRemainingLabel(sleepTimerEndsAt);
  }, [now, sleepTimerEndsAt]);

  const handleCustomMinutes = () => {
    const parsed = Number.parseInt(customMinutes.trim(), 10);
    if (!Number.isFinite(parsed) || parsed <= 0) return;
    setSleepTimer(parsed);
  };

  return (
    <div className="rounded-xl border border-border/70 bg-muted/20 p-3">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <Clock3 className="h-4 w-4 text-primary" />
            <span className="text-xs font-semibold text-foreground">{t("tts.sleepTimer", "定时停止")}</span>
          </div>
          <p className="mt-1 text-[11px] leading-5 text-muted-foreground">
            {remainingLabel
              ? t("tts.sleepTimerRemaining", {
                  time: remainingLabel,
                  defaultValue: `Remaining ${remainingLabel}`,
                })
              : t("tts.sleepTimerSubtitle", "让朗读在你设定的时间后自动停止")}
          </p>
        </div>

        <div className="flex min-h-8 min-w-[82px] items-center justify-center rounded-full border border-border/70 bg-background/85 px-3 text-xs font-semibold text-foreground">
          {remainingLabel || t("common.settings", "设置")}
        </div>
      </div>

      <div className="mt-3 flex flex-wrap items-center gap-2">
        {PRESET_MINUTES.map((minutes) => {
          const isActive = sleepTimerEndsAt && sleepTimerDurationMinutes === minutes;
          return (
            <Button
              key={minutes}
              type="button"
              variant={isActive ? "default" : "secondary"}
              size="sm"
              className="h-8 rounded-full px-3 text-xs"
              onClick={() => setSleepTimer(minutes)}
            >
              {t("tts.sleepTimerPresetShort", { minutes, defaultValue: `${minutes} min` })}
            </Button>
          );
        })}
        {sleepTimerEndsAt ? (
          <Button
            type="button"
            variant="ghost"
            size="sm"
            className="h-8 rounded-full px-3 text-xs text-muted-foreground"
            onClick={clearSleepTimer}
          >
            {t("tts.sleepTimerCancel", "Turn off sleep timer")}
          </Button>
        ) : null}
      </div>

      <div className="mt-3 flex items-center gap-2">
        <Input
          type="number"
          inputMode="numeric"
          min={1}
          value={customMinutes}
          onChange={(event) => setCustomMinutes(event.target.value)}
          className="h-8 text-xs"
          placeholder={t("tts.sleepTimerCustomPlaceholder", "Custom minutes")}
        />
        <Button type="button" size="sm" className="h-8 rounded-full px-3 text-xs" onClick={handleCustomMinutes}>
          {t("tts.sleepTimerApply", "Start timer")}
        </Button>
      </div>
    </div>
  );
}
