import { useEffect, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { Crosshair, Power, PowerOff, Settings } from "lucide-react";
import StatusPill from "../components/StatusPill";
import Terminal from "../components/Terminal";
import { openWindow } from "../utils/navigation";

export default function ClonePage() {
  const [engineEnabled, setEngineEnabled] = useState(false);
  const [engineBusy, setEngineBusy] = useState(false);
  const [agentLogs, setAgentLogs] = useState([]);
  const [annotating, setAnnotating] = useState(false);
  const [sourcePickerOpen, setSourcePickerOpen] = useState(false);
  const [captureSources, setCaptureSources] = useState([]);
  const [sourceStatus, setSourceStatus] = useState("");

  useEffect(() => {
    if (!window.__TAURI_INTERNALS__) return undefined;

    let unlisten;
    let cancelled = false;
    listen("engine-state-changed", (event) => {
      setEngineEnabled(Boolean(event.payload?.enabled));
      setEngineBusy(false);
      setAgentLogs((currentLogs) => [
        ...currentLogs.slice(-300),
        { level: "warning", message: "工作台已关闭，引擎状态已同步" },
      ]);
    }).then((cleanup) => {
      if (cancelled) {
        cleanup();
        return;
      }
      unlisten = cleanup;
    });

    return () => {
      cancelled = true;
      if (unlisten) unlisten();
    };
  }, []);

  async function startAnnotation() {
    if (!window.__TAURI_INTERNALS__) {
      window.location.hash = "/annotate";
      return;
    }

    setSourcePickerOpen(true);
    setSourceStatus("正在读取桌面和窗口列表...");
    try {
      const sources = await invoke("list_capture_sources");
      setCaptureSources(sources);
      setSourceStatus(sources.length ? "请选择一个桌面或应用窗口" : "未找到可用来源");
    } catch (error) {
      setCaptureSources([]);
      setSourceStatus(`读取来源失败：${String(error)}`);
    }
  }

  function beginAnnotationWithSource(source) {
    setAnnotating(true);
    sessionStorage.removeItem("pendingAnnotationCapture");
    localStorage.removeItem("annotationCaptureResult");
    localStorage.removeItem("annotationCaptureError");
    localStorage.setItem("annotationCaptureSource", JSON.stringify(source));
    localStorage.setItem("annotationCaptureStatus", "pending");
    setSourcePickerOpen(false);

    if (window.__TAURI_INTERNALS__) {
      invoke("capture_source", { sourceId: source.id })
        .then((capture) => {
          localStorage.setItem("annotationCaptureResult", JSON.stringify(capture));
          localStorage.setItem("annotationCaptureStatus", "done");
        })
        .catch((error) => {
          localStorage.setItem("annotationCaptureError", String(error));
          localStorage.setItem("annotationCaptureStatus", "error");
        });

      openWindow("/annotate").finally(() => setAnnotating(false));
      return;
    }

    window.location.hash = "/annotate";
    setAnnotating(false);
  }

  async function toggleAgent() {
    if (engineBusy) return;

    if (!window.__TAURI_INTERNALS__) {
      setEngineEnabled((enabled) => !enabled);
      return;
    }

    setEngineBusy(true);
    try {
      if (engineEnabled) {
        await invoke("stop_agent");
        await invoke("stop_vision_stream").catch((error) => {
          setAgentLogs((currentLogs) => [
            ...currentLogs,
            { level: "warning", message: `停止视觉流失败：${String(error)}` },
          ]);
        });
        setEngineEnabled(false);
        setAgentLogs((currentLogs) => [
          ...currentLogs.slice(-300),
          { level: "warning", message: "引擎已停用，暂未读取 Rust 日志" },
        ]);
      } else {
        await invoke("start_vision_stream");
        await invoke("start_agent").catch((error) => {
          setAgentLogs((currentLogs) => [
            ...currentLogs.slice(-300),
            { level: "warning", message: `agent 启动失败，预览已继续启动：${String(error)}` },
          ]);
        });
        setEngineEnabled(true);
        setAgentLogs((currentLogs) => [
          ...currentLogs.slice(-300),
          { level: "info", message: "引擎已启动，暂未读取 Rust 日志" },
        ]);
        await openWindow("/window/engine-workbench");
      }
    } catch (error) {
      setAgentLogs((currentLogs) => [
        ...currentLogs,
        { level: "error", message: String(error) },
      ]);
    } finally {
      setEngineBusy(false);
    }
  }

  return (
    <section className="flex min-h-full flex-1 flex-col gap-3">
      <div className="flex justify-end">
        <StatusPill tone="success" label="大模型已连接" />
      </div>
      <div className="flex flex-col items-center gap-5 px-6 py-2">
        <div className="engine-sphere engine-success" aria-hidden="true" />
        <div className="text-center">
          <h2 className="text-[22px] font-extrabold">微信引擎运行中</h2>
          <p className="mt-2 text-[13px] text-muted">微信适配层已就绪，等待本地消息事件。</p>
        </div>
        <div className="flex w-full items-center justify-center gap-4">
          <button
            className={`${engineEnabled ? "btn-danger" : "btn-primary"} w-full gap-2`}
            onClick={toggleAgent}
            disabled={engineBusy}
          >
            {engineEnabled ? <PowerOff size={16} strokeWidth={2.6} /> : <Power size={16} strokeWidth={2.6} />}
            {engineBusy ? "处理中" : engineEnabled ? "停用引擎" : "启动引擎"}
          </button>
          <button className="icon-action shrink-0" onClick={() => openWindow("/window/settings")} aria-label="设置"><Settings size={18} strokeWidth={2.5} /></button>
        </div>
      </div>
      <div className="panel p-4">
        <div className="flex items-center justify-between gap-3">
          <div>
            <h3 className="text-[16px] font-extrabold">屏幕区域标注</h3>
            <p className="mt-1 text-[12px] text-muted">截取当前屏幕，配置联系人、聊天内容、输入框和发送按钮坐标。</p>
          </div>
          <button className="btn-primary shrink-0 gap-2" onClick={startAnnotation} disabled={annotating}>
            <Crosshair size={16} strokeWidth={2.6} />
            {annotating ? "截屏中" : "开始标注"}
          </button>
        </div>
      </div>
      {sourcePickerOpen ? (
        <div className="fixed inset-0 z-50 grid place-items-center bg-black/35 px-5">
          <div className="panel max-h-[78dvh] w-full max-w-[440px] overflow-hidden p-4">
            <div className="flex items-start justify-between gap-3">
              <div>
                <h3 className="text-[17px] font-extrabold">选择标注来源 Demo</h3>
                <p className="mt-1 text-[12px] text-muted">可以选择某个桌面，或某个可见应用窗口。</p>
              </div>
              <button className="btn-ghost" onClick={() => setSourcePickerOpen(false)}>关闭</button>
            </div>
            <div className="mt-3 rounded-[12px] bg-surface2 px-3 py-2 text-[12px] text-muted">{sourceStatus}</div>
            <div className="mt-3 max-h-[54dvh] space-y-2 overflow-y-auto pr-1">
              {captureSources.map((source) => (
                <button
                  key={source.id}
                  className="list-card w-full !rounded-[12px] text-left transition hover:border-primary"
                  onClick={() => beginAnnotationWithSource(source)}
                >
                  <div className="min-w-0">
                    <div className="truncate text-[13px] font-extrabold">{source.label}</div>
                    <div className="mt-1 text-[11px] text-muted">
                      {source.kind === "display" ? "桌面" : "窗口"} · {source.width}x{source.height} · x:{source.x} y:{source.y}
                    </div>
                  </div>
                  <span className="tag shrink-0">{source.kind === "display" ? "桌面" : "窗口"}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      ) : null}
      <Terminal title="运行日志" lines={agentLogs} onClear={() => setAgentLogs([])} />
    </section>
  );
}
