"use client";

import { useEffect, useState } from "react";
import { Monitor } from "lucide-react";

import { SettingHeader, SettingsSwitch } from "@/app/(main)/chat/code/settings-primitives";
import { ColorThemeToggle } from "@/components/ColorThemeToggle";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useDesktopShellInfo } from "@/hooks/use-desktop-shell-info";
import { SHORTCUTS } from "@/lib/desktop/shortcuts";
import { displayPath } from "@/lib/desktop/display-path";
import { type SettingsSection, useDesktopShell } from "@/lib/desktop/store";
import { type ShellSettings, tauriBridge } from "@/lib/desktop/tauri-bridge";
import { cn } from "@/lib/utils";

const SECTIONS: { key: SettingsSection; label: string }[] = [
  { key: "general", label: "通用" },
  { key: "appearance", label: "外观" },
  { key: "runtime", label: "本机运行时" },
  { key: "shortcuts", label: "快捷键" },
];
const STATE_DOT = { running: "bg-success", idle: "bg-ink-4", stopped: "bg-border-strong" } as const;
const STATE_NOTE = { running: "运行中", idle: "空闲", stopped: "已停止" } as const;
const LEVEL = { info: "text-muted-foreground", warn: "text-warning-deep", error: "text-destructive" } as const;
type GeneralKey = keyof Pick<ShellSettings, "autostart" | "keep_tray_on_close" | "notify_on_done">;
const GENERAL_SWITCHES: { key: GeneralKey; label: string; note: string }[] = [
  { key: "autostart", label: "开机时自动启动", note: "启动后在后台待命" },
  { key: "keep_tray_on_close", label: "关闭窗口后留在托盘", note: "本机运行中的服务继续保持" },
  { key: "notify_on_done", label: "任务完成时发送系统通知", note: "仅在窗口未激活时提醒" },
];
/** 壳 workspace_move 的错误码 → 给用户看的话; 其余原因原样显示. */
const MOVE_ERRORS: Record<string, string> = {
  WORKSPACE_BUSY: "有命令或任务正在运行, 等它结束或停掉后再更改目录",
  TARGET_NOT_EMPTY: "目标目录不是空的, 换一个",
  TARGET_INSIDE_WORKSPACE: "目标目录不能在当前工作区里面",
};

const SectionTitle = ({ children }: { children: string }) => (
  <h3 className="mb-2 text-[13px] font-semibold text-muted-foreground">{children}</h3>
);

/** 通用节: 三个开关读壳的设置文件, 翻一个立即写回, 以壳回的为准; 写不进去就翻回来并说原因. */
const GeneralSection = () => {
  const [settings, setSettings] = useState<ShellSettings | null>(null);
  const [saveError, setSaveError] = useState<string | null>(null);
  useEffect(() => {
    void tauriBridge.settings.get().then(setSettings);
  }, []);
  const toggle = async (key: GeneralKey, value: boolean) => {
    setSaveError(null);
    setSettings((prev) => (prev ? { ...prev, [key]: value } : prev));
    try {
      const next = await tauriBridge.settings.set({ [key]: value });
      if (next) setSettings(next);
    } catch (e) {
      setSettings((prev) => (prev ? { ...prev, [key]: !value } : prev));
      setSaveError(`保存失败: ${String(e)}`);
    }
  };
  return (
    <>
      <SectionTitle>通用</SectionTitle>
      {GENERAL_SWITCHES.map((g) => (
        <div key={g.key} className="py-2">
          <SettingHeader
            align="center"
            title={g.label}
            description={g.note}
            right={
              <SettingsSwitch
                checked={settings?.[g.key] ?? false}
                disabled={!settings}
                onChange={(v) => void toggle(g.key, v)}
                ariaLabel={g.label}
              />
            }
          />
        </div>
      ))}
      {saveError && <p className="mt-1 text-[12px] text-destructive">{saveError}</p>}
    </>
  );
};

/** 工作区目录行: 「更改」选一个新目录, 壳把整个工作区搬过去; 目录行随壳的状态事件更新. */
const WorkspaceRootRow = () => {
  const workspaceRoot = useDesktopShell((s) => displayPath(s.workspace_root, s.home));
  const [moving, setMoving] = useState(false);
  const [moveError, setMoveError] = useState<string | null>(null);
  const changeRoot = async () => {
    const picked = await tauriBridge.pickDirectory();
    if (typeof picked !== "string") return;
    setMoveError(null);
    setMoving(true);
    try {
      await tauriBridge.workspace.move(picked);
    } catch (e) {
      setMoveError(MOVE_ERRORS[String(e)] ?? String(e));
    } finally {
      setMoving(false);
    }
  };
  return (
    <section>
      <SectionTitle>工作区目录</SectionTitle>
      <div className="flex items-center gap-3">
        <p data-testid="workspace-root" className="min-w-0 flex-1 truncate font-mono text-[12.5px] text-foreground">
          {workspaceRoot}
        </p>
        <Button variant="outline" size="sm" disabled={moving} onClick={() => void changeRoot()}>
          更改
        </Button>
      </div>
      {moveError && <p className="mt-1 text-[12px] text-destructive">{moveError}</p>}
    </section>
  );
};

const RuntimeSection = () => {
  const device = useDesktopShell((s) => s.device);
  const workspaces = useDesktopShell((s) => s.workspaces);
  const workspaceTitles = useDesktopShell((s) => s.workspaceTitles);
  const activity = useDesktopShell((s) => s.activity);
  const deviceFacts = [device.os, device.chip, device.memory, device.disk_free && `磁盘剩余 ${device.disk_free}`]
    .filter(Boolean)
    .join(" · ");
  return (
    <div className="space-y-6">
      <section
        data-testid="device-row"
        className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3"
      >
        <Monitor size={20} className="text-muted-foreground" aria-hidden />
        <div>
          <p className="text-[14px] font-medium text-foreground">{device.name || "本机"}</p>
          {deviceFacts && <p className="text-[12px] text-muted-foreground">{deviceFacts}</p>}
        </div>
      </section>
      <WorkspaceRootRow />
      <section>
        <SectionTitle>各应用占用</SectionTitle>
        {workspaces.map((w) => (
          <div key={w.subdir} data-testid="workspace-row" className="flex items-center gap-3 border-b border-border py-2 last:border-0">
            <span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", STATE_DOT[w.state])} aria-hidden />
            <div className="min-w-0 flex-1">
              <p className="truncate text-[13.5px] text-foreground">
                {workspaceTitles[w.subdir] ?? "未知应用"}
              </p>
              <p className="font-mono text-[11.5px] text-muted-foreground">
                {w.subdir} · {STATE_NOTE[w.state]}
              </p>
            </div>
            <span className="font-mono text-[12px] text-muted-foreground">{w.size}</span>
          </div>
        ))}
      </section>
      <section>
        <SectionTitle>活动日志 · 最近 200 条</SectionTitle>
        {activity.map((a) => (
          <div key={a.seq} data-testid="activity-row" className="flex gap-3 py-1 font-mono text-[12px]">
            <span className="shrink-0 text-ink-4">{a.time}</span>
            <span className={cn("shrink-0", LEVEL[a.level])}>{a.method}</span>
            <span className="min-w-0 truncate text-foreground">{a.detail}</span>
          </div>
        ))}
      </section>
    </div>
  );
};

/** 设置弹层: 通用 / 外观 / 本机运行时 / 快捷键. 标题栏、托盘、快捷键都经 store 的 openSettings 打开它. */
export const DesktopSettingsDialog = () => {
  const section = useDesktopShell((s) => s.settingsSection);
  const openSettings = useDesktopShell((s) => s.openSettings);
  const closeSettings = useDesktopShell((s) => s.closeSettings);
  const platform = useDesktopShellInfo()?.platform ?? "macos";
  if (!section) return null;
  return (
    <Dialog open onOpenChange={(next) => !next && closeSettings()}>
      <DialogContent className="h-[560px] overflow-hidden p-0 sm:max-w-[880px]">
        <Tabs
          value={section}
          onValueChange={(value: SettingsSection) => openSettings(value)}
          orientation="vertical"
          className="flex h-full min-h-0 flex-row gap-0"
        >
          <aside className="w-[200px] shrink-0 border-r border-border bg-surface p-3">
            <DialogTitle className="px-2 pb-3 text-[15px]">设置</DialogTitle>
            <TabsList aria-label="设置" variant="line" className="w-full items-stretch gap-0.5">
              {SECTIONS.map((s) => (
                <TabsTrigger key={s.key} value={s.key}>
                  {s.label}
                </TabsTrigger>
              ))}
            </TabsList>
          </aside>
          <div className="min-h-0 min-w-0 flex-1 overflow-y-auto p-6">
            <TabsContent value="general">
              <GeneralSection />
            </TabsContent>
            <TabsContent value="appearance">
              <SectionTitle>外观</SectionTitle>
              <ThemeToggle />
              <ColorThemeToggle />
            </TabsContent>
            <TabsContent value="runtime">
              <RuntimeSection />
            </TabsContent>
            <TabsContent value="shortcuts">
              <SectionTitle>全局</SectionTitle>
              {SHORTCUTS(platform).map((s) => (
                <div key={s.label} data-testid="shortcut-row" className="flex items-center justify-between border-b border-border py-2 last:border-0">
                  <span className="text-[13px] text-foreground">{s.label}</span>
                  <kbd className="rounded-md bg-surface-2 px-1.5 py-0.5 font-mono text-[12px] text-muted-foreground">{s.key}</kbd>
                </div>
              ))}
            </TabsContent>
          </div>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
};
