import { useEffect, useState } from "react";
import {
  Settings as SettingsIcon,
  ExternalLink,
  Power,
  Pin,
  Keyboard,
  Eye,
  Lock,
} from "lucide-react";
import { useAppStore } from "../../store/useAppStore";
import { openDataDir } from "../../api/tauri";
import {
  disable as disableAutostart,
  enable as enableAutostart,
  isEnabled as isAutostartEnabled,
} from "@tauri-apps/plugin-autostart";
import styles from "./SettingsPanel.module.css";

/** 设置面板：置顶 / 透明度 / 三个全局热键 / 开机自启 / 数据目录 */
export function SettingsPanel() {
  const settings = useAppStore((s) => s.settings);
  const updateSettings = useAppStore((s) => s.updateSettings);

  const [autostart, setAutostart] = useState(false);

  // 启动时读取系统当前的自启状态
  useEffect(() => {
    isAutostartEnabled()
      .then((v) => setAutostart(v))
      .catch(() => {});
  }, []);

  const toggleAutostart = async (v: boolean) => {
    try {
      if (v) await enableAutostart();
      else await disableAutostart();
      setAutostart(v);
      updateSettings({ autoStart: v });
    } catch (e) {
      console.error("[DeskFloat] autostart toggle failed:", e);
      alert("开机自启切换失败：" + (e as Error).message);
    }
  };

  const updateHotkey = (
    key: keyof typeof settings.globalHotkeys,
    val: string
  ) => {
    updateSettings({
      globalHotkeys: { ...settings.globalHotkeys, [key]: val },
    });
  };

  return (
    <div className={styles.panel}>
      <div className={styles.header}>
        <div className={styles.title}>
          <SettingsIcon size={14} /> 设置
        </div>
        <button
          className={styles.linkBtn}
          onClick={() => void openDataDir().catch(() => {})}
        >
          <ExternalLink size={11} /> 数据目录
        </button>
      </div>

      <div className={styles.body}>
        {/* 显示与置顶 */}
        <div className={styles.row}>
          <div className={styles.rowLabel}>
            <Pin size={12} /> 始终置顶
          </div>
          <Toggle
            checked={settings.alwaysOnTop}
            onChange={(v) => updateSettings({ alwaysOnTop: v })}
          />
        </div>

        <div className={styles.row}>
          <div className={styles.rowLabel}>
            <Lock size={12} /> 仅悬浮（锁定，防误触）
          </div>
          <Toggle
            checked={settings.locked}
            onChange={(v) => updateSettings({ locked: v })}
          />
        </div>

        <div className={styles.rowCol}>
          <div className={styles.rowLabel}>
            <Eye size={12} /> 背景透明度
            <span className={styles.muted}>
              {Math.round(settings.opacity * 100)}%
            </span>
          </div>
          <input
            type="range"
            min={0.3}
            max={1}
            step={0.05}
            value={settings.opacity}
            onChange={(e) =>
              updateSettings({ opacity: Number(e.target.value) })
            }
            className={styles.range}
          />
        </div>

        <div className={styles.row}>
          <div className={styles.rowLabel}>
            <Power size={12} /> 开机自启
          </div>
          <Toggle checked={autostart} onChange={toggleAutostart} />
        </div>

        <div className={styles.divider} />

        {/* 全局快捷键 */}
        <div className={styles.sectionTitle}>
          <Keyboard size={12} /> 全局快捷键
        </div>

        <HotkeyField
          label="显示 / 隐藏窗口"
          value={settings.globalHotkeys.showHide}
          onChange={(v) => updateHotkey("showHide", v)}
          placeholder="Ctrl+Alt+`"
        />
        <HotkeyField
          label="新建任务"
          value={settings.globalHotkeys.newTask}
          onChange={(v) => updateHotkey("newTask", v)}
          placeholder="Ctrl+Alt+T"
        />
        <HotkeyField
          label="番茄钟 开始/暂停"
          value={settings.globalHotkeys.togglePomodoro}
          onChange={(v) => updateHotkey("togglePomodoro", v)}
          placeholder="Ctrl+Alt+P"
        />

        <div className={styles.hint}>
          格式：修饰键 + 字母，例如{" "}
          <span className={styles.kbd}>Ctrl+Alt+T</span>。
        </div>
      </div>
    </div>
  );
}

/** 自定义开关组件 */
function Toggle({
  checked,
  onChange,
}: {
  checked: boolean;
  onChange: (v: boolean) => void;
}) {
  return (
    <label className={styles.toggle}>
      <input
        type="checkbox"
        checked={checked}
        onChange={(e) => onChange(e.target.checked)}
      />
      <span className={styles.toggleTrack}>
        <span className={styles.toggleThumb} />
      </span>
    </label>
  );
}

/** 单个全局快捷键编辑行 */
function HotkeyField({
  label,
  value,
  onChange,
  placeholder,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  placeholder: string;
}) {
  const [draft, setDraft] = useState(value);
  useEffect(() => setDraft(value), [value]);

  return (
    <div className={styles.hotkeyRow}>
      <span className={styles.hotkeyLabel}>{label}</span>
      <input
        value={draft}
        onChange={(e) => setDraft(e.target.value)}
        onBlur={() => {
          if (draft !== value) onChange(draft.trim());
        }}
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            (e.target as HTMLInputElement).blur();
          }
        }}
        placeholder={placeholder}
        className={styles.hotkeyInput}
      />
    </div>
  );
}
