"use client";

import { useState, useEffect } from "react";
import { Settings, Save, Loader2, CheckCircle, XCircle, FlaskConical, KeyRound, Mail, Languages, Cpu, Network, ScanText } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { ModelCombobox, ModelOption } from "@/components/ui/model-combobox";
import { useNotification } from "@/components/ui/notification";
import { useTranslationStore } from "@/lib/store";
import { API_BASE } from "@/lib/config";
import { useI18n } from "@/lib/i18n";
import type { AiTiersSettings } from "../types";

interface ProviderConfig {
  enabled: boolean;
  api_key?: string;
  base_url?: string;
  model?: string;
  timeout?: number;
  max_retries?: number;
}

interface SmtpConfig {
  enabled: boolean;
  host?: string;
  port: number;
  username?: string;
  password?: string;
  from_email?: string;
  use_tls: boolean;
}

interface SettingsConfig {
  google: ProviderConfig;
  google_cloud: ProviderConfig;
  openai: ProviderConfig;
  deepseek: ProviderConfig;
  zhipu: ProviderConfig;
  minimax: ProviderConfig;
  openrouter: ProviderConfig;
  openrouter_premium: ProviderConfig;
  zai: ProviderConfig;
  mistral: ProviderConfig;
  smtp: SmtpConfig;
  /** Paliers IA « Modèles & abonnements » — renvoyé tel quel à la sauvegarde. */
  ai_tiers?: AiTiersSettings;
  fallback_chain: string;
  fallback_chain_classic: string;
  fallback_chain_llm: string;
}

interface EnvInfo {
  openai: boolean;
  openrouter: boolean;
  openrouter_premium: boolean;
  deepseek: boolean;
  zhipu: boolean;
  minimax: boolean;
  zai: boolean;
  mistral: boolean;
  google_cloud: boolean;
  smtp: boolean;
}

const defaultConfig: SettingsConfig = {
  google: { enabled: true, timeout: 30, max_retries: 3 },
  google_cloud: { enabled: false, api_key: "", timeout: 30, max_retries: 3 },
  deepseek: { enabled: false, api_key: "", model: "deepseek-chat", base_url: "https://api.deepseek.com/v1" },
  zhipu: { enabled: false, api_key: "", model: "glm-5.3", base_url: "https://api.z.ai/api/paas/v4" },
  minimax: { enabled: false, api_key: "", model: "MiniMax-M3", base_url: "https://api.minimax.io/v1" },
  openai: { enabled: false, api_key: "", model: "gpt-4o-mini" },
  openrouter: { enabled: false, api_key: "", model: "deepseek/deepseek-v4-flash" },
  openrouter_premium: { enabled: false, api_key: "", model: "anthropic/claude-sonnet-5" },
  zai: { enabled: false, api_key: "", base_url: "https://api.x.ai/v1", model: "grok-2-1212" },
  mistral: { enabled: false, api_key: "", model: "mistral-ocr-latest", timeout: 180 },
  smtp: { enabled: false, host: "", port: 587, username: "", password: "", from_email: "", use_tls: true },
  fallback_chain: "google,google_cloud,openrouter,openrouter_premium,openai,deepseek,zai",
  fallback_chain_classic: "google,google_cloud",
  fallback_chain_llm: "openrouter,openrouter_premium,openai,deepseek,zai",
};

const defaultEnvInfo: EnvInfo = {
  openai: false,
  openrouter: false,
  openrouter_premium: false,
  deepseek: false,
  zhipu: false,
  minimax: false,
  zai: false,
  mistral: false,
  google_cloud: false,
  smtp: false,
};

/** En-tête de section de la page Fournisseurs. */
function ProviderSection({
  icon,
  title,
  description,
  children,
}: {
  icon: React.ReactNode;
  title: string;
  description: string;
  children: React.ReactNode;
}) {
  return (
    <section className="space-y-3">
      <div className="flex items-center gap-2">
        <span className="flex size-8 items-center justify-center rounded-lg bg-muted text-foreground/70">
          {icon}
        </span>
        <div>
          <h2 className="text-base font-semibold text-foreground">{title}</h2>
          <p className="text-xs text-muted-foreground">{description}</p>
        </div>
      </div>
      <div className="grid gap-4">{children}</div>
    </section>
  );
}

export default function AdminSettingsPage() {
  const { t } = useI18n();
  const [config, setConfig] = useState<SettingsConfig>(defaultConfig);
  const [envInfo, setEnvInfo] = useState<EnvInfo>(defaultEnvInfo);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [testResults, setTestResults] = useState<Record<string, "ok" | "error" | "testing" | "idle">>({});
  const [testMessages, setTestMessages] = useState<Record<string, string>>({});
  const [openaiModels, setOpenaiModels] = useState<ModelOption[]>([]);
  const [zaiModels, setZaiModels] = useState<ModelOption[]>([]);
  const [loadingModelsProvider, setLoadingModelsProvider] = useState<string | null>(null);
  const [isSendingTestEmail, setIsSendingTestEmail] = useState(false);
  const [testEmailResult, setTestEmailResult] = useState<"idle" | "ok" | "error">("idle");
  const [testEmailMessage, setTestEmailMessage] = useState<string>("");
  const { success, error, info } = useNotification();

  useEffect(() => {
    loadConfig();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const getToken = () => useTranslationStore.getState().settings.adminToken ?? "";

  const loadConfig = async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`${API_BASE}/api/v1/admin/settings`, {
        headers: { Authorization: `Bearer ${getToken()}` },
      });
      if (response.ok) {
        const envelope = await response.json();
        // API returns { data: {...settings...}, env_info: {...}, meta: {} }
        const payload = envelope.data ?? envelope;
        setConfig({ ...defaultConfig, ...payload });
        if (envelope.env_info) {
          setEnvInfo({ ...defaultEnvInfo, ...envelope.env_info });
        }
      } else {
        error({ title: t("admin.settings.loadErrorTitle"), description: t("admin.settings.loadErrorDesc", { status: response.status }) });
      }
    } catch (e) {
      error({ title: t("admin.settings.networkErrorTitle"), description: t("admin.settings.networkErrorDesc") });
      console.error("Failed to load settings:", e);
    } finally {
      setIsLoading(false);
    }
  };

  const saveConfig = async () => {
    setIsSaving(true);
    try {
      // `config` inclut `ai_tiers` tel que chargé (voir loadConfig) : la
      // sauvegarde des fournisseurs ne doit jamais réinitialiser les paliers
      // personnalisés de la page « Modèles & abonnements ».
      const response = await fetch(`${API_BASE}/api/v1/admin/settings`, {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${getToken()}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(config),
      });
      if (response.ok) {
        success({ title: t("admin.settings.savedTitle"), description: t("admin.settings.savedDesc") });
      } else {
        const body = await response.json().catch(() => ({}));
        error({ title: t("admin.settings.saveErrorTitle"), description: body.detail || `HTTP ${response.status}` });
      }
    } catch (e) {
      error({ title: t("admin.settings.networkErrorTitle"), description: t("admin.settings.networkSaveErrorDesc") });
    } finally {
      setIsSaving(false);
    }
  };

  const testProvider = async (provider: string) => {
    setTestResults((prev) => ({ ...prev, [provider]: "testing" }));
    setTestMessages((prev) => ({ ...prev, [provider]: "" }));
    try {
      // For SMTP, send current form values so unsaved changes are tested
      const smtpBody = provider === "smtp"
        ? { body: JSON.stringify(config.smtp) }
        : {};
      const response = await fetch(
        `${API_BASE}/api/v1/admin/providers/${provider}/test`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${getToken()}`,
            ...(provider === "smtp" ? { "Content-Type": "application/json" } : {}),
          },
          ...smtpBody,
        }
      );
      const data = await response.json();
      if (data.available) {
        setTestResults((prev) => ({ ...prev, [provider]: "ok" }));
        let detail: string;
        if (data.models_count !== undefined) {
          detail = t("admin.settings.modelsFound", { count: data.models_count, provider });
        } else if (data.test_result) {
          detail = `${t("admin.settings.connectionOk")} — "${data.test_result}"`;
        } else {
          detail = t("admin.settings.connectionOk");
        }
        setTestMessages((prev) => ({ ...prev, [provider]: detail }));
      } else {
        setTestResults((prev) => ({ ...prev, [provider]: "error" }));
        setTestMessages((prev) => ({ ...prev, [provider]: data.error || t("admin.settings.failure") }));
      }
    } catch (e) {
      setTestResults((prev) => ({ ...prev, [provider]: "error" }));
      setTestMessages((prev) => ({ ...prev, [provider]: t("admin.settings.networkErrorDesc") }));
    }
  };

  const fetchModels = async (provider: string) => {
    setLoadingModelsProvider(provider);
    try {
      const response = await fetch(
        `${API_BASE}/api/v1/admin/providers/${provider}/models`,
        { headers: { Authorization: `Bearer ${getToken()}` } }
      );
      if (response.ok) {
        const data = await response.json();
        const models: ModelOption[] = data.data || [];
        if (provider === "openai") setOpenaiModels(models);
        else if (provider === "zai") setZaiModels(models);
        info({ title: t("admin.settings.modelsFound", { count: models.length, provider }) });
      } else {
        const body = await response.json().catch(() => ({}));
        error({ title: t("admin.settings.providerError", { provider }), description: body.message || `HTTP ${response.status}` });
      }
    } catch (e) {
      error({ title: t("admin.settings.providerError", { provider }), description: t("admin.settings.networkErrorDesc") });
    } finally {
      setLoadingModelsProvider(null);
    }
  };

  type ProviderKey = "google" | "google_cloud" | "openai" | "deepseek" | "zhipu" | "minimax" | "openrouter" | "openrouter_premium" | "zai" | "mistral";
  const updateProvider = (provider: ProviderKey, updates: Partial<ProviderConfig>) => {
    setConfig((prev) => ({
      ...prev,
      [provider]: { ...prev[provider], ...updates } as ProviderConfig,
    }));
  };

  const updateSmtp = (updates: Partial<SmtpConfig>) => {
    setConfig((prev) => ({
      ...prev,
      smtp: { ...prev.smtp, ...updates },
    }));
  };

  const sendTestEmail = async () => {
    setIsSendingTestEmail(true);
    setTestEmailResult("idle");
    setTestEmailMessage("");
    try {
      const response = await fetch(
        `${API_BASE}/api/v1/admin/providers/smtp/test-send`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${getToken()}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify(config.smtp),
        }
      );
      const data = await response.json();
      if (data.available) {
        setTestEmailResult("ok");
        setTestEmailMessage(data.test_result || t("admin.settings.smtp.sent"));
      } else {
        setTestEmailResult("error");
        setTestEmailMessage(data.error || t("admin.settings.smtp.sendFailed"));
      }
    } catch {
      setTestEmailResult("error");
      setTestEmailMessage(t("admin.settings.networkErrorDesc"));
    } finally {
      setIsSendingTestEmail(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="size-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const envPlaceholder = (envSet: boolean) =>
    envSet ? t("admin.settings.envKeyPlaceholder") : "";

  return (
    <div className="space-y-8">
      <div className="flex items-center gap-3">
        <div className="w-10 h-10 bg-purple-600/20 rounded-lg flex items-center justify-center">
          <Settings className="w-5 h-5 text-purple-400" />
        </div>
        <div>
          <h1 className="text-xl font-semibold text-foreground">{t("admin.settings.title")}</h1>
          <p className="text-sm text-muted-foreground">{t("admin.settings.subtitle")}</p>
        </div>
      </div>

      {/* ── Traduction classique ── */}
      <ProviderSection
        icon={<Languages className="size-4" />}
        title={t("admin.settings.sectionClassic")}
        description={t("admin.settings.sectionClassicDesc")}
      >
        <ProviderCard
          title={t("admin.settings.google.title")}
          description={t("admin.settings.google.desc")}
          enabled={config.google.enabled}
          onToggle={(enabled) => updateProvider("google", { enabled })}
          onTest={() => testProvider("google")}
          testResult={testResults.google ?? "idle"}
          testMessage={testMessages.google}
          noApiKey
          t={t}
        />

        <ProviderCard
          title={t("admin.settings.googleCloud.title")}
          description={t("admin.settings.googleCloud.desc")}
          enabled={config.google_cloud.enabled}
          onToggle={(enabled) => updateProvider("google_cloud", { enabled })}
          onTest={() => testProvider("google_cloud")}
          testResult={testResults.google_cloud ?? "idle"}
          testMessage={testMessages.google_cloud}
          envKeySet={envInfo.google_cloud}
          t={t}
        >
          <div className="space-y-2">
            <Label htmlFor="google-cloud-key">{t("admin.settings.apiKey")}</Label>
            <Input
              id="google-cloud-key"
              type="password"
              placeholder={envPlaceholder(envInfo.google_cloud) || "AIza..."}
              value={config.google_cloud.api_key || ""}
              onChange={(e) => updateProvider("google_cloud", { api_key: e.target.value })}
            />
            <p className="text-xs text-muted-foreground">
              {t("admin.settings.googleCloud.hint")}
            </p>
          </div>
        </ProviderCard>
      </ProviderSection>

      {/* ── Fournisseurs IA directs ── */}
      <ProviderSection
        icon={<Cpu className="size-4" />}
        title={t("admin.settings.sectionDirect")}
        description={t("admin.settings.sectionDirectDesc")}
      >
        <ProviderCard
          title={t("admin.settings.deepseek.title")}
          description={t("admin.settings.deepseek.desc")}
          enabled={config.deepseek.enabled}
          onToggle={(enabled) => updateProvider("deepseek", { enabled })}
          onTest={() => testProvider("deepseek")}
          testResult={testResults.deepseek ?? "idle"}
          testMessage={testMessages.deepseek}
          envKeySet={envInfo.deepseek}
          t={t}
        >
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="deepseek-key">{t("admin.settings.apiKey")}</Label>
              <Input
                id="deepseek-key"
                type="password"
                placeholder={envPlaceholder(envInfo.deepseek) || "sk-..."}
                value={config.deepseek.api_key || ""}
                onChange={(e) => updateProvider("deepseek", { api_key: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="deepseek-model">{t("admin.settings.model")}</Label>
              <Input
                id="deepseek-model"
                placeholder="deepseek-chat"
                value={config.deepseek.model || ""}
                onChange={(e) => updateProvider("deepseek", { model: e.target.value })}
              />
            </div>
          </div>
        </ProviderCard>

        <ProviderCard
          title={t("admin.settings.zhipu.title")}
          description={t("admin.settings.zhipu.desc")}
          enabled={config.zhipu.enabled}
          onToggle={(enabled) => updateProvider("zhipu", { enabled })}
          onTest={() => testProvider("zhipu")}
          testResult={testResults.zhipu ?? "idle"}
          testMessage={testMessages.zhipu}
          envKeySet={envInfo.zhipu}
          t={t}
        >
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="zhipu-key">{t("admin.settings.apiKey")}</Label>
              <Input
                id="zhipu-key"
                type="password"
                placeholder={envPlaceholder(envInfo.zhipu) || "xxxxxxxxxxxxxxxx"}
                value={config.zhipu.api_key || ""}
                onChange={(e) => updateProvider("zhipu", { api_key: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="zhipu-model">{t("admin.settings.model")}</Label>
              <Input
                id="zhipu-model"
                placeholder="glm-5.3"
                value={config.zhipu.model || ""}
                onChange={(e) => updateProvider("zhipu", { model: e.target.value })}
              />
            </div>
          </div>
          <div className="mt-3 space-y-2">
            <Label htmlFor="zhipu-url">{t("admin.settings.baseUrl")}</Label>
            <Input
              id="zhipu-url"
              placeholder="https://api.z.ai/api/paas/v4"
              value={config.zhipu.base_url || ""}
              onChange={(e) => updateProvider("zhipu", { base_url: e.target.value })}
            />
            <p className="text-xs text-muted-foreground">
              {t("admin.settings.zhipu.urlHint")}
            </p>
          </div>
        </ProviderCard>

        <ProviderCard
          title={t("admin.settings.minimax.title")}
          description={t("admin.settings.minimax.desc")}
          enabled={config.minimax.enabled}
          onToggle={(enabled) => updateProvider("minimax", { enabled })}
          onTest={() => testProvider("minimax")}
          testResult={testResults.minimax ?? "idle"}
          testMessage={testMessages.minimax}
          envKeySet={envInfo.minimax}
          t={t}
        >
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="minimax-key">{t("admin.settings.apiKey")}</Label>
              <Input
                id="minimax-key"
                type="password"
                placeholder={envPlaceholder(envInfo.minimax) || "eyJ..."}
                value={config.minimax.api_key || ""}
                onChange={(e) => updateProvider("minimax", { api_key: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="minimax-model">{t("admin.settings.model")}</Label>
              <Input
                id="minimax-model"
                placeholder="MiniMax-M3"
                value={config.minimax.model || ""}
                onChange={(e) => updateProvider("minimax", { model: e.target.value })}
              />
            </div>
          </div>
        </ProviderCard>

        <ProviderCard
          title={t("admin.settings.openai.title")}
          description={t("admin.settings.openai.desc")}
          enabled={config.openai.enabled}
          onToggle={(enabled) => updateProvider("openai", { enabled })}
          onTest={() => testProvider("openai")}
          testResult={testResults.openai ?? "idle"}
          testMessage={testMessages.openai}
          envKeySet={envInfo.openai}
          t={t}
        >
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="openai-key">{t("admin.settings.apiKey")}</Label>
              <Input
                id="openai-key"
                type="password"
                placeholder={envPlaceholder(envInfo.openai) || "sk-..."}
                value={config.openai.api_key || ""}
                onChange={(e) => updateProvider("openai", { api_key: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="openai-model">{t("admin.settings.model")}</Label>
              <ModelCombobox
                value={config.openai.model || ""}
                onChange={(v) => updateProvider("openai", { model: v })}
                models={openaiModels}
                isLoading={loadingModelsProvider === "openai"}
                onFetchModels={() => fetchModels("openai")}
                providerLabel="OpenAI"
                placeholder="gpt-4o"
              />
            </div>
          </div>
        </ProviderCard>

        <ProviderCard
          title={t("admin.settings.zai.title")}
          description={t("admin.settings.zai.desc")}
          enabled={config.zai.enabled}
          onToggle={(enabled) => updateProvider("zai", { enabled })}
          onTest={() => testProvider("zai")}
          testResult={testResults.zai ?? "idle"}
          testMessage={testMessages.zai}
          envKeySet={envInfo.zai}
          t={t}
        >
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="zai-key">{t("admin.settings.apiKey")}</Label>
              <Input
                id="zai-key"
                type="password"
                placeholder={envPlaceholder(envInfo.zai) || "xai-..."}
                value={config.zai.api_key || ""}
                onChange={(e) => updateProvider("zai", { api_key: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="zai-model">{t("admin.settings.model")}</Label>
              <ModelCombobox
                value={config.zai.model || ""}
                onChange={(v) => updateProvider("zai", { model: v })}
                models={zaiModels}
                isLoading={loadingModelsProvider === "zai"}
                onFetchModels={() => fetchModels("zai")}
                providerLabel="xAI"
                placeholder="grok-2-1212"
              />
            </div>
          </div>
          <div className="mt-3 space-y-2">
            <Label htmlFor="zai-url">{t("admin.settings.baseUrl")}</Label>
            <Input
              id="zai-url"
              placeholder="https://api.x.ai/v1"
              value={config.zai.base_url || ""}
              onChange={(e) => updateProvider("zai", { base_url: e.target.value })}
            />
            <p className="text-xs text-muted-foreground">
              {t("admin.settings.zai.urlHint")}
            </p>
          </div>
        </ProviderCard>
      </ProviderSection>

      {/* ── Passerelles multi-modèles ── */}
      <ProviderSection
        icon={<Network className="size-4" />}
        title={t("admin.settings.sectionGateway")}
        description={t("admin.settings.sectionGatewayDesc")}
      >
        <ProviderCard
          title={t("admin.settings.openrouter.title")}
          description={t("admin.settings.openrouter.desc")}
          enabled={config.openrouter.enabled}
          onToggle={(enabled) => updateProvider("openrouter", { enabled })}
          onTest={() => testProvider("openrouter")}
          testResult={testResults.openrouter ?? "idle"}
          testMessage={testMessages.openrouter}
          envKeySet={envInfo.openrouter}
          t={t}
        >
          <div className="space-y-2">
            <Label htmlFor="openrouter-key">{t("admin.settings.openrouter.keyLabel")}</Label>
            <Input
              id="openrouter-key"
              type="password"
              placeholder={envInfo.openrouter ? t("admin.settings.openrouter.envSharedPlaceholder") : "sk-or-..."}
              value={config.openrouter.api_key || ""}
              onChange={(e) => updateProvider("openrouter", { api_key: e.target.value })}
            />
            <p className="text-xs text-amber-500">
              {t("admin.settings.openrouter.reminder")}
            </p>
          </div>
        </ProviderCard>

        <ProviderCard
          title={t("admin.settings.openrouterPremium.title")}
          description={t("admin.settings.openrouterPremium.desc")}
          enabled={config.openrouter_premium.enabled}
          onToggle={(enabled) => updateProvider("openrouter_premium", { enabled })}
          onTest={() => testProvider("openrouter_premium")}
          testResult={testResults.openrouter_premium ?? "idle"}
          testMessage={testMessages.openrouter_premium}
          envKeySet={envInfo.openrouter_premium}
          t={t}
        >
          <div className="space-y-2">
            <p className="text-xs text-amber-500">
              {t("admin.settings.openrouterPremium.reminder")}
            </p>
          </div>
        </ProviderCard>
      </ProviderSection>

      {/* ── OCR ── */}
      <ProviderSection
        icon={<ScanText className="size-4" />}
        title={t("admin.settings.sectionOcr")}
        description={t("admin.settings.sectionOcrDesc")}
      >
        <ProviderCard
          title={t("admin.settings.mistral.title")}
          description={t("admin.settings.mistral.desc")}
          enabled={config.mistral.enabled}
          onToggle={(enabled) => updateProvider("mistral", { enabled })}
          onTest={() => testProvider("mistral")}
          testResult={testResults.mistral ?? "idle"}
          testMessage={testMessages.mistral}
          envKeySet={envInfo.mistral}
          t={t}
        >
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="mistral-key">{t("admin.settings.mistral.keyLabel")}</Label>
              <Input
                id="mistral-key"
                type="password"
                placeholder={envPlaceholder(envInfo.mistral) || "Clé console.mistral.ai"}
                value={config.mistral.api_key || ""}
                onChange={(e) => updateProvider("mistral", { api_key: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="mistral-model">{t("admin.settings.mistral.modelLabel")}</Label>
              <Input
                id="mistral-model"
                placeholder="mistral-ocr-latest"
                value={config.mistral.model || ""}
                onChange={(e) => updateProvider("mistral", { model: e.target.value })}
              />
              <p className="text-xs text-muted-foreground">
                {t("admin.settings.mistral.modelHint")}
              </p>
            </div>
          </div>
        </ProviderCard>
      </ProviderSection>

      {/* ── Emails ── */}
      <ProviderSection
        icon={<Mail className="size-4" />}
        title={t("admin.settings.sectionEmails")}
        description={t("admin.settings.sectionEmailsDesc")}
      >
        <Card className={config.smtp.enabled ? "border-primary/30 overflow-visible" : "overflow-visible"}>
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <CardTitle className="text-base">{t("admin.settings.smtp.title")}</CardTitle>
                <Badge variant={config.smtp.enabled ? "default" : "secondary"} className="text-xs">
                  {config.smtp.enabled ? t("admin.settings.enabled") : t("admin.settings.disabled")}
                </Badge>
                {envInfo.smtp && (
                  <Badge variant="outline" className="text-xs gap-1 border-green-500/40 text-green-400">
                    <KeyRound className="size-3" />
                    {t("admin.settings.envBadge")}
                  </Badge>
                )}
              </div>
              <div className="flex items-center gap-3">
                <TestButton
                  result={testResults.smtp ?? "idle"}
                  onTest={() => testProvider("smtp")}
                  labels={{
                    test: t("admin.settings.test"),
                    testing: t("admin.settings.testing"),
                    ok: t("admin.settings.ok"),
                    error: t("admin.settings.error"),
                  }}
                />
                <Switch checked={config.smtp.enabled} onCheckedChange={(enabled) => updateSmtp({ enabled })} />
              </div>
            </div>
            <CardDescription>{t("admin.settings.smtp.desc")}</CardDescription>
            {testMessages.smtp && (
              <p className={`text-xs mt-1 ${testResults.smtp === "ok" ? "text-green-400" : "text-red-400"}`}>
                {testMessages.smtp}
              </p>
            )}
          </CardHeader>
          <CardContent className="pt-0 space-y-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="smtp-host">{t("admin.settings.smtp.host")}</Label>
                <Input
                  id="smtp-host"
                  placeholder={envInfo.smtp ? t("admin.settings.envConfigured") : "smtp.example.com"}
                  value={config.smtp.host || ""}
                  onChange={(e) => updateSmtp({ host: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="smtp-port">{t("admin.settings.smtp.port")}</Label>
                <Input
                  id="smtp-port"
                  type="number"
                  placeholder="587"
                  value={config.smtp.port}
                  onChange={(e) => updateSmtp({ port: parseInt(e.target.value) || 587 })}
                />
              </div>
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="smtp-username">{t("admin.settings.smtp.username")}</Label>
                <Input
                  id="smtp-username"
                  placeholder={envInfo.smtp ? t("admin.settings.envConfigured") : "user@example.com"}
                  value={config.smtp.username || ""}
                  onChange={(e) => updateSmtp({ username: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="smtp-password">{t("admin.settings.smtp.password")}</Label>
                <Input
                  id="smtp-password"
                  type="password"
                  placeholder="••••••••"
                  value={config.smtp.password || ""}
                  onChange={(e) => updateSmtp({ password: e.target.value })}
                />
              </div>
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="smtp-from">{t("admin.settings.smtp.fromEmail")}</Label>
                <Input
                  id="smtp-from"
                  type="email"
                  placeholder={envInfo.smtp ? t("admin.settings.envConfigured") : "noreply@example.com"}
                  value={config.smtp.from_email || ""}
                  onChange={(e) => updateSmtp({ from_email: e.target.value })}
                />
              </div>
              <div className="flex items-center gap-3 pt-6">
                <Switch
                  checked={config.smtp.use_tls}
                  onCheckedChange={(checked) => updateSmtp({ use_tls: checked })}
                />
                <Label>{t("admin.settings.smtp.useTls")}</Label>
              </div>
            </div>
            <div className="flex items-center gap-3 pt-2">
              <Button
                variant="outline"
                size="sm"
                onClick={sendTestEmail}
                disabled={isSendingTestEmail || !config.smtp.enabled}
                className="h-8"
              >
                {isSendingTestEmail ? (
                  <><Loader2 className="size-3 animate-spin me-1" />{t("admin.settings.sending")}</>
                ) : testEmailResult === "ok" ? (
                  <><CheckCircle className="size-3 text-green-500 me-1" />{t("admin.settings.smtp.sent")}</>
                ) : testEmailResult === "error" ? (
                  <><XCircle className="size-3 text-red-500 me-1" />{t("admin.settings.failure")}</>
                ) : (
                  <><Mail className="size-3 me-1" />{t("admin.settings.smtp.sendTest")}</>
                )}
              </Button>
              {testEmailMessage && (
                <p className={`text-xs ${testEmailResult === "ok" ? "text-green-400" : "text-red-400"}`}>
                  {testEmailMessage}
                </p>
              )}
            </div>
          </CardContent>
        </Card>
      </ProviderSection>

      {/* ── Chaîne de secours ── */}
      <ProviderSection
        icon={<Network className="size-4" />}
        title={t("admin.settings.fallback.title")}
        description={t("admin.settings.fallback.desc")}
      >
        <Card>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label>{t("admin.settings.fallback.classic")}</Label>
              <Input
                value={config.fallback_chain_classic}
                onChange={(e) => setConfig((prev) => ({ ...prev, fallback_chain_classic: e.target.value }))}
                placeholder="google,google_cloud"
              />
            </div>
            <div className="space-y-2">
              <Label>{t("admin.settings.fallback.llm")}</Label>
              <Input
                value={config.fallback_chain_llm}
                onChange={(e) => setConfig((prev) => ({ ...prev, fallback_chain_llm: e.target.value }))}
                placeholder="openrouter,openai,deepseek,zai"
              />
            </div>
            <p className="text-xs text-amber-500">{t("admin.settings.fallback.note")}</p>
          </CardContent>
        </Card>
      </ProviderSection>

      <div className="flex justify-end">
        <Button onClick={saveConfig} disabled={isSaving} size="lg">
          {isSaving ? (
            <>
              <Loader2 className="me-2 size-4 animate-spin" />
              {t("admin.settings.saving")}
            </>
          ) : (
            <>
              <Save className="me-2 size-4" />
              {t("admin.settings.save")}
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

type TestState = "ok" | "error" | "testing" | "idle";

function TestButton({
  result,
  onTest,
  labels,
}: {
  result: TestState;
  onTest: () => void;
  labels: { test: string; testing: string; ok: string; error: string };
}) {
  return (
    <Button variant="outline" size="sm" onClick={onTest} disabled={result === "testing"} className="h-8">
      {result === "testing" ? (
        <><Loader2 className="size-3 animate-spin me-1" />{labels.testing}</>
      ) : result === "ok" ? (
        <><CheckCircle className="size-3 text-green-500 me-1" />{labels.ok}</>
      ) : result === "error" ? (
        <><XCircle className="size-3 text-red-500 me-1" />{labels.error}</>
      ) : (
        <><FlaskConical className="size-3 me-1" />{labels.test}</>
      )}
    </Button>
  );
}

function ProviderCard({
  title,
  description,
  enabled,
  onToggle,
  onTest,
  testResult,
  testMessage,
  noApiKey = false,
  envKeySet = false,
  t,
  children,
}: {
  title: string;
  description: string;
  enabled: boolean;
  onToggle: (enabled: boolean) => void;
  onTest: () => void;
  testResult: TestState;
  testMessage?: string;
  noApiKey?: boolean;
  envKeySet?: boolean;
  t: (key: string, params?: Record<string, string | number>) => string;
  children?: React.ReactNode;
}) {
  return (
    <Card className={enabled ? "border-primary/30 overflow-visible" : "overflow-visible"}>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <CardTitle className="text-base">{title}</CardTitle>
            <Badge variant={enabled ? "default" : "secondary"} className="text-xs">
              {enabled ? t("admin.settings.enabled") : t("admin.settings.disabled")}
            </Badge>
            {envKeySet && !noApiKey && (
              <Badge variant="outline" className="text-xs gap-1 border-green-500/40 text-green-400">
                <KeyRound className="size-3" />
                {t("admin.settings.envBadge")}
              </Badge>
            )}
          </div>
          <div className="flex items-center gap-3">
            <TestButton
              result={testResult}
              onTest={onTest}
              labels={{
                test: t("admin.settings.test"),
                testing: t("admin.settings.testing"),
                ok: t("admin.settings.ok"),
                error: t("admin.settings.error"),
              }}
            />
            <Switch checked={enabled} onCheckedChange={onToggle} />
          </div>
        </div>
        <CardDescription>{description}</CardDescription>
        {testMessage && (
          <p className={`text-xs mt-1 ${testResult === "ok" ? "text-green-400" : "text-red-400"}`}>
            {testMessage}
          </p>
        )}
      </CardHeader>
      {!noApiKey && children && <CardContent className="pt-0">{children}</CardContent>}
    </Card>
  );
}
