import React, { useEffect, useMemo, useState } from 'react';
import { CheckCircle, Globe, Loader2, Save, XCircle } from 'lucide-react';
import { agentSettingsBridge } from '../../lib/agentSettingsBridge';
import { AgentConfigStatus } from '../../types/agentSettings';
import { ValidatedInput, ValidationStatus } from './ValidatedInput';
import { HelpIcon } from './Tooltip';

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

const validateSecEdgarUserAgent = (
  value: string,
): { valid: boolean; error?: string } => {
  const trimmed = value.trim();
  if (!trimmed) {
    return { valid: true };
  }

  if (!trimmed.includes(' ') || !trimmed.includes('@')) {
    return {
      valid: false,
      error: 'Use a format like `MosaicIQ admin@example.com`',
    };
  }

  return { valid: true };
};

export const SecEdgarSettingsCard: React.FC<SecEdgarSettingsCardProps> = ({
  status,
  onStatusChange,
}) => {
  const [value, setValue] = useState('');
  const [initialValue, setInitialValue] = useState('');
  const [validation, setValidation] = useState<{
    status: ValidationStatus;
    error?: string;
  }>({
    status: 'idle',
  });
  const [isBusy, setIsBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

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

    setValue(status.secEdgarUserAgent);
    setInitialValue(status.secEdgarUserAgent);
    setValidation({ status: 'idle' });
    setError(null);
    setSuccess(null);
  }, [status]);

  useEffect(() => {
    if (!value.trim()) {
      setValidation({ status: 'idle' });
      return;
    }

    const result = validateSecEdgarUserAgent(value);
    setValidation({
      status: result.valid ? 'valid' : 'invalid',
      error: result.error,
    });
  }, [value]);

  const hasChanges = value !== initialValue;
  const isValid = validation.status === 'valid' || validation.status === 'idle';

  const helperText = useMemo(() => {
    if (status?.hasSecEdgarUserAgent) {
      return 'Stored in app settings and used before env fallback.';
    }
    return 'Leave blank to fall back to the `SEC_EDGAR_USER_AGENT` environment variable.';
  }, [status]);

  const handleSave = async () => {
    if (!status || !isValid) {
      return;
    }

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

    try {
      const nextStatus = await agentSettingsBridge.saveRuntimeConfig({
        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: status.taskDefaults,
        secEdgarUserAgent: value,
      });
      onStatusChange(nextStatus);
      setInitialValue(value);
      setSuccess('SEC EDGAR setting saved successfully');
    } catch (saveError) {
      setError(
        saveError instanceof Error
          ? saveError.message
          : 'Failed to save SEC EDGAR setting.',
      );
    } finally {
      setIsBusy(false);
    }
  };

  return (
    <section className="rounded-lg bg-term-surface p-6 shadow-sm">
      <div className="mb-6 flex items-start justify-between gap-4">
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <h2 className="text-base font-mono font-semibold text-term-text">
              SEC EDGAR
            </h2>
            <HelpIcon tooltip="Identity string sent with SEC EDGAR requests. The SEC asks automated clients to provide a descriptive product name and contact email." />
          </div>
          <p className="mt-1.5 text-xs font-mono leading-6 text-term-text-muted">
            Configure how MosaicIQ identifies itself when calling SEC EDGAR.
          </p>
        </div>
        <div className="rounded border border-term-border bg-term-bg px-3 py-2 text-right">
          <div className="flex items-center gap-2 text-[11px] font-mono text-term-text-muted">
            <Globe className="h-3.5 w-3.5" />
            <span>{status?.hasSecEdgarUserAgent ? 'Stored in app' : 'Env fallback / unset'}</span>
          </div>
        </div>
      </div>

      <ValidatedInput
        label="SEC EDGAR User Agent"
        value={value}
        onChange={(event) => setValue(event.target.value)}
        placeholder="MosaicIQ admin@example.com"
        validationStatus={validation.status}
        errorMessage={validation.error}
        helperText={helperText}
        disabled={isBusy}
      />

      <div className="mt-5 flex justify-end gap-3">
        {hasChanges && (
          <button
            type="button"
            onClick={() => setValue(initialValue)}
            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
          type="button"
          onClick={handleSave}
          disabled={isBusy || !hasChanges || !isValid || !status}
          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"
        >
          {isBusy ? (
            <>
              <Loader2 className="h-3.5 w-3.5 animate-spin" />
              Saving...
            </>
          ) : (
            <>
              <Save className="h-3.5 w-3.5" />
              Save SEC Setting
            </>
          )}
        </button>
      </div>

      {success && (
        <div className="mt-4 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">
          <CheckCircle className="h-5 w-5" />
          <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="mt-4 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">
          <XCircle className="h-5 w-5" />
          <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>
      )}
    </section>
  );
};
