import { useEffect, useState } from "react";
import { Dialog } from "../ui/Dialog";
import { Button } from "../ui/Button";
import { useToast } from "../ui/Toast";
import { getMyJarvis, saveMyJarvis, type JarvisConfig, GATEWAY, getToken } from "../lib/api";
import {
  defaultLocalDirs,
  localExecEnabled,
  localRunnerAvailable,
  localRunnerStatus,
  setLocalExecEnabled,
  startLocalRunner,
  stopLocalRunner,
} from "../lib/desktop";

// 每用户 JARVIS 设置：名字 / 人设 / （高级）自带豆包配置。
// 名字与人设归用户自己；豆包配置齐全则语音走用户的账号，否则走系统兜底。
export function JarvisSettings({ open, onClose }: { open: boolean; onClose: () => void }) {
  const toast = useToast();
  const [cfg, setCfg] = useState<JarvisConfig | null>(null);
  const [saving, setSaving] = useState(false);
  const [advanced, setAdvanced] = useState(false);

  useEffect(() => {
    if (!open) return;
    setCfg(null);
    getMyJarvis()
      .then(setCfg)
      .catch((e) => toast.push("error", (e as Error).message));
  }, [open, toast]);

  const set = (k: keyof JarvisConfig, v: string) => setCfg((c) => (c ? { ...c, [k]: v } : c));

  const onSave = async () => {
    if (!cfg) return;
    setSaving(true);
    try {
      await saveMyJarvis({
        name: cfg.name,
        persona: cfg.persona,
        api_key: cfg.api_key.includes("•") ? "" : cfg.api_key, // 掩码=没改动，留空沿用已存
        asr_resource_id: cfg.asr_resource_id,
        tts_resource_id: cfg.tts_resource_id,
        tts_voice_type: cfg.tts_voice_type,
      });
      toast.push("success", "已保存，下次说话即生效");
      onClose();
    } catch (e) {
      toast.push("error", (e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="JARVIS 设置"
      footer={
        <>
          <Button variant="ghost" size="sm" onClick={onClose}>
            取消
          </Button>
          <Button variant="primary" size="sm" onClick={onSave} disabled={saving || !cfg}>
            {saving ? "保存中…" : "保存"}
          </Button>
        </>
      }
    >
      {!cfg ? (
        <div className="text-slate-500">加载中…</div>
      ) : (
        <div className="space-y-4">
          <label className="block">
            <span className="text-xs text-slate-400">助手名字</span>
            <input
              className="mt-1 w-full rounded-md border border-line bg-ink-850 px-3 py-2 text-slate-100 focus:border-brand focus:outline-none"
              value={cfg.name}
              onChange={(e) => set("name", e.target.value)}
              placeholder="JARVIS（留空用默认；可改成星期五、小助手…）"
            />
          </label>

          <label className="block">
            <span className="text-xs text-slate-400">语气 / 人设</span>
            <textarea
              rows={3}
              className="mt-1 w-full resize-none rounded-md border border-line bg-ink-850 px-3 py-2 text-slate-100 focus:border-brand focus:outline-none"
              value={cfg.persona}
              onChange={(e) => set("persona", e.target.value)}
              placeholder="例：简洁专业、平和有礼；或活泼幽默一点。留空用默认平和语气。"
            />
            <span className="mt-1 block text-[11px] text-slate-500">只作用于语音助手，和你的主偏好记忆分开、互不影响。</span>
          </label>

          <button
            type="button"
            className="text-xs text-slate-400 transition hover:text-slate-200"
            onClick={() => setAdvanced((v) => !v)}
          >
            {advanced ? "▾" : "▸"} 高级：用我自己的豆包（火山）配置
            <span className="ml-1 text-slate-500">{cfg.has_own_voice ? "（已启用）" : "（默认走系统）"}</span>
          </button>

          {advanced && (
            <div className="space-y-3 rounded-md border border-line bg-ink-900/50 p-3">
              <p className="text-[11px] leading-relaxed text-slate-500">
                填齐这四项就用你自己的豆包账号跑语音（识别 + 合成）；任一留空则整体回落系统配置。
              </p>
              <Field label="API Key" type="password" value={cfg.api_key} onChange={(v) => set("api_key", v)} placeholder="留空 = 沿用已存 / 系统" />
              <Field label="ASR Resource-Id" value={cfg.asr_resource_id} onChange={(v) => set("asr_resource_id", v)} placeholder="volc.bigasr.sauc.duration" />
              <Field label="TTS Resource-Id" value={cfg.tts_resource_id} onChange={(v) => set("tts_resource_id", v)} placeholder="seed-tts-2.0" />
              <Field label="音色 voice_type" value={cfg.tts_voice_type} onChange={(v) => set("tts_voice_type", v)} placeholder="zh_male_m191_uranus_bigtts" />
            </div>
          )}

          <LocalAccessSection />
        </div>
      )}
    </Dialog>
  );
}

// LocalAccessSection 本地文件访问（JARVIS「本地的手」，只读起步）：用户显式选目录 + 开启，
// JARVIS 才能看/读该目录内的文件；随时可关。仅桌面壳可用（浏览器隐藏整个区块）。
function LocalAccessSection() {
  const toast = useToast();
  const [dir, setDir] = useState("");
  const [status, setStatus] = useState("offline");
  const [busy, setBusy] = useState(false);
  const [canExec, setCanExec] = useState(false);

  useEffect(() => {
    if (!localRunnerAvailable()) return;
    let alive = true;
    const poll = () => {
      localRunnerStatus().then((s) => alive && setStatus(s)).catch(() => {});
      localExecEnabled().then((v) => alive && setCanExec(v)).catch(() => {});
    };
    poll();
    const iv = window.setInterval(poll, 2000);
    return () => {
      alive = false;
      window.clearInterval(iv);
    };
  }, []);

  if (!localRunnerAvailable()) return null;

  const online = status.startsWith("online");
  const onToggle = async () => {
    setBusy(true);
    try {
      if (online || status === "connecting") {
        stopLocalRunner();
        setStatus("offline");
      } else {
        if (!dir.trim()) throw new Error("至少填一个允许 JARVIS 访问的目录（绝对路径，每行一个）");
        await startLocalRunner(GATEWAY, getToken(), dir.trim());
        setStatus("connecting");
        toast.push("success", "本地访问已开启（仅限授权目录）");
      }
    } catch (e) {
      toast.push("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="space-y-2 rounded-md border border-line bg-ink-900/50 p-3">
      <div className="flex items-center justify-between">
        <span className="text-xs text-slate-400">本地访问（授权目录）</span>
        <span className={online ? "text-[11px] text-emerald-400" : "text-[11px] text-slate-500"}>
          {online ? "已开启" : status === "connecting" ? "连接中…" : "未开启"}
        </span>
      </div>
      <p className="text-[11px] leading-relaxed text-slate-500">
        JARVIS 只能在你授权的这些目录里活动（其余一律拒绝）。开启后可以说
        “看看我桌面上有什么”“把下载里的图片整理一下”。默认只读；要让它动手改文件、跑命令，
        还得单独打开下面那个开关。
      </p>
      {online ? (
        <div className="space-y-0.5">
          {status.slice("online:".length).split("\n").filter(Boolean).map((d) => (
            <p key={d} className="break-all font-mono text-[11px] text-slate-400">· {d}</p>
          ))}
        </div>
      ) : (
        <>
          <textarea
            rows={3}
            className="w-full resize-none rounded-md border border-line bg-ink-850 px-3 py-1.5 font-mono text-xs text-slate-100 focus:border-brand focus:outline-none"
            value={dir}
            onChange={(e) => setDir(e.target.value)}
            placeholder={"每行一个目录（绝对路径），例：\n/Users/你/Desktop\n/Users/你/Downloads"}
          />
          <button
            type="button"
            className="text-[11px] text-brand-400 transition hover:underline"
            onClick={() => void defaultLocalDirs().then((d) => d && setDir(d))}
          >
            + 填入常用目录（桌面 / 下载 / 文档）
          </button>
        </>
      )}
      <Button variant={online ? "ghost" : "secondary"} size="sm" onClick={onToggle} disabled={busy}>
        {online || status === "connecting" ? "关闭本地访问" : "开启本地访问"}
      </Button>

      {/* 第二道开关：写文件 + 执行命令。风险等级远高于只读，所以单独开、且每次仍要弹框批准。 */}
      {online && (
        <label className="mt-1 flex cursor-pointer items-start gap-2 border-t border-line pt-3">
          <input
            type="checkbox"
            className="mt-0.5"
            checked={canExec}
            onChange={(e) => {
              setLocalExecEnabled(e.target.checked);
              setCanExec(e.target.checked);
            }}
          />
          <span className="text-[11px] leading-relaxed text-slate-400">
            允许 <b className="text-slate-200">写文件 / 执行命令</b>（高风险）
            <span className="mt-0.5 block text-slate-500">
              开启后 JARVIS 每次动手前都会弹系统确认框，你点「允许」才执行；删库、提权、写系统路径等危险命令一律直接拒绝。
            </span>
          </span>
        </label>
      )}
    </div>
  );
}

function Field({
  label,
  value,
  onChange,
  placeholder,
  type,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  type?: string;
}) {
  return (
    <label className="block">
      <span className="text-xs text-slate-400">{label}</span>
      <input
        type={type}
        className="mt-1 w-full rounded-md border border-line bg-ink-850 px-3 py-1.5 font-mono text-sm text-slate-100 focus:border-brand focus:outline-none"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
      />
    </label>
  );
}
