import { useEffect, useLayoutEffect, useRef, type MouseEvent } from "react";
import clsx from "clsx";
import {
  Zap,
  Settings as SettingsIcon,
  ChevronDown,
  ChevronUp,
  GripVertical,
  Lock,
  Unlock,
} from "lucide-react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { useAppStore } from "../../store/useAppStore";
import { setWindowSize } from "../../api/tauri";
import { TasksPanel, TasksTrigger } from "../../modules/tasks/TasksPanel";
import {
  ShortcutsBar,
  ShortcutsPanel,
} from "../../modules/shortcuts/ShortcutsPanel";
import {
  PomodoroIndicator,
  PomodoroPanel,
} from "../../modules/pomodoro/PomodoroPanel";
import { SettingsPanel } from "../../modules/settings/SettingsPanel";
import styles from "./Toolbar.module.css";

const BAR_WIDTH = 620;
const BAR_HEIGHT = 56;
const BAR_COLLAPSED_W = 200;
const BAR_COLLAPSED_H = 40;
const PANEL_WIDTH = 620;
const FALLBACK_PANEL_HEIGHT = 320;

/**
 * 浮动工具栏外壳：
 * - 拖动柄主动调用 startDragging，避免 data-tauri-drag-region 在部分环境下失效
 * - 抽屉面板高度通过 ResizeObserver 实时测量并同步到窗口尺寸
 */
export function Toolbar() {
  const activePanel = useAppStore((s) => s.activePanel);
  const setActivePanel = useAppStore((s) => s.setActivePanel);
  const collapsed = useAppStore((s) => s.collapsed);
  const toggleCollapsed = useAppStore((s) => s.toggleCollapsed);
  const locked = useAppStore((s) => s.settings.locked);
  const updateSettings = useAppStore((s) => s.updateSettings);

  // 进入锁定模式时关闭所有抽屉
  useEffect(() => {
    if (locked && activePanel) {
      useAppStore.setState({ activePanel: null });
    }
  }, [locked, activePanel]);

  const toggleLock = () => updateSettings({ locked: !locked });

  const panelRef = useRef<HTMLDivElement | null>(null);

  /** 显式调用 startDragging，最可靠的拖动方式；锁定状态下禁止拖动 */
  const startDrag = async (e: MouseEvent) => {
    if (e.button !== 0) return; // 仅左键
    if (locked) return; // 仅悬浮模式：拖动也禁用
    try {
      await getCurrentWindow().startDragging();
    } catch (err) {
      console.warn("[DeskFloat] startDragging failed", err);
    }
  };

  // 根据折叠/抽屉状态调整窗口尺寸（首次同步）
  useLayoutEffect(() => {
    if (collapsed) {
      void setWindowSize(BAR_COLLAPSED_W, BAR_COLLAPSED_H);
      return;
    }
    if (!activePanel) {
      void setWindowSize(BAR_WIDTH, BAR_HEIGHT);
      return;
    }
    const ph = panelRef.current?.offsetHeight ?? FALLBACK_PANEL_HEIGHT;
    void setWindowSize(BAR_WIDTH, BAR_HEIGHT + ph + 12);
  }, [activePanel, collapsed]);

  // 抽屉打开时，监听其实际高度变化（例如编辑器展开/折叠时）实时调整窗口
  useEffect(() => {
    if (collapsed || !activePanel || !panelRef.current) return;
    const el = panelRef.current;
    const ro = new ResizeObserver(() => {
      const ph = el.offsetHeight || FALLBACK_PANEL_HEIGHT;
      void setWindowSize(BAR_WIDTH, BAR_HEIGHT + ph + 12);
    });
    ro.observe(el);
    return () => ro.disconnect();
  }, [activePanel, collapsed]);

  return (
    <div className={styles.root}>
      <div
        className={clsx(
          styles.bar,
          collapsed && styles.barCollapsed,
          locked && styles.barLocked
        )}
      >
        {/* 左侧拖拽柄：主动 startDragging，避免环境差异；锁定时禁用 */}
        <div
          className={clsx(
            styles.dragHandle,
            locked && styles.dragHandleLocked
          )}
          onMouseDown={startDrag}
          title={locked ? "已锁定（请先解锁）" : "按住拖动移动窗口"}
        >
          <GripVertical size={14} />
        </div>

        {!collapsed && (
          <>
            <TasksTrigger
              active={activePanel === "tasks"}
              onClick={() => !locked && setActivePanel("tasks")}
              disabled={locked}
            />

            <div className={styles.divider} />

            <div
              className={clsx(
                styles.shortcutsRegion,
                locked && styles.disabledRegion
              )}
            >
              <ShortcutsBar disabled={locked} />
            </div>

            <div className={styles.divider} />

            <PomodoroIndicator
              active={activePanel === "pomodoro"}
              onClick={() => !locked && setActivePanel("pomodoro")}
              disabled={locked}
            />

            <button
              className={clsx(
                styles.iconBtn,
                activePanel === "shortcuts" && styles.iconBtnActive
              )}
              title={locked ? "已锁定（请先解锁）" : "管理快捷方式"}
              onClick={() => !locked && setActivePanel("shortcuts")}
              disabled={locked}
            >
              <Zap size={16} />
            </button>

            <button
              className={clsx(
                styles.iconBtn,
                activePanel === "settings" && styles.iconBtnActive
              )}
              title={locked ? "已锁定（请先解锁）" : "设置"}
              onClick={() => !locked && setActivePanel("settings")}
              disabled={locked}
            >
              <SettingsIcon size={16} />
            </button>
          </>
        )}

        {/* 锁定/解锁按钮：永远可点击，与折叠按钮并列 */}
        <button
          className={clsx(styles.iconBtn, locked && styles.lockBtnActive)}
          title={locked ? "解锁（恢复交互）" : "锁定（仅悬浮 / 防误触）"}
          onClick={toggleLock}
        >
          {locked ? <Lock size={14} /> : <Unlock size={14} />}
        </button>

        {/* 折叠/展开按钮 */}
        <button
          className={styles.iconBtn}
          title={collapsed ? "展开" : "折叠"}
          onClick={toggleCollapsed}
        >
          {collapsed ? <ChevronDown size={14} /> : <ChevronUp size={14} />}
        </button>
      </div>

      {activePanel && !collapsed && !locked && (
        <div
          className={styles.panelWrap}
          ref={panelRef}
          style={{ width: PANEL_WIDTH - 8 }}
        >
          {activePanel === "tasks" && <TasksPanel />}
          {activePanel === "shortcuts" && <ShortcutsPanel />}
          {activePanel === "pomodoro" && <PomodoroPanel />}
          {activePanel === "settings" && <SettingsPanel />}
        </div>
      )}
    </div>
  );
}
