import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  AlertCircle,
  AlertTriangle,
  CheckCircle,
  Eye,
  EyeOff,
  Globe,
  KeyRound,
  Loader2,
  Save,
  XCircle,
} from 'lucide-react';
import { agentSettingsBridge } from '../../lib/agentSettingsBridge';
import {
  AGENT_PROVIDER_LABELS,
  AgentConfigStatus,
  AgentProviderKind,
  AgentTaskRoute,
  SaveAgentRuntimeConfigRequest,
  TASK_LABELS,
  TASK_PROFILES,
  TaskProfile,
} from '../../types/agentSettings';
import { ConfirmDialog } from './ConfirmDialog';
import { DEFAULT_MODEL_OPTIONS, ModelSelector, OLLAMA_MODEL_OPTIONS } from './ModelSelector';
import { HelpIcon } from './Tooltip';
import { ValidatedInput, ValidationStatus } from './ValidatedInput';

interface AgentSettingsFormProps {
  status: AgentConfigStatus | null;
  onStatusChange: (status: AgentConfigStatus) => void;
}

interface ProviderFormState {
  enabled: boolean;
  baseUrl: string;
  defaultModel: string;
}

interface FormState {
  remote: ProviderFormState;
  ollama: ProviderFormState;
  taskDefaults: Record<TaskProfile, AgentTaskRoute>;
  remoteApiKey: string;
}

interface ValidationState {
  remoteBaseUrl: ValidationStatus;
  remoteBaseUrlError?: string;
  ollamaBaseUrl: ValidationStatus;
  ollamaBaseUrlError?: string;
  apiKey: ValidationStatus;
}

const REMOTE_DEFAULT_BASE_URL = 'https://api.z.ai/api/coding/paas/v4';
const OLLAMA_DEFAULT_BASE_URL = 'http://localhost:11434/v1';

const PROVIDER_MODEL_OPTIONS: Record<AgentProviderKind, typeof DEFAULT_MODEL_OPTIONS> = {
  remote: DEFAULT_MODEL_OPTIONS,
  ollama: OLLAMA_MODEL_OPTIONS,
};

const OLLAMA_EXAMPLE_MODELS = ['llama3.2', 'qwen3-coder', 'deepseek-r1:14b', 'mistral:latest'];

const mergeTaskDefaults = (
  taskDefaults: Partial<Record<TaskProfile, AgentTaskRoute>>,
): Record<TaskProfile, AgentTaskRoute> =>
  TASK_PROFILES.reduce((acc, profile) => {
    acc[profile] = taskDefaults[profile] ?? { provider: 'remote', model: '' };
    return acc;
  }, {} as Record<TaskProfile, AgentTaskRoute>);

const validateUrl = (url: string): { valid: boolean; error?: string } => {
  if (!url.trim()) {
    return { valid: false, error: 'Base URL is required' };
  }

  try {
    new URL(url);
    return { valid: true };
  } catch {
    return { valid: false, error: 'Please enter a valid URL (e.g., https://api.example.com)' };
  }
};

const providerDefaultModel = (
  formState: FormState,
  provider: AgentProviderKind,
) => (provider === 'remote' ? formState.remote.defaultModel : formState.ollama.defaultModel);

export const AgentSettingsForm: React.FC<AgentSettingsFormProps> = ({
  status,
  onStatusChange,
}) => {
  const [formState, setFormState] = useState<FormState>({
    remote: {
      enabled: true,
      baseUrl: REMOTE_DEFAULT_BASE_URL,
      defaultModel: '',
    },
    ollama: {
      enabled: false,
      baseUrl: OLLAMA_DEFAULT_BASE_URL,
      defaultModel: '',
    },
    taskDefaults: mergeTaskDefaults({}),
    remoteApiKey: '',
  });
  const [initialState, setInitialState] = useState<FormState | null>(null);
  const [validation, setValidation] = useState<ValidationState>({
    remoteBaseUrl: 'idle',
    ollamaBaseUrl: 'idle',
    apiKey: 'idle',
  });
  const [showApiKey, setShowApiKey] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [isBusy, setIsBusy] = useState(false);
  const [showClearConfirm, setShowClearConfirm] = useState(false);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [dontAskAgain, setDontAskAgain] = useState(false);
  const saveButtonRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (!status) {
      return;
    }

    const nextState: FormState = {
      remote: {
        enabled: status.providers.remote.enabled,
        baseUrl: status.providers.remote.baseUrl,
        defaultModel: status.providers.remote.defaultModel,
      },
      ollama: {
        enabled: status.providers.ollama.enabled,
        baseUrl: status.providers.ollama.baseUrl,
        defaultModel: status.providers.ollama.defaultModel,
      },
      taskDefaults: mergeTaskDefaults(status.taskDefaults),
      remoteApiKey: '',
    };

    setFormState(nextState);
    setInitialState(nextState);
    setError(null);
    setSuccess(null);
    setHasUnsavedChanges(false);
    setValidation({
      remoteBaseUrl: nextState.remote.baseUrl ? 'valid' : 'idle',
      ollamaBaseUrl: nextState.ollama.baseUrl ? 'valid' : 'idle',
      apiKey: 'idle',
    });
  }, [status]);

  useEffect(() => {
    if (!initialState) {
      return;
    }

    const hasChanges =
      JSON.stringify({
        remote: formState.remote,
        ollama: formState.ollama,
        taskDefaults: formState.taskDefaults,
      }) !==
        JSON.stringify({
          remote: initialState.remote,
          ollama: initialState.ollama,
          taskDefaults: initialState.taskDefaults,
        }) || Boolean(formState.remoteApiKey.trim());

    setHasUnsavedChanges(hasChanges);
  }, [formState, initialState]);

  useEffect(() => {
    if (!formState.remote.baseUrl.trim()) {
      setValidation((prev) => ({
        ...prev,
        remoteBaseUrl: 'idle',
        remoteBaseUrlError: undefined,
      }));
      return;
    }

    const result = validateUrl(formState.remote.baseUrl);
    setValidation((prev) => ({
      ...prev,
      remoteBaseUrl: result.valid ? 'valid' : 'invalid',
      remoteBaseUrlError: result.error,
    }));
  }, [formState.remote.baseUrl]);

  useEffect(() => {
    if (!formState.ollama.baseUrl.trim()) {
      setValidation((prev) => ({
        ...prev,
        ollamaBaseUrl: 'idle',
        ollamaBaseUrlError: undefined,
      }));
      return;
    }

    const result = validateUrl(formState.ollama.baseUrl);
    setValidation((prev) => ({
      ...prev,
      ollamaBaseUrl: result.valid ? 'valid' : 'invalid',
      ollamaBaseUrlError: result.error,
    }));
  }, [formState.ollama.baseUrl]);

  useEffect(() => {
    setValidation((prev) => ({
      ...prev,
      apiKey: formState.remoteApiKey.trim() ? 'valid' : 'idle',
    }));
  }, [formState.remoteApiKey]);

  const runtimeRequest = useMemo<SaveAgentRuntimeConfigRequest | null>(() => {
    if (!status) {
      return null;
    }

    return {
      remote: {
        enabled: formState.remote.enabled,
        baseUrl: formState.remote.baseUrl,
        defaultModel: formState.remote.defaultModel,
      },
      ollama: {
        enabled: formState.ollama.enabled,
        baseUrl: formState.ollama.baseUrl,
        defaultModel: formState.ollama.defaultModel,
      },
      taskDefaults: formState.taskDefaults,
      secEdgarUserAgent: status.secEdgarUserAgent,
    };
  }, [formState, status]);

  const saveRuntimeConfig = useCallback(async () => {
    if (!runtimeRequest) {
      throw new Error('Settings are not loaded yet');
    }

    const nextStatus = await agentSettingsBridge.saveRuntimeConfig(runtimeRequest);
    onStatusChange(nextStatus);
    return nextStatus;
  }, [onStatusChange, runtimeRequest]);

  const handleSaveRuntime = async () => {
    if (validation.remoteBaseUrl === 'invalid' || validation.ollamaBaseUrl === 'invalid') {
      setError('Please fix validation errors before saving');
      return;
    }

    setIsBusy(true);
    setError(null);
    setSuccess(null);

    try {
      await saveRuntimeConfig();
      setSuccess('Settings saved successfully');
      setInitialState({ ...formState, remoteApiKey: '' });
      setFormState((current) => ({ ...current, remoteApiKey: '' }));
    } catch (saveError) {
      setError(
        saveError instanceof Error ? saveError.message : 'Failed to save settings. Please try again.',
      );
    } finally {
      setIsBusy(false);
    }
  };

  const handleSaveRemoteApiKey = async () => {
    if (!formState.remoteApiKey.trim()) {
      setError('Please enter an API key');
      return;
    }

    setIsBusy(true);
    setError(null);
    setSuccess(null);

    try {
      await saveRuntimeConfig();
      const nextStatus = await agentSettingsBridge.updateRemoteApiKey({
        apiKey: formState.remoteApiKey,
      });
      onStatusChange(nextStatus);
      setFormState((current) => ({ ...current, remoteApiKey: '' }));
      setValidation((prev) => ({ ...prev, apiKey: 'idle' }));
      setSuccess(
        status?.providers.remote.hasApiKey ? 'API key updated successfully' : 'API key saved successfully',
      );
    } catch (saveError) {
      setError(
        saveError instanceof Error ? saveError.message : 'Failed to save API key. Please try again.',
      );
    } finally {
      setIsBusy(false);
    }
  };

  const handleClearRemoteApiKey = async () => {
    setIsBusy(true);
    setError(null);
    setSuccess(null);
    setShowClearConfirm(false);

    try {
      await saveRuntimeConfig();
      const nextStatus = await agentSettingsBridge.clearRemoteApiKey();
      onStatusChange(nextStatus);
      setSuccess('API key cleared successfully');
    } catch (clearError) {
      setError(
        clearError instanceof Error ? clearError.message : 'Failed to clear API key. Please try again.',
      );
    } finally {
      setIsBusy(false);
    }
  };

  const setTaskRoute = useCallback(
    (task: TaskProfile, updates: Partial<AgentTaskRoute>) => {
      setFormState((current) => ({
        ...current,
        taskDefaults: {
          ...current.taskDefaults,
          [task]: {
            ...current.taskDefaults[task],
            ...updates,
          },
        },
      }));
    },
    [],
  );

  const applyProviderToAllTasks = useCallback((provider: AgentProviderKind) => {
    setFormState((current) => ({
      ...current,
      taskDefaults: TASK_PROFILES.reduce(
        (nextRoutes, task) => {
          nextRoutes[task] = {
            provider,
            model: '',
          };
          return nextRoutes;
        },
        {} as Record<TaskProfile, AgentTaskRoute>,
      ),
    }));
  }, []);

  if (!status) {
    return (
      <div className="rounded-lg border border-term-border bg-term-surface px-6 py-4 text-sm font-mono text-term-text-muted">
        <div className="flex items-center gap-3">
          <Loader2 className="h-4 w-4 animate-spin" />
          Loading AI settings...
        </div>
      </div>
    );
  }

  const remoteReadyLabel = status.providers.remote.configured ? 'Ready' : 'Needs setup';
  const ollamaReadyLabel = status.providers.ollama.configured ? 'Ready' : 'Needs setup';
  const isFormValid =
    validation.remoteBaseUrl !== 'invalid' && validation.ollamaBaseUrl !== 'invalid';

  return (
    <div className="space-y-6">
      <section className="rounded-lg bg-term-surface p-6 shadow-sm">
        <div className="mb-5 flex items-center justify-between gap-4">
          <div>
            <h3 className="text-base font-mono font-semibold text-term-text">Runtime Status</h3>
            <p className="mt-1.5 text-xs font-mono text-term-text-muted">
              {status.configured ? 'All configured task routes are available' : 'Some flows still need configuration'}
            </p>
          </div>
          <div className="text-right text-xs font-mono text-term-text-muted">
            <div className="flex items-center justify-end gap-2">
              <Globe className="h-3.5 w-3.5" />
              <span>Remote: {remoteReadyLabel}</span>
            </div>
            <div className="mt-1 flex items-center justify-end gap-2">
              <Globe className="h-3.5 w-3.5" />
              <span>Local (Ollama): {ollamaReadyLabel}</span>
            </div>
            <div className="mt-1 flex items-center justify-end gap-2">
              <KeyRound className="h-3.5 w-3.5" />
              <span>Remote API key: {status.providers.remote.hasApiKey ? 'Stored' : 'Missing'}</span>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <div
            className={`flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs font-mono ${
              status.configured
                ? 'border-[var(--term-status-success-border)] bg-[var(--term-status-success)] text-positive'
                : 'border-[var(--term-status-error-border)] bg-[var(--term-status-error)] text-negative'
            }`}
          >
            {status.configured ? (
              <>
                <CheckCircle className="h-4 w-4" />
                Configured
              </>
            ) : (
              <>
                <AlertTriangle className="h-4 w-4" />
                Needs Configuration
              </>
            )}
          </div>
          {hasUnsavedChanges && (
            <div className="flex items-center gap-2 rounded-md border border-[var(--term-status-warning-border)] bg-[var(--term-status-warning)] px-3 py-1.5 text-xs font-mono text-warning">
              <AlertCircle className="h-4 w-4" />
              Unsaved changes
            </div>
          )}
        </div>
      </section>

      <section className="rounded-lg bg-term-surface p-6 shadow-sm">
        <div className="mb-6">
          <div className="flex items-center gap-2">
            <h3 className="text-base font-mono font-semibold text-term-text">Remote Provider</h3>
            <HelpIcon tooltip="Configure the external OpenAI-compatible provider." />
          </div>
          <p className="mt-1.5 text-xs font-mono leading-6 text-term-text-muted">
            Use this provider for hosted models that require an API key.
          </p>
        </div>

        <div className="grid gap-5 md:grid-cols-2">
          <label className="flex items-center gap-2 text-xs font-mono text-term-text">
            <input
              type="checkbox"
              checked={formState.remote.enabled}
              onChange={(event) =>
                setFormState((current) => ({
                  ...current,
                  remote: { ...current.remote, enabled: event.target.checked },
                }))
              }
              className="h-4 w-4 rounded border-term-border bg-term-bg text-info focus:ring-2 focus:ring-info focus:ring-offset-2 focus:ring-offset-term-surface"
            />
            Enabled
          </label>

          <ValidatedInput
            label="Remote Base URL"
            value={formState.remote.baseUrl}
            onChange={(event) =>
              setFormState((current) => ({
                ...current,
                remote: { ...current.remote, baseUrl: event.target.value },
              }))
            }
            placeholder="https://api.example.com/v1"
            validationStatus={validation.remoteBaseUrl}
            errorMessage={validation.remoteBaseUrlError}
            helperText="Endpoint for the external OpenAI-compatible provider."
            disabled={isBusy}
          />

          <div className="md:col-span-2">
            <label className="mb-2 block text-xs font-mono text-term-text-muted">
              Default Remote Model
            </label>
            <ModelSelector
              value={formState.remote.defaultModel}
              onChange={(value) =>
                setFormState((current) => ({
                  ...current,
                  remote: { ...current.remote, defaultModel: value },
                }))
              }
              options={DEFAULT_MODEL_OPTIONS}
              placeholder="Select or enter a remote model"
              disabled={isBusy}
            />
            <p className="mt-1.5 text-xs font-mono text-term-text-muted">
              Used when a task route points to Remote and leaves its model blank.
            </p>
          </div>
        </div>

        <div className="mt-6 border-t border-term-border-subtle pt-6">
          <div className="mb-5">
            <div className="flex items-center gap-2">
              <h4 className="text-sm font-mono font-semibold text-term-text">Remote API Key</h4>
              <HelpIcon tooltip="Stored separately and only used for the Remote provider." />
            </div>
            <p className="mt-1.5 text-xs font-mono leading-6 text-term-text-muted">
              {status.providers.remote.hasApiKey
                ? 'A Remote API key is already stored.'
                : 'Required for any task route that uses the Remote provider.'}
            </p>
          </div>

          <div className="relative">
            <ValidatedInput
              label={status.providers.remote.hasApiKey ? 'Update API Key' : 'API Key'}
              type={showApiKey ? 'text' : 'password'}
              value={formState.remoteApiKey}
              onChange={(event) =>
                setFormState((current) => ({ ...current, remoteApiKey: event.target.value }))
              }
              placeholder="Enter your API key"
              validationStatus={validation.apiKey}
              helperText="Only the Remote provider uses an API key."
              disabled={isBusy}
              className="pr-20"
            />
            <button
              type="button"
              onClick={() => setShowApiKey((current) => !current)}
              className="absolute right-3 top-[2.1rem] text-term-text-tertiary transition-colors hover:text-info focus:outline-none focus:ring-2 focus:ring-info focus:ring-offset-2 focus:ring-offset-term-surface"
              aria-label={showApiKey ? 'Hide API key' : 'Show API key'}
              aria-pressed={showApiKey}
            >
              {showApiKey ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
            </button>
          </div>

          <div className="mt-4 flex flex-wrap justify-between gap-3">
            <div>
              {status.providers.remote.hasApiKey && (
                <button
                  type="button"
                  onClick={() => {
                    if (dontAskAgain) {
                      void handleClearRemoteApiKey();
                    } else {
                      setShowClearConfirm(true);
                    }
                  }}
                  disabled={isBusy}
                  className="flex items-center gap-2 rounded border border-[var(--term-status-error-border)] bg-[var(--term-status-error)] px-4 py-2 text-xs font-mono text-negative transition-colors hover:border-negative hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  <XCircle className="h-3.5 w-3.5" />
                  Clear Key
                </button>
              )}
            </div>
            <button
              type="button"
              onClick={handleSaveRemoteApiKey}
              disabled={isBusy || !formState.remoteApiKey.trim()}
              className="rounded border border-info bg-[var(--term-status-info)] px-4 py-2 text-xs font-mono text-info transition-colors hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {isBusy ? 'Saving...' : status.providers.remote.hasApiKey ? 'Update API Key' : 'Save API Key'}
            </button>
          </div>
        </div>
      </section>

      <section className="rounded-lg bg-term-surface p-6 shadow-sm">
        <div className="mb-6">
          <div className="flex items-center gap-2">
            <h3 className="text-base font-mono font-semibold text-term-text">Local Provider</h3>
            <HelpIcon tooltip="Configure the local Ollama provider using its OpenAI-compatible API." />
          </div>
          <p className="mt-1.5 text-xs font-mono leading-6 text-term-text-muted">
            Local (Ollama) uses `http://localhost:11434/v1` by default and does not need an API key.
          </p>
        </div>

        <div className="mb-6 rounded-lg border border-term-border-subtle bg-term-bg px-4 py-4">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div>
              <h4 className="text-sm font-mono font-semibold text-term-text">How to add a local model</h4>
              <p className="mt-1.5 text-xs font-mono leading-6 text-term-text-muted">
                1. Run `ollama pull llama3.2` or another Ollama tag in your terminal.
              </p>
              <p className="text-xs font-mono leading-6 text-term-text-muted">
                2. Enter the exact model name below, like `llama3.2`, `qwen3-coder`, or `deepseek-r1:14b`.
              </p>
              <p className="text-xs font-mono leading-6 text-term-text-muted">
                3. Save settings, then switch task routing to Local if you want Ollama used everywhere.
              </p>
            </div>
            <button
              type="button"
              onClick={() => applyProviderToAllTasks('ollama')}
              disabled={isBusy}
              className="rounded border border-info bg-[var(--term-status-info)] px-4 py-2 text-xs font-mono text-info transition-colors hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
            >
              Route All Tasks To Local
            </button>
          </div>
        </div>

        <div className="grid gap-5 md:grid-cols-2">
          <label className="flex items-center gap-2 text-xs font-mono text-term-text">
            <input
              type="checkbox"
              checked={formState.ollama.enabled}
              onChange={(event) =>
                setFormState((current) => ({
                  ...current,
                  ollama: { ...current.ollama, enabled: event.target.checked },
                }))
              }
              className="h-4 w-4 rounded border-term-border bg-term-bg text-info focus:ring-2 focus:ring-info focus:ring-offset-2 focus:ring-offset-term-surface"
            />
            Enabled
          </label>

          <ValidatedInput
            label="Local Base URL"
            value={formState.ollama.baseUrl}
            onChange={(event) =>
              setFormState((current) => ({
                ...current,
                ollama: { ...current.ollama, baseUrl: event.target.value },
              }))
            }
            placeholder={OLLAMA_DEFAULT_BASE_URL}
            validationStatus={validation.ollamaBaseUrl}
            errorMessage={validation.ollamaBaseUrlError}
            helperText="Endpoint for the local Ollama OpenAI-compatible API."
            disabled={isBusy}
          />

          <div className="md:col-span-2">
            <label className="mb-2 block text-xs font-mono text-term-text-muted">
              Default Local Model / Ollama Tag
            </label>
            <ModelSelector
              value={formState.ollama.defaultModel}
              onChange={(value) =>
                setFormState((current) => ({
                  ...current,
                  ollama: { ...current.ollama, defaultModel: value },
                }))
              }
              options={OLLAMA_MODEL_OPTIONS}
              placeholder="Type the exact Ollama model tag or choose a preset"
              disabled={isBusy}
            />
            <p className="mt-1.5 text-xs font-mono text-term-text-muted">
              Used when a task route points to Local (Ollama) and leaves its model blank.
            </p>
            <div className="mt-3 flex flex-wrap gap-2">
              {OLLAMA_EXAMPLE_MODELS.map((model) => (
                <button
                  key={model}
                  type="button"
                  onClick={() =>
                    setFormState((current) => ({
                      ...current,
                      ollama: { ...current.ollama, defaultModel: model },
                    }))
                  }
                  disabled={isBusy}
                  className={`rounded border px-2.5 py-1 text-xs font-mono transition-colors ${
                    formState.ollama.defaultModel === model
                      ? 'border-info bg-[var(--term-status-info)] text-info'
                      : 'border-term-border bg-term-bg text-term-text-muted hover:border-term-border-focus hover:text-term-text'
                  } disabled:cursor-not-allowed disabled:opacity-50`}
                >
                  {model}
                </button>
              ))}
            </div>
          </div>
        </div>
      </section>

      <section className="rounded-lg bg-term-surface p-6 shadow-sm">
        <div className="mb-6">
          <div className="flex items-center gap-2">
            <h3 className="text-base font-mono font-semibold text-term-text">Task Routing</h3>
            <HelpIcon tooltip="Choose which provider and model each AI flow should use." />
          </div>
          <p className="mt-1.5 text-xs font-mono leading-6 text-term-text-muted">
            Each flow can independently use Remote or Local (Ollama). Leave a route model blank to inherit the selected provider default model.
          </p>
        </div>

        <div className="mb-6 flex flex-wrap items-center gap-3 rounded-lg border border-term-border-subtle bg-term-bg px-4 py-3">
          <span className="text-xs font-mono text-term-text-muted">Quick apply:</span>
          <button
            type="button"
            onClick={() => applyProviderToAllTasks('remote')}
            disabled={isBusy}
            className="rounded border border-term-border bg-term-surface px-3 py-1.5 text-xs font-mono text-term-text transition-colors hover:border-term-border-focus disabled:cursor-not-allowed disabled:opacity-50"
          >
            All Remote
          </button>
          <button
            type="button"
            onClick={() => applyProviderToAllTasks('ollama')}
            disabled={isBusy}
            className="rounded border border-info bg-[var(--term-status-info)] px-3 py-1.5 text-xs font-mono text-info transition-colors hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
          >
            All Local
          </button>
          <span className="text-xs font-mono text-term-text-muted">
            Clears per-task model overrides and makes every flow inherit the chosen provider default.
          </span>
        </div>

        <div className="space-y-4">
          {TASK_PROFILES.map((task) => {
            const route = formState.taskDefaults[task];
            const selectedProviderOptions = PROVIDER_MODEL_OPTIONS[route.provider];
            const inheritedModel = providerDefaultModel(formState, route.provider);

            return (
              <div
                key={task}
                className="rounded-lg border border-term-border-subtle bg-term-bg p-4 transition-colors hover:border-term-border"
              >
                <div className="grid gap-4 md:grid-cols-[180px_180px_minmax(0,1fr)]">
                  <div className="text-sm font-mono text-term-text">{TASK_LABELS[task]}</div>

                  <label className="block">
                    <span className="mb-2 block text-xs font-mono text-term-text-muted">Provider</span>
                    <select
                      value={route.provider}
                      onChange={(event) =>
                        setTaskRoute(task, {
                          provider: event.target.value as AgentProviderKind,
                        })
                      }
                      disabled={isBusy}
                      className="w-full border border-term-border bg-term-surface px-3 py-2 text-sm font-mono text-term-text outline-none transition-all hover:border-term-border-focus focus:border-info disabled:cursor-not-allowed disabled:opacity-50 border-l-2 focus:border-l-info hover:border-l-term-border-focus"
                    >
                      <option value="remote">{AGENT_PROVIDER_LABELS.remote}</option>
                      <option value="ollama">{AGENT_PROVIDER_LABELS.ollama}</option>
                    </select>
                  </label>

                  <div>
                    <label className="mb-2 block text-xs font-mono text-term-text-muted">
                      Model
                    </label>
                    <ModelSelector
                      id={`model-${task}`}
                      value={route.model}
                      onChange={(value) => setTaskRoute(task, { model: value })}
                      options={selectedProviderOptions}
                      placeholder={inheritedModel || 'Use provider default model'}
                      disabled={isBusy}
                    />
                    <p className="mt-1.5 text-xs font-mono text-term-text-muted">
                      {route.model.trim()
                        ? `Using ${AGENT_PROVIDER_LABELS[route.provider]} model override.`
                        : inheritedModel
                          ? `Inherits ${AGENT_PROVIDER_LABELS[route.provider]} default: ${inheritedModel}`
                          : `Set a model here or define a default for ${AGENT_PROVIDER_LABELS[route.provider]}.`}
                    </p>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <div className="mt-6 flex justify-end gap-3">
          {hasUnsavedChanges && (
            <button
              type="button"
              onClick={() => {
                if (initialState) {
                  setFormState({ ...initialState, remoteApiKey: formState.remoteApiKey });
                }
              }}
              className="rounded border border-term-border bg-term-highlight px-4 py-2 text-xs font-mono text-term-text-muted transition-colors hover:border-term-border-focus hover:text-term-text"
              disabled={isBusy}
            >
              Discard Changes
            </button>
          )}
          <button
            ref={saveButtonRef}
            type="button"
            onClick={handleSaveRuntime}
            disabled={isBusy || !hasUnsavedChanges || !isFormValid}
            className="flex items-center gap-2 rounded border border-info bg-[var(--term-status-info)] px-4 py-2 text-xs font-mono text-info transition-colors hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
            aria-describedby="save-hint"
          >
            {isBusy ? (
              <>
                <Loader2 className="h-3.5 w-3.5 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Save className="h-3.5 w-3.5" />
                Save Settings
              </>
            )}
          </button>
          <span id="save-hint" className="sr-only">
            Save your configuration changes
          </span>
        </div>
      </section>

      {success && (
        <div
          className="flex items-center gap-3 rounded-lg border border-[var(--term-status-success-border)] bg-[var(--term-status-success)] px-4 py-3 text-sm font-mono text-positive"
          role="alert"
          aria-live="polite"
        >
          <CheckCircle className="h-5 w-5" aria-hidden="true" />
          <div className="flex-1">{success}</div>
          <button
            type="button"
            onClick={() => setSuccess(null)}
            className="text-positive opacity-60 transition-opacity hover:opacity-100"
            aria-label="Dismiss success message"
          >
            <XCircle className="h-4 w-4" />
          </button>
        </div>
      )}

      {error && (
        <div
          className="flex items-center gap-3 rounded-lg border border-[var(--term-status-error-border)] bg-[var(--term-status-error)] px-4 py-3 text-sm font-mono text-negative"
          role="alert"
          aria-live="assertive"
        >
          <XCircle className="h-5 w-5" aria-hidden="true" />
          <div className="flex-1">{error}</div>
          <button
            type="button"
            onClick={() => setError(null)}
            className="text-negative opacity-60 transition-opacity hover:opacity-100"
            aria-label="Dismiss error message"
          >
            <XCircle className="h-4 w-4" />
          </button>
        </div>
      )}

      <ConfirmDialog
        isOpen={showClearConfirm}
        title="Clear Remote API key?"
        message="This removes the stored Remote API key. Any flows routed to Remote will stop working until a new key is saved."
        confirmLabel="Clear Key"
        cancelLabel="Cancel"
        variant="danger"
        onConfirm={() => {
          void handleClearRemoteApiKey();
        }}
        onCancel={() => setShowClearConfirm(false)}
        showDontAskAgain
        onDontAskAgainChange={setDontAskAgain}
      />
    </div>
  );
};
