import type { ReactElement } from "react";
import { useEffect, useMemo, useState } from "react";

import { builtinProviderProfileOrder, providerProfileLabel as profileLabel } from "../../hooks/useProviderProfileOptions";
import { api } from "../../services/api/client";
import type { ProviderProfile, ProviderProfileConfig, ProviderProfileStatusItem, ProviderProfileValidation, Tone } from "../../types/domain";
import { formatTimestamp, shortToken, toneClass } from "../../utils";
import { StateTag } from "../shared/StateTag";
import { WorkbenchDialog } from "../shared/WorkbenchDialog";

interface ConfigDialogState {
  profile: ProviderProfile;
  configToml: string;
  loading: boolean;
  saving: boolean;
  error: string | null;
}

interface ManagementState {
  loading: boolean;
  savingProfile: ProviderProfile | null;
  validatingProfile: ProviderProfile | null;
  configDialog: ConfigDialogState | null;
  profiles: ProviderProfileStatusItem[];
  inputs: Record<string, string>;
  validations: Partial<Record<string, ProviderProfileValidation>>;
  error: string | null;
  notice: string | null;
}

const initialInputs: Record<string, string> = {};
const initialState: ManagementState = { loading: false, savingProfile: null, validatingProfile: null, configDialog: null, profiles: [], inputs: initialInputs, validations: {}, error: null, notice: null };

export function ManagementView(): ReactElement {
  const [state, setState] = useState<ManagementState>(initialState);

  async function load(): Promise<void> {
    setState((current) => ({ ...current, loading: true, error: null, notice: null }));
    const response = await api.providerProfiles();
    if (!response.ok) {
      setState((current) => ({ ...current, loading: false, error: response.error ?? "Provider profile 状态不可用" }));
      return;
    }
    setState((current) => ({ ...current, loading: false, profiles: orderedProfiles(profileItems(response.data)), error: null }));
  }

  async function saveKey(profile: ProviderProfile): Promise<void> {
    const apiKey = (state.inputs[profile] ?? "").trim();
    if (apiKey.length < 8 || state.savingProfile || state.validatingProfile) return;
    setState((current) => ({ ...current, savingProfile: profile, error: null, notice: null }));
    const response = await api.setProviderProfileKey(profile, apiKey);
    if (!response.ok) {
      setState((current) => ({ ...current, savingProfile: null, error: response.error ?? `${profileLabel(profile)} 保存失败` }));
      return;
    }
    const updated = profileItem(response.data);
    setState((current) => ({
      ...current,
      savingProfile: null,
      inputs: { ...current.inputs, [profile]: "" },
      profiles: updated ? mergeProfile(current.profiles, updated) : current.profiles,
      notice: `${profileLabel(profile)} 已保存`,
      error: null
    }));
    if (!updated) void load();
  }

  async function openConfig(profile: ProviderProfile): Promise<void> {
    if (state.savingProfile || state.validatingProfile) return;
    setState((current) => ({ ...current, configDialog: { profile, configToml: "", loading: true, saving: false, error: null }, error: null, notice: null }));
    const response = await api.providerProfileConfig(profile);
    if (!response.ok) {
      setState((current) => ({ ...current, configDialog: current.configDialog?.profile === profile ? { ...current.configDialog, loading: false, error: response.error ?? `${profileLabel(profile)} config.toml 加载失败` } : current.configDialog }));
      return;
    }
    const config = configPayload(response.data, profile);
    setState((current) => ({ ...current, configDialog: current.configDialog?.profile === profile ? { ...current.configDialog, loading: false, configToml: config.configToml ?? "", error: null } : current.configDialog }));
  }

  async function saveConfig(): Promise<void> {
    const dialog = state.configDialog;
    if (!dialog || dialog.loading || dialog.saving || !dialog.configToml.trim()) return;
    setState((current) => ({ ...current, configDialog: current.configDialog ? { ...current.configDialog, saving: true, error: null } : null, error: null, notice: null }));
    const response = await api.setProviderProfileConfig(dialog.profile, dialog.configToml);
    if (!response.ok) {
      setState((current) => ({ ...current, configDialog: current.configDialog ? { ...current.configDialog, saving: false, error: response.error ?? `${profileLabel(dialog.profile)} config.toml 保存失败` } : null }));
      return;
    }
    const updated = profileItem(response.data);
    setState((current) => ({
      ...current,
      configDialog: null,
      profiles: updated ? mergeProfile(current.profiles, updated) : current.profiles,
      notice: `${profileLabel(dialog.profile)} config.toml 已保存`,
      error: null
    }));
    if (!updated) void load();
  }

  function closeConfig(): void {
    if (state.configDialog?.saving) return;
    setState((current) => ({ ...current, configDialog: null }));
  }

  function setConfigToml(value: string): void {
    setState((current) => ({ ...current, configDialog: current.configDialog ? { ...current.configDialog, configToml: value } : null }));
  }

  async function validateProfile(profile: ProviderProfile): Promise<void> {
    if (state.savingProfile || state.validatingProfile) return;
    setState((current) => ({ ...current, validatingProfile: profile, error: null, notice: null }));
    const submitted = await api.validateProviderProfile(profile);
    if (!submitted.ok) {
      setState((current) => ({ ...current, validatingProfile: null, error: submitted.error ?? `${profileLabel(profile)} 验证失败` }));
      return;
    }
    const first = validationPayload(submitted.data, profile);
    setValidation(profile, first);
    if (!first.validationId) {
      setState((current) => ({ ...current, validatingProfile: null, notice: `${profileLabel(profile)} 验证已提交` }));
      return;
    }
    let latest = first;
    for (let attempt = 0; attempt < 45 && !terminalValidation(latest); attempt += 1) {
      await sleep(2000);
      const polled = await api.providerProfileValidation(profile, first.validationId);
      if (!polled.ok) {
        setState((current) => ({ ...current, validatingProfile: null, error: polled.error ?? `${profileLabel(profile)} 验证查询失败` }));
        return;
      }
      latest = validationPayload(polled.data, profile);
      setValidation(profile, latest);
    }
    setState((current) => ({ ...current, validatingProfile: null, notice: `${profileLabel(profile)} 验证 ${latest.status ?? "已更新"}` }));
  }

  function setValidation(profile: ProviderProfile, validation: ProviderProfileValidation): void {
    setState((current) => ({ ...current, validations: { ...current.validations, [profile]: validation } }));
  }

  function setInput(profile: ProviderProfile, value: string): void {
    setState((current) => ({ ...current, inputs: { ...current.inputs, [profile]: value } }));
  }

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

  const statusTone = state.error ? "blocked" : state.loading ? "pending" : "source";
  const statusLabel = state.error ? "阻塞" : state.loading ? "加载中" : `${state.profiles.length} profiles`;
  const visibleProfiles = useMemo(() => orderedProfiles(state.profiles), [state.profiles]);

  return (
    <section className="view management-view" id="management" data-view="management" aria-labelledby="management-title">
      <div className="workspace-panel management-panel">
        <div className="panel-title-row">
          <div><p className="eyebrow">管理员</p><h2 id="management-title">管理</h2></div>
          <div className="panel-title-actions"><StateTag id="management-status" tone={statusTone}>{statusLabel}</StateTag><button className="command-button secondary" id="management-refresh" type="button" disabled={state.loading} onClick={() => void load()}>{state.loading ? "刷新中" : "刷新"}</button></div>
        </div>
        {state.error ? <p className="management-error" role="alert">{state.error}</p> : null}
        {state.notice ? <p className="management-notice" role="status">{state.notice}</p> : null}
        <div className="management-grid" aria-live="polite">
          {visibleProfiles.map((profile) => <ProfilePanel key={profile.profile} profile={profile} inputValue={state.inputs[profile.profile] ?? ""} validation={state.validations[profile.profile] ?? profile.lastValidation ?? null} saving={state.savingProfile === profile.profile} validating={state.validatingProfile === profile.profile} configuring={state.configDialog?.profile === profile.profile && (state.configDialog.loading || state.configDialog.saving)} busy={Boolean(state.savingProfile || state.validatingProfile || state.configDialog?.loading || state.configDialog?.saving)} onInput={setInput} onSave={(item) => void saveKey(item)} onConfig={(item) => void openConfig(item)} onValidate={(item) => void validateProfile(item)} />)}
        </div>
        {state.configDialog ? <WorkbenchDialog id="management-config-dialog" title={`${profileLabel(state.configDialog.profile)} config.toml`} onClose={closeConfig}>
          <div className="management-config-editor">
            {state.configDialog.error ? <p className="management-config-error" role="alert">{state.configDialog.error}</p> : null}
            <label className="management-config-label" htmlFor="management-config-toml">config.toml</label>
            <textarea id="management-config-toml" className="mono" value={state.configDialog.configToml} disabled={state.configDialog.loading || state.configDialog.saving} aria-label={`${profileLabel(state.configDialog.profile)} config.toml`} spellCheck={false} onChange={(event) => setConfigToml(event.currentTarget.value)} />
            <div className="management-config-actions">
              <button className="command-button secondary" type="button" disabled={state.configDialog.saving} onClick={closeConfig}>关闭</button>
              <button className="command-button" type="button" disabled={state.configDialog.loading || state.configDialog.saving || !state.configDialog.configToml.trim()} onClick={() => void saveConfig()}>{state.configDialog.saving ? "保存中" : state.configDialog.loading ? "加载中" : "保存"}</button>
            </div>
          </div>
        </WorkbenchDialog> : null}
      </div>
    </section>
  );
}

function ProfilePanel({ profile, inputValue, validation, saving, validating, configuring, busy, onInput, onSave, onConfig, onValidate }: { profile: ProviderProfileStatusItem; inputValue: string; validation: ProviderProfileValidation | null; saving: boolean; validating: boolean; configuring: boolean; busy: boolean; onInput(profile: ProviderProfile, value: string): void; onSave(profile: ProviderProfile): void; onConfig(profile: ProviderProfile): void; onValidate(profile: ProviderProfile): void }): ReactElement {
  const tone = profile.configured ? "ok" : "blocked";
  const validationTone = validationToneFor(validation);
  const bridge = profile.bridge ?? (profile.profile === "deepseek" ? { route: "HWLAB Moon Bridge -> DeepSeek official upstream", serviceUrl: "http://hwlab-deepseek-proxy.hwlab-v02.svc.cluster.local:4000/v1", responsesPath: "/v1/responses" } : null);
  const validationJob = validation?.runnerJobs?.[0]?.jobName ?? validation?.result?.agentRun?.jobName ?? "-";
  const disabled = busy && !saving && !validating;
  return (
    <article className="management-profile" data-profile={profile.profile} aria-labelledby={`management-profile-${profile.profile}`}>
      <header className="management-profile-head">
        <div><p className="eyebrow">{profile.backendKind ?? profile.profile}</p><h3 id={`management-profile-${profile.profile}`}>{profileLabel(profile.profile)}</h3></div>
        <StateTag tone={tone}>{profile.configured ? "已配置" : "未配置"}</StateTag>
      </header>
      <dl className="management-meta-grid">
        <div><dt>Secret</dt><dd className="mono wrap">{profile.secretRef?.namespace ?? "-"}/{profile.secretRef?.name ?? "-"}</dd></div>
        <div><dt>keys</dt><dd className="mono wrap">{profile.secretRef?.keys?.join(", ") ?? "-"}</dd></div>
        <div><dt>key hash</dt><dd className="mono">{shortToken(profile.credentialHashSuffix, 16)}</dd></div>
        <div><dt>config hash</dt><dd className="mono">{shortToken(profile.configHashSuffix, 16)}</dd></div>
        <div><dt>resource</dt><dd className="mono">{shortToken(profile.resourceVersion, 14)}</dd></div>
        <div><dt>updated</dt><dd>{formatTimestamp(profile.updatedAt)}</dd></div>
      </dl>
      {bridge ? <div className="management-bridge" aria-label="DeepSeek bridge"><strong>{bridge.route}</strong><span className="mono wrap">{bridge.serviceUrl}{bridge.responsesPath ?? ""}</span></div> : null}
      <div className="management-key-row">
        <label><span>API Key</span><input type="password" value={inputValue} autoComplete="new-password" placeholder="sk-..." disabled={disabled || saving || validating} onChange={(event) => onInput(profile.profile, event.currentTarget.value)} /></label>
        <button className="command-button secondary" type="button" disabled={disabled || saving || validating || configuring} onClick={() => onConfig(profile.profile)}>{configuring ? "加载中" : "config.toml"}</button>
        <button className="command-button" type="button" disabled={disabled || saving || validating || inputValue.trim().length < 8} onClick={() => onSave(profile.profile)}>{saving ? "保存中" : "保存"}</button>
        <button className="command-button secondary" type="button" disabled={disabled || saving || validating || profile.configured !== true} onClick={() => onValidate(profile.profile)}>{validating ? "验证中" : "验证"}</button>
      </div>
      <section className="management-validation" aria-label={`${profileLabel(profile.profile)} validation`}>
        <div className="management-section-head"><h4>验证</h4><StateTag tone={validationTone}>{validation?.status ?? "未运行"}</StateTag></div>
        <dl className="management-validation-grid">
          <div><dt>validation</dt><dd className="mono wrap">{validation?.validationId ?? "-"}</dd></div>
          <div><dt>run</dt><dd className="mono wrap">{validation?.runId ?? "-"}</dd></div>
          <div><dt>command</dt><dd className="mono wrap">{validation?.commandId ?? "-"}</dd></div>
          <div><dt>job</dt><dd className="mono wrap">{validationJob}</dd></div>
          <div><dt>terminal</dt><dd>{validation?.result?.terminalStatus ?? validation?.result?.status ?? "-"}</dd></div>
          <div><dt>failure</dt><dd>{validation?.result?.failureKind ?? "-"}</dd></div>
        </dl>
      </section>
    </article>
  );
}

function profileItems(payload: unknown): ProviderProfileStatusItem[] {
  const record = payload && typeof payload === "object" ? payload as { items?: ProviderProfileStatusItem[]; data?: { items?: ProviderProfileStatusItem[] } } : {};
  return Array.isArray(record.items) ? record.items : Array.isArray(record.data?.items) ? record.data.items : [];
}

function profileItem(payload: unknown): ProviderProfileStatusItem | null {
  const record = payload && typeof payload === "object" ? payload as { data?: ProviderProfileStatusItem; profile?: ProviderProfile } : null;
  if (!record) return null;
  if (record.data && typeof record.data === "object" && "profile" in record.data) return record.data;
  return "profile" in record ? record as ProviderProfileStatusItem : null;
}

function validationPayload(payload: unknown, profile: ProviderProfile): ProviderProfileValidation {
  const record = payload && typeof payload === "object" ? payload as { data?: ProviderProfileValidation; validationId?: string } : {};
  const validation = record.data && typeof record.data === "object" ? record.data : record as ProviderProfileValidation;
  return { ...validation, profile: validation.profile ?? profile };
}

function configPayload(payload: unknown, profile: ProviderProfile): ProviderProfileConfig {
  const record = payload && typeof payload === "object" ? payload as { data?: ProviderProfileConfig; configToml?: string; profile?: ProviderProfile } : {};
  const config = record.data && typeof record.data === "object" ? record.data : record as ProviderProfileConfig;
  return { ...config, profile: config.profile ?? profile, configToml: typeof config.configToml === "string" ? config.configToml : "" };
}

function orderedProfiles(items: ProviderProfileStatusItem[]): ProviderProfileStatusItem[] {
  const byProfile = new Map(items.map((item) => [item.profile, item]));
  const ordered = builtinProviderProfileOrder.map((profile) => byProfile.get(profile) ?? { profile, configured: false, valuesPrinted: false });
  const extras = items.filter((item) => !builtinProviderProfileOrder.includes(item.profile)).sort((left, right) => left.profile.localeCompare(right.profile));
  return [...ordered, ...extras];
}

function mergeProfile(items: ProviderProfileStatusItem[], updated: ProviderProfileStatusItem): ProviderProfileStatusItem[] {
  const next = new Map(orderedProfiles(items).map((item) => [item.profile, item]));
  next.set(updated.profile, { ...next.get(updated.profile), ...updated });
  return orderedProfiles(Array.from(next.values()));
}

function validationToneFor(validation: ProviderProfileValidation | null): Tone {
  if (!validation) return "source";
  return toneClass(validation.result?.terminalStatus ?? validation.status);
}

function terminalValidation(validation: ProviderProfileValidation): boolean {
  const status = String(validation.result?.terminalStatus ?? validation.status ?? "").toLowerCase();
  return ["completed", "failed", "canceled", "cancelled", "timeout", "blocked"].includes(status);
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => window.setTimeout(resolve, ms));
}
