/**
 * Settings -> AI Profiles. This is the durable CRUD surface for named runtime
 * profiles; first-run stays a small default-profile bootstrap.
 */

import { useCallback, useEffect, useMemo, useState } from "react";

import type {
  AgentProfile,
  GatewayError,
  ProfileModelCatalogEntry,
} from "@/domain";
import { useGateways } from "@/app/di";
import { Button, Input, Panel, cn } from "@/shared";

type ProfileTab = "codex" | "claude" | "openCode";

const TABS: Array<{ id: ProfileTab; label: string }> = [
  { id: "codex", label: "Codex" },
  { id: "claude", label: "Claude" },
  { id: "openCode", label: "OpenCode-local" },
];

const EMPTY_CATALOGUE: Record<"codex" | "claude", ProfileModelCatalogEntry[]> = {
  codex: [],
  claude: [],
};

function describe(e: unknown): string {
  if (e && typeof e === "object" && "message" in e) {
    return String((e as GatewayError).message);
  }
  return String(e);
}

function tabFor(profile: AgentProfile): ProfileTab | null {
  if (profile.structuredAdapter === "codex") return "codex";
  if (profile.structuredAdapter === "claude") return "claude";
  if (profile.structuredAdapter === "openCode" && profile.opencode) {
    return "openCode";
  }
  return null;
}

function modelOf(profile: AgentProfile): string {
  if (profile.structuredAdapter === "openCode") {
    return profile.opencode?.model ?? profile.opencodeProvider?.model ?? "";
  }
  return profile.model ?? "";
}

function withModel(profile: AgentProfile, model: string): AgentProfile {
  const nextModel = model.trim() || undefined;
  if (profile.structuredAdapter === "openCode" && profile.opencode) {
    return {
      ...profile,
      opencode: { ...profile.opencode, model: model.trim() },
    };
  }
  return { ...profile, model: nextModel };
}

function optionLabel(entry: ProfileModelCatalogEntry): string {
  return entry.recommended
    ? `${entry.displayName} (${entry.modelId}, recommande)`
    : `${entry.displayName} (${entry.modelId})`;
}

export function ProfilesSettings() {
  const { profile } = useGateways();
  const [profiles, setProfiles] = useState<AgentProfile[]>([]);
  const [references, setReferences] = useState<AgentProfile[]>([]);
  const [catalogue, setCatalogue] = useState(EMPTY_CATALOGUE);
  const [activeTab, setActiveTab] = useState<ProfileTab>("codex");
  const [drafts, setDrafts] = useState<Record<string, AgentProfile>>({});
  const [error, setError] = useState<string | null>(null);
  const [catalogueWarning, setCatalogueWarning] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const refresh = useCallback(async () => {
    setError(null);
    try {
      const [saved, refs] = await Promise.all([
        profile.listProfiles(),
        profile.referenceProfiles(),
      ]);
      setProfiles(saved);
      setReferences(refs);
      setDrafts(Object.fromEntries(saved.map((p) => [p.id, p])));
    } catch (e) {
      setError(describe(e));
    }
  }, [profile]);

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

  useEffect(() => {
    let cancelled = false;
    async function loadCatalogue() {
      setCatalogueWarning(null);
      const [codex, claude] = await Promise.allSettled([
        profile.listCodexModels(),
        profile.listClaudeModels(),
      ]);
      if (cancelled) return;
      setCatalogue({
        codex: codex.status === "fulfilled" ? codex.value : [],
        claude: claude.status === "fulfilled" ? claude.value : [],
      });
      if (codex.status === "rejected" || claude.status === "rejected") {
        setCatalogueWarning(
          "Catalogue de modeles indisponible: saisie manuelle active.",
        );
      }
    }
    void loadCatalogue();
    return () => {
      cancelled = true;
    };
  }, [profile]);

  const visibleProfiles = useMemo(
    () => profiles.filter((p) => tabFor(p) === activeTab),
    [profiles, activeTab],
  );

  const seed = useMemo(
    () => references.find((p) => tabFor(p) === activeTab) ?? null,
    [references, activeTab],
  );

  function updateDraft(id: string, updater: (profile: AgentProfile) => AgentProfile) {
    setDrafts((prev) => {
      const current = prev[id] ?? profiles.find((p) => p.id === id);
      if (!current) return prev;
      return { ...prev, [id]: updater(current) };
    });
  }

  async function createFromSeed() {
    if (!seed) return;
    setBusy(true);
    setError(null);
    try {
      const models =
        activeTab === "codex" || activeTab === "claude"
          ? catalogue[activeTab]
          : [];
      const recommended = models.find((m) => m.recommended)?.modelId;
      await profile.cloneProfileFromSeed({
        seedProfileId: seed.id,
        name: `${seed.name} copy`,
        model: recommended,
      });
      await refresh();
    } catch (e) {
      setError(describe(e));
    } finally {
      setBusy(false);
    }
  }

  async function save(id: string) {
    const draft = drafts[id];
    if (!draft) return;
    setBusy(true);
    setError(null);
    try {
      await profile.saveProfile(draft);
      await refresh();
    } catch (e) {
      setError(describe(e));
    } finally {
      setBusy(false);
    }
  }

  async function duplicate(source: AgentProfile) {
    setBusy(true);
    setError(null);
    try {
      await profile.cloneProfileFromSeed({
        seedProfileId: source.id,
        name: `${source.name} copy`,
        model:
          source.structuredAdapter === "codex" ||
          source.structuredAdapter === "claude"
            ? modelOf(source) || undefined
            : undefined,
      });
      await refresh();
    } catch (e) {
      setError(describe(e));
    } finally {
      setBusy(false);
    }
  }

  async function del(source: AgentProfile) {
    setBusy(true);
    setError(null);
    try {
      await profile.deleteProfile(source.id);
      await refresh();
    } catch (e) {
      setError(describe(e));
    } finally {
      setBusy(false);
    }
  }

  const modelOptions =
    activeTab === "codex" || activeTab === "claude" ? catalogue[activeTab] : [];

  return (
    <Panel
      aria-label="ai profiles settings"
      title="Profils IA"
      actions={
        <Button size="sm" onClick={() => void createFromSeed()} disabled={!seed || busy}>
          Creer un profil
        </Button>
      }
    >
      <div className="flex flex-col gap-4">
        <div
          role="tablist"
          aria-label="types de profils IA"
          className="inline-flex w-fit rounded-md border border-border bg-raised p-0.5"
        >
          {TABS.map((tab) => (
            <button
              key={tab.id}
              type="button"
              role="tab"
              aria-selected={activeTab === tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={cn(
                "h-7 rounded px-3 text-xs font-medium transition-colors",
                activeTab === tab.id
                  ? "bg-surface text-content shadow-sm"
                  : "text-muted hover:text-content",
              )}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {error && (
          <p role="alert" className="text-sm text-danger">
            {error}
          </p>
        )}
        {catalogueWarning && (
          <p className="text-xs text-muted">{catalogueWarning}</p>
        )}

        <datalist id={`profile-models-${activeTab}`}>
          {modelOptions.map((entry) => (
            <option key={entry.modelId} value={entry.modelId}>
              {optionLabel(entry)}
            </option>
          ))}
        </datalist>

        {visibleProfiles.length === 0 ? (
          <p className="text-sm text-muted">
            Aucun profil {TABS.find((tab) => tab.id === activeTab)?.label} configure.
          </p>
        ) : (
          <ul className="flex flex-col gap-3">
            {visibleProfiles.map((saved) => {
              const draft = drafts[saved.id] ?? saved;
              const model = modelOf(draft);
              const dirty = JSON.stringify(draft) !== JSON.stringify(saved);
              return (
                <li
                  key={saved.id}
                  className="rounded-md border border-border bg-surface p-3"
                >
                  <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
                    <label className="flex min-w-0 flex-col gap-1">
                      <span className="text-xs font-medium text-muted">Nom</span>
                      <Input
                        aria-label={`nom du profil ${saved.name}`}
                        value={draft.name}
                        onChange={(e) =>
                          updateDraft(saved.id, (p) => ({
                            ...p,
                            name: e.target.value,
                          }))
                        }
                      />
                    </label>

                    <label className="flex min-w-0 flex-col gap-1">
                      <span className="text-xs font-medium text-muted">Modele</span>
                      <Input
                        aria-label={`modele du profil ${saved.name}`}
                        list={`profile-models-${activeTab}`}
                        placeholder={
                          modelOptions.length > 0
                            ? "Choisir ou saisir un modele"
                            : "Saisir un modele"
                        }
                        value={model}
                        onChange={(e) =>
                          updateDraft(saved.id, (p) =>
                            withModel(p, e.target.value),
                          )
                        }
                      />
                    </label>
                  </div>

                  <div className="mt-2 flex flex-wrap items-center justify-between gap-2">
                    <code className="min-w-0 truncate text-xs text-muted">
                      {draft.command}
                      {model ? ` · ${model}` : ""}
                    </code>
                    <span className="flex flex-wrap gap-1.5">
                      <Button
                        size="sm"
                        variant="primary"
                        disabled={!dirty || busy || draft.name.trim() === ""}
                        onClick={() => void save(saved.id)}
                      >
                        Enregistrer
                      </Button>
                      <Button
                        size="sm"
                        variant="secondary"
                        disabled={busy}
                        onClick={() => void duplicate(saved)}
                      >
                        Dupliquer
                      </Button>
                      <Button
                        size="sm"
                        variant="ghost"
                        disabled={busy}
                        className="text-danger hover:text-danger"
                        aria-label={`supprimer ${saved.name}`}
                        onClick={() => void del(saved)}
                      >
                        Supprimer
                      </Button>
                    </span>
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </Panel>
  );
}
