import { useEffect, useState } from "react";
import { api } from "../api/haixun";
import { ExtensionInstallCard } from "../components/ExtensionInstallCard";
import { Button, Card, ErrorText, Field, Input, PageTitle, Select } from "../components/ui";

type PlacementSettings = {
  web_search_provider?: string;
  expand_strategy?: string;
  brave_api_key_configured?: boolean;
  exa_api_key_configured?: boolean;
  dev_mode_enabled?: boolean;
  brave_api_key?: string;
  exa_api_key?: string;
};

function broadcastPlacementSettings(settings: PlacementSettings) {
  window.dispatchEvent(
    new CustomEvent("haixun:placement-settings-changed", {
      detail: settings,
    })
  );
}

function buildPlacementPatch(placement: PlacementSettings): Record<string, unknown> {
  const payload: Record<string, unknown> = {};
  if (placement.web_search_provider) {
    payload.web_search_provider = placement.web_search_provider;
  }
  if (placement.expand_strategy) {
    payload.expand_strategy = placement.expand_strategy;
  }
  if (placement.brave_api_key) {
    payload.brave_api_key = placement.brave_api_key;
  }
  if (placement.exa_api_key) {
    payload.exa_api_key = placement.exa_api_key;
  }
  if (placement.dev_mode_enabled !== undefined) {
    payload.dev_mode_enabled = placement.dev_mode_enabled;
  }
  return payload;
}

export function SettingsPage() {
  const [member, setMember] = useState<unknown>();
  const [placement, setPlacement] = useState<PlacementSettings>({});
  const [permissions, setPermissions] = useState<unknown>();
  const [error, setError] = useState<unknown>();
  const [message, setMessage] = useState("");
  const [savingDevMode, setSavingDevMode] = useState(false);

  async function load() {
    setError(undefined);
    try {
      const [memberData, placementData, permissionData] = await Promise.all([api.memberMe(), api.placementSettings(), api.permissions()]);
      setMember(memberData);
      setPlacement((placementData || {}) as PlacementSettings);
      setPermissions(permissionData);
    } catch (err) {
      setError(err);
    }
  }

  useEffect(() => {
    void load();
  }, []);

  async function savePlacement() {
    const updated = (await api.updatePlacementSettings(buildPlacementPatch(placement))) as PlacementSettings;
    setPlacement((current) => ({ ...current, ...updated }));
    setMessage("搜尋設定已儲存");
    broadcastPlacementSettings(updated);
  }

  async function toggleDevMode(enabled: boolean) {
    const previous = placement.dev_mode_enabled;
    setPlacement({ ...placement, dev_mode_enabled: enabled });
    setSavingDevMode(true);
    setError(undefined);
    try {
      const updated = (await api.updatePlacementSettings({ dev_mode_enabled: enabled })) as PlacementSettings;
      setPlacement((current) => ({ ...current, ...updated }));
      setMessage(enabled ? "開發模式已開啟" : "開發模式已關閉");
      broadcastPlacementSettings(updated);
    } catch (err) {
      setPlacement({ ...placement, dev_mode_enabled: previous });
      setError(err);
    } finally {
      setSavingDevMode(false);
    }
  }

  return (
    <div className="page-grid">
      <PageTitle title="設定" subtitle="管理會員資訊、搜尋供應商、API key readiness 與權限檢視。" action={<Button onClick={() => void load()}>重新載入</Button>} />
      <ErrorText error={error} />
      {message ? <Card><p>{message}</p></Card> : null}

      <div className="grid-2">
        <Card title="會員資料">
          <pre style={{ whiteSpace: "pre-wrap" }}>{JSON.stringify(member, null, 2)}</pre>
        </Card>

        <Card title="搜尋與延伸策略">
          <div className="page-grid">
            <Field label="搜尋 provider">
              <Select value={String(placement.web_search_provider || "brave")} onChange={(e) => setPlacement({ ...placement, web_search_provider: e.target.value })}>
                <option value="brave">Brave</option>
                <option value="exa">Exa</option>
              </Select>
            </Field>
            <Field label="延伸策略">
              <Select value={String(placement.expand_strategy || "hybrid")} onChange={(e) => setPlacement({ ...placement, expand_strategy: e.target.value })}>
                <option value="brave">Brave</option>
                <option value="llm">LLM</option>
                <option value="hybrid">Hybrid</option>
              </Select>
            </Field>
            <Field label="Brave API Key">
              <Input type="password" placeholder={placement.brave_api_key_configured ? "已設定，輸入新值才會覆蓋" : "尚未設定"} onChange={(e) => setPlacement({ ...placement, brave_api_key: e.target.value })} />
            </Field>
            <Field label="Exa API Key">
              <Input type="password" placeholder={placement.exa_api_key_configured ? "已設定，輸入新值才會覆蓋" : "尚未設定"} onChange={(e) => setPlacement({ ...placement, exa_api_key: e.target.value })} />
            </Field>
            <Field label="開發模式（測試海巡）" hint="僅測試海巡走 Chrome 爬蟲；正式海巡、擴圖、發文與留言仍走 Threads API。開啟後才會顯示測試海巡按鈕與 Chrome Session 同步。">
              <label className="button-row" style={{ justifyContent: "space-between" }}>
                <span>啟用爬蟲測試海巡{savingDevMode ? "（儲存中…）" : ""}</span>
                <input
                  type="checkbox"
                  checked={Boolean(placement.dev_mode_enabled)}
                  disabled={savingDevMode}
                  onChange={(e) => void toggleDevMode(e.target.checked)}
                />
              </label>
            </Field>
            <Button variant="primary" onClick={() => void savePlacement()}>儲存搜尋設定</Button>
          </div>
        </Card>
      </div>

      <Card title="Chrome 擴充套件">
        <ExtensionInstallCard />
        {!placement.dev_mode_enabled ? (
          <p className="muted hx-text-sm" style={{ margin: "0.75rem 0 0" }}>
            請先開啟上方「啟用爬蟲測試海巡」，安裝擴充後才能在 Threads 帳號頁同步 Session、在海巡頁使用測試海巡。
          </p>
        ) : null}
      </Card>

      <Card title="我的權限">
        <pre style={{ whiteSpace: "pre-wrap" }}>{JSON.stringify(permissions, null, 2)}</pre>
      </Card>
    </div>
  );
}