import { useEffect, useState } from "react";
import clsx from "clsx";
import { Play, Pause, RotateCcw, Coffee, Timer as TimerIcon } from "lucide-react";
import { useAppStore } from "../../store/useAppStore";
import { notifyUser } from "../../api/tauri";
import { usePomodoroStore } from "./pomodoroStore";
import styles from "./PomodoroPanel.module.css";

/**
 * 工具栏中的番茄钟指示器：显示 MM:SS + 阶段点
 */
export function PomodoroIndicator({
  active,
  onClick,
  disabled = false,
}: {
  active: boolean;
  onClick: () => void;
  disabled?: boolean;
}) {
  const phase = usePomodoroStore((s) => s.phase);
  const remaining = usePomodoroStore((s) => s.remaining);
  const running = usePomodoroStore((s) => s.running);

  const text = formatTime(remaining);

  return (
    <button
      className={clsx(styles.indicator, active && styles.indicatorActive)}
      title={disabled ? "已锁定" : "番茄钟（点击展开）"}
      onClick={onClick}
      disabled={disabled}
    >
      <span
        className={clsx(
          styles.dot,
          running && phase === "work" && styles.dotWork,
          running && phase === "break" && styles.dotBreak,
          !running && styles.dotIdle
        )}
      />
      <span className={styles.time}>{text}</span>
    </button>
  );
}

function formatTime(sec: number): string {
  const m = Math.floor(sec / 60)
    .toString()
    .padStart(2, "0");
  const s = Math.floor(sec % 60)
    .toString()
    .padStart(2, "0");
  return `${m}:${s}`;
}

/**
 * 番茄钟展开面板：开始/暂停/重置 + 可调工作/休息时长
 */
export function PomodoroPanel() {
  const config = useAppStore((s) => s.pomodoro);
  const updatePomodoro = useAppStore((s) => s.updatePomodoro);

  const phase = usePomodoroStore((s) => s.phase);
  const remaining = usePomodoroStore((s) => s.remaining);
  const running = usePomodoroStore((s) => s.running);
  const start = usePomodoroStore((s) => s.start);
  const pause = usePomodoroStore((s) => s.pause);
  const reset = usePomodoroStore((s) => s.reset);
  const tick = usePomodoroStore((s) => s.tick);
  const setConfigInTimer = usePomodoroStore((s) => s.setConfig);

  // 同步配置到计时器
  useEffect(() => {
    setConfigInTimer({ workSec: config.workMin * 60, breakSec: config.breakMin * 60 });
  }, [config.workMin, config.breakMin, setConfigInTimer]);

  // 计时器主 tick
  useEffect(() => {
    if (!running) return;
    const id = window.setInterval(() => {
      const finished = tick();
      if (finished) {
        const next = phase === "work" ? "break" : "work";
        const title = next === "break" ? "工作完成" : "休息结束";
        const body =
          next === "break"
            ? `休息 ${config.breakMin} 分钟，放松一下吧。`
            : `继续专注 ${config.workMin} 分钟。`;
        void notifyUser(title, body);
      }
    }, 1000);
    return () => window.clearInterval(id);
  }, [running, tick, phase, config.workMin, config.breakMin]);

  // 监听全局快捷键事件
  useEffect(() => {
    const handler = () => {
      if (usePomodoroStore.getState().running) pause();
      else start();
    };
    window.addEventListener("deskfloat:toggle-pomodoro", handler);
    return () => window.removeEventListener("deskfloat:toggle-pomodoro", handler);
  }, [start, pause]);

  const [workMin, setWorkMin] = useState(config.workMin);
  const [breakMin, setBreakMin] = useState(config.breakMin);
  useEffect(() => setWorkMin(config.workMin), [config.workMin]);
  useEffect(() => setBreakMin(config.breakMin), [config.breakMin]);

  const total = phase === "work" ? config.workMin * 60 : config.breakMin * 60;
  const progress = total === 0 ? 0 : ((total - remaining) / total) * 100;

  return (
    <div className={styles.panel}>
      <div className={styles.header}>
        <div className={styles.title}>
          {phase === "work" ? <TimerIcon size={14} /> : <Coffee size={14} />}
          {phase === "work" ? "工作中" : "休息中"}
          <span className={styles.muted}>{formatTime(remaining)}</span>
        </div>
      </div>

      <div className={styles.progress}>
        <div
          className={clsx(
            styles.progressFill,
            phase === "work" ? styles.fillWork : styles.fillBreak
          )}
          style={{ width: `${progress}%` }}
        />
      </div>

      <div className={styles.controls}>
        {running ? (
          <button className={styles.primaryBtn} onClick={pause}>
            <Pause size={14} /> 暂停
          </button>
        ) : (
          <button className={styles.primaryBtn} onClick={start}>
            <Play size={14} /> 开始
          </button>
        )}
        <button className={styles.secondaryBtn} onClick={reset}>
          <RotateCcw size={14} /> 重置
        </button>
      </div>

      <div className={styles.config}>
        <div className={styles.field}>
          <label>工作 (分钟)</label>
          <input
            type="number"
            min={1}
            max={180}
            value={workMin}
            onChange={(e) => setWorkMin(Number(e.target.value))}
            onBlur={() => {
              const v = Math.max(1, Math.min(180, workMin || 25));
              updatePomodoro({ workMin: v });
              setWorkMin(v);
            }}
          />
        </div>
        <div className={styles.field}>
          <label>休息 (分钟)</label>
          <input
            type="number"
            min={1}
            max={60}
            value={breakMin}
            onChange={(e) => setBreakMin(Number(e.target.value))}
            onBlur={() => {
              const v = Math.max(1, Math.min(60, breakMin || 5));
              updatePomodoro({ breakMin: v });
              setBreakMin(v);
            }}
          />
        </div>
      </div>
    </div>
  );
}
