import { useCallback, useEffect, useState } from "react";
import { useI18n } from "../../i18n/I18nContext";
import {
  isExtensionBridgePresent,
  pingExtensionBridge,
  requestExtensionSync,
  waitForExtensionBridge,
} from "../../lib/extensionSync";
import { Badge, Button } from "../ui";
import { ExtensionInstallCard } from "./ExtensionInstallCard";

type Props = {
  onMessage: (msg: string) => void;
  onError: (msg: string) => void;
};

/**
 * 開發模式：偵測擴充 + 從 Chrome 同步 Threads session → scout crawler-session
 */
export function DevModeSessionCard({ onMessage, onError }: Props) {
  const { t } = useI18n();
  const [extensionReady, setExtensionReady] = useState(() => isExtensionBridgePresent());
  const [syncBusy, setSyncBusy] = useState(false);
  const [checking, setChecking] = useState(false);
  const [lastSynced, setLastSynced] = useState(false);
  const pageOrigin = typeof window !== "undefined" ? window.location.origin : "";

  const recheck = useCallback(async () => {
    setChecking(true);
    try {
      if (isExtensionBridgePresent()) {
        setExtensionReady(true);
        return true;
      }
      pingExtensionBridge();
      const ready = await waitForExtensionBridge(5000);
      setExtensionReady(ready);
      return ready;
    } finally {
      setChecking(false);
    }
  }, []);

  useEffect(() => {
    let cancelled = false;
    const onBridgeMessage = (event: MessageEvent) => {
      if (event.source !== window) return;
      if (event.data?.type === "HAIXUN_EXTENSION_READY") {
        setExtensionReady(true);
      }
    };
    window.addEventListener("message", onBridgeMessage);
    const timer = window.setInterval(() => {
      if (cancelled) return;
      if (isExtensionBridgePresent()) {
        setExtensionReady(true);
        return;
      }
      pingExtensionBridge();
    }, 1200);
    pingExtensionBridge();
    void waitForExtensionBridge(8000).then((ready) => {
      if (!cancelled && ready) setExtensionReady(true);
    });
    return () => {
      cancelled = true;
      window.removeEventListener("message", onBridgeMessage);
      window.clearInterval(timer);
    };
  }, []);

  async function syncChromeSession() {
    setSyncBusy(true);
    onError("");
    onMessage("");
    try {
      const ready =
        extensionReady || isExtensionBridgePresent() || (await waitForExtensionBridge(4000));
      if (!ready) {
        throw new Error(t("settings.ext.notDetected", { origin: pageOrigin }));
      }
      setExtensionReady(true);

      const result = await requestExtensionSync({
        serverUrl: window.location.origin,
      });
      if (result.success === false || result.valid === false) {
        throw new Error(result.message || t("settings.ext.syncFail"));
      }
      setLastSynced(true);
      onMessage(result.message || t("settings.ext.syncOk"));
    } catch (err) {
      onError(err instanceof Error ? err.message : t("settings.ext.syncFail"));
    } finally {
      setSyncBusy(false);
    }
  }

  return (
    <div className="hb-stack hb-settings-ext-wrap">
      <div className="hb-list-row" style={{ alignItems: "center" }}>
        <div className="hb-stack hb-stack--tight" style={{ gap: "0.35rem" }}>
          <strong style={{ fontSize: "var(--hb-text-sm)" }}>{t("settings.ext.sessionTitle")}</strong>
          <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
            {t("settings.ext.sessionHint")}
          </p>
          <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
            {t("settings.ext.pageOrigin", { origin: pageOrigin })}
          </p>
        </div>
        <div className="hb-list-row__actions" style={{ flexWrap: "wrap" }}>
          <Badge tone={extensionReady ? "success" : "warning"}>
            {extensionReady ? t("settings.ext.detected") : t("settings.ext.notReady")}
          </Badge>
          <Badge tone={lastSynced ? "success" : "neutral"}>
            {lastSynced ? t("settings.ext.synced") : t("settings.ext.notSynced")}
          </Badge>
        </div>
      </div>

      <div className="hb-wizard-actions">
        <Button type="button" disabled={syncBusy || !extensionReady} onClick={() => void syncChromeSession()}>
          {syncBusy ? t("common.loading") : t("settings.ext.syncBtn")}
        </Button>
        <Button
          type="button"
          variant="secondary"
          disabled={checking}
          onClick={() => void recheck()}
        >
          {checking ? t("common.loading") : t("settings.ext.recheck")}
        </Button>
      </div>

      {!extensionReady ? (
        <div className="hb-stack hb-stack--tight" style={{ gap: "0.5rem" }}>
          <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
            {t("settings.ext.detectSteps", { origin: pageOrigin })}
          </p>
          <ExtensionInstallCard />
        </div>
      ) : (
        <ExtensionInstallCard />
      )}
    </div>
  );
}
