'use client';

import { useState, useEffect, useCallback } from 'react';
import { clsx } from 'clsx';
import { Loader2, CheckCircle, XCircle } from 'lucide-react';
import { loadAIConfig, saveAIConfig, PROVIDER_DEFAULTS } from '@/lib/ai-config';
import type { AIConfig } from '@/lib/ai-config';

type TestStatus = 'idle' | 'testing' | 'success' | 'error';

export function AIConfigPanel() {
  const [config, setConfig] = useState<AIConfig>(loadAIConfig);
  const [testStatus, setTestStatus] = useState<TestStatus>('idle');
  const [testError, setTestError] = useState('');
  const [saved, setSaved] = useState(false);

  // Reload config from localStorage on mount
  useEffect(() => {
    setConfig(loadAIConfig());
  }, []);

  const updateProvider = useCallback((provider: AIConfig['provider']) => {
    const defaults = PROVIDER_DEFAULTS[provider];
    setConfig(prev => ({
      ...prev,
      provider,
      model: defaults.model,
      baseUrl: defaults.baseUrl,
    }));
    setSaved(false);
  }, []);

  const updateField = useCallback(<K extends keyof AIConfig>(key: K, value: AIConfig[K]) => {
    setConfig(prev => ({ ...prev, [key]: value }));
    setSaved(false);
  }, []);

  const toggleFeature = useCallback((feature: keyof AIConfig['features']) => {
    setConfig(prev => ({
      ...prev,
      features: { ...prev.features, [feature]: !prev.features[feature] },
    }));
    setSaved(false);
  }, []);

  const handleSave = useCallback(() => {
    saveAIConfig(config);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }, [config]);

  const handleTest = useCallback(async () => {
    setTestStatus('testing');
    setTestError('');
    try {
      const res = await fetch('/api/ai/invoke', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-KnowHub-AI-Provider': config.provider,
          'X-KnowHub-AI-Key': config.apiKey,
          'X-KnowHub-AI-Model': config.model,
          'X-KnowHub-AI-BaseURL': config.baseUrl,
        },
        body: JSON.stringify({ action: 'test', payload: {} }),
      });
      const data = await res.json();
      if (data.ok) {
        setTestStatus('success');
      } else {
        setTestStatus('error');
        setTestError(data.error || 'Connection failed');
      }
    } catch {
      setTestStatus('error');
      setTestError('Network error');
    }
  }, [config]);

  const features: { key: keyof AIConfig['features']; label: string; description: string }[] = [
    { key: 'smartUpload', label: 'Smart Upload', description: 'Auto-extract metadata when uploading files' },
    { key: 'skillAnalyzer', label: 'Skill Analyzer', description: 'Score and suggest improvements for skill definitions' },
    { key: 'memoryHygiene', label: 'Memory Hygiene', description: 'Detect duplicate and contradicting memories' },
    { key: 'contentClassification', label: 'Content Classification', description: 'Auto-classify content as skill or knowledge' },
    { key: 'stalenessCheck', label: 'Staleness Check', description: 'Detect outdated knowledge documents' },
  ];

  return (
    <div className="space-y-6">
      {/* Provider Selection */}
      <div className="rounded-xl bg-surface border border-border-light p-6">
        <h3 className="text-sm font-semibold text-text-primary uppercase tracking-wide mb-4">
          Provider
        </h3>
        <div className="flex gap-2 mb-4">
          {(['openai', 'anthropic', 'custom'] as const).map((p) => (
            <button
              key={p}
              onClick={() => updateProvider(p)}
              className={clsx(
                'px-4 py-2 rounded-lg text-sm font-medium transition-colors border',
                config.provider === p
                  ? 'bg-accent text-white border-accent'
                  : 'bg-surface-elevated text-text-secondary border-border hover:text-text-primary hover:border-text-muted'
              )}
            >
              {p === 'openai' ? 'OpenAI' : p === 'anthropic' ? 'Anthropic' : 'Custom'}
            </button>
          ))}
        </div>

        {/* API Key */}
        <label className="block mb-4">
          <span className="text-xs font-medium text-text-secondary mb-1.5 block">API Key</span>
          <div className="flex gap-2">
            <input
              type="password"
              value={config.apiKey}
              onChange={(e) => updateField('apiKey', e.target.value)}
              placeholder="sk-..."
              className="flex-1 bg-surface-elevated border border-border rounded-md px-3 py-2 text-text-primary text-sm focus:outline-none focus:border-accent transition-colors font-mono"
            />
            <button
              onClick={handleTest}
              disabled={!config.apiKey || testStatus === 'testing'}
              className={clsx(
                'flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium transition-colors',
                !config.apiKey || testStatus === 'testing'
                  ? 'bg-surface-elevated text-text-muted cursor-not-allowed'
                  : 'bg-surface-elevated border border-border text-text-secondary hover:text-text-primary hover:border-text-muted'
              )}
            >
              {testStatus === 'testing' && <Loader2 size={14} className="animate-spin" />}
              {testStatus === 'success' && <CheckCircle size={14} className="text-success" />}
              {testStatus === 'error' && <XCircle size={14} className="text-error" />}
              Test
            </button>
          </div>
          {testStatus === 'error' && testError && (
            <p className="text-xs text-error mt-1">{testError}</p>
          )}
          {testStatus === 'success' && (
            <p className="text-xs text-success mt-1">Connection successful</p>
          )}
        </label>

        {/* Model */}
        <label className="block mb-4">
          <span className="text-xs font-medium text-text-secondary mb-1.5 block">Model</span>
          <input
            type="text"
            value={config.model}
            onChange={(e) => updateField('model', e.target.value)}
            placeholder="e.g. gpt-4o-mini"
            className="w-full bg-surface-elevated border border-border rounded-md px-3 py-2 text-text-primary text-sm focus:outline-none focus:border-accent transition-colors"
          />
        </label>

        {/* Base URL */}
        <label className="block">
          <span className="text-xs font-medium text-text-secondary mb-1.5 block">Base URL</span>
          <input
            type="text"
            value={config.baseUrl}
            onChange={(e) => updateField('baseUrl', e.target.value)}
            placeholder="https://api.openai.com/v1"
            className="w-full bg-surface-elevated border border-border rounded-md px-3 py-2 text-text-primary text-sm focus:outline-none focus:border-accent transition-colors"
          />
        </label>
      </div>

      {/* Feature Toggles */}
      <div className="rounded-xl bg-surface border border-border-light p-6">
        <h3 className="text-sm font-semibold text-text-primary uppercase tracking-wide mb-4">
          Features
        </h3>
        <div className="space-y-3">
          {features.map((f) => (
            <label key={f.key} className="flex items-center justify-between cursor-pointer">
              <div>
                <p className="text-sm text-text-primary">{f.label}</p>
                <p className="text-xs text-text-muted mt-0.5">{f.description}</p>
              </div>
              <button
                role="switch"
                aria-checked={config.features[f.key]}
                onClick={() => toggleFeature(f.key)}
                className={clsx(
                  'relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors',
                  config.features[f.key] ? 'bg-accent' : 'bg-border'
                )}
              >
                <span
                  className={clsx(
                    'pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-sm transition-transform',
                    config.features[f.key] ? 'translate-x-5' : 'translate-x-0'
                  )}
                />
              </button>
            </label>
          ))}
        </div>
      </div>

      {/* Save */}
      <div className="flex justify-end">
        <button
          onClick={handleSave}
          className={clsx(
            'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
            saved
              ? 'bg-success text-white'
              : 'bg-accent text-white hover:bg-accent-hover'
          )}
        >
          {saved ? 'Saved!' : 'Save Configuration'}
        </button>
      </div>
    </div>
  );
}
