import React from 'react';
import { 
  Cpu, Key, Shield, Save, Loader2, ExternalLink, 
  AlertCircle, ChevronDown, Info, MousePointer2, Zap, CheckCircle2
} from 'lucide-react';
import { GhostButton, ModernCardHeader, SettingInput } from "../ui/settings-ui";
import { Badge } from "../ui/badge";
import { Switch } from "../ui/switch";
import { cn } from "@/lib/utils";
import { motion } from 'framer-motion';

import type { WawpDashboardData } from '../../types';

interface AIProvider {
  id: string;
  name: string;
  description: string;
  logo: string; 
  models: string[];
  link: string;
}

export default function AISettings({ data, onBack }: { data: WawpDashboardData; onBack: () => void }) {
  const [settings, setSettings] = React.useState<Record<string, string | boolean | undefined>>({
    freeModeEnabled: true
  });
  const [isSaving, setIsSaving] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(true);
  const [status, setStatus] = React.useState<'idle' | 'success' | 'error'>('idle');
  const [isTesting, setIsTesting] = React.useState<Record<string, boolean>>({});
  const [testResults, setTestResults] = React.useState<Record<string, { success: boolean; message: string } | null>>({});

  const assetsUrl = `${data.global.pluginUrl}assets/icons/ai/`;

  const PROVIDERS: AIProvider[] = [
    {
      id: 'openai',
      name: 'OpenAI',
      description: 'Leader in Agentic AI and self-managing workflows with GPT-5.5.',
      logo: `${assetsUrl}openai.svg`,
      models: ['gpt-5.5-preview', 'gpt-5.4-turbo', 'gpt-4o', 'o1-preview'],
      link: 'https://platform.openai.com/'
    },
    {
      id: 'anthropic',
      name: 'Anthropic',
      description: 'Expert coding with Claude 4.7 and advanced Effort Control logic.',
      logo: `${assetsUrl}anthropic.svg`,
      models: ['claude-4-7-opus', 'claude-4-6-sonnet', 'claude-3-5-sonnet-latest'],
      link: 'https://console.anthropic.com/'
    },
    {
      id: 'google',
      name: 'Google DeepMind',
      description: 'Massive 2M context and Personal Intelligence with Gemini 3.5.',
      logo: `${assetsUrl}google.svg`,
      models: ['gemini-3-5-flash', 'gemini-3-1-pro', 'gemini-1.5-pro'],
      link: 'https://aistudio.google.com/'
    },
    {
      id: 'groq',
      name: 'Groq (LPU Speed)',
      description: 'The world\'s fastest inference for Llama 4 and DeepSeek V4.',
      logo: `${assetsUrl}groq.svg`,
      models: ['llama-4-70b-fast', 'deepseek-v4-instant', 'llama-3.1-70b-versatile'],
      link: 'https://console.groq.com/'
    },
    {
      id: 'deepseek',
      name: 'DeepSeek',
      description: 'Open-weight V4 Pro with Extended Thinking Mode at record low cost.',
      logo: `${assetsUrl}deepseek.svg`,
      models: ['deepseek-v4-pro', 'deepseek-v4-flash', 'deepseek-chat'],
      link: 'https://platform.deepseek.com/'
    }
  ];

  const RECOMMENDED_MODELS = [
    { provider: 'openai', model: 'gpt-5.5-preview', label: 'Agentic Standard', color: 'blue' },
    { provider: 'groq', model: 'llama-4-70b-fast', label: 'LPU Lightning Speed', color: 'emerald' },
    { provider: 'anthropic', model: 'claude-4-7-opus', label: 'High Effort Reasoning', color: 'orange' },
  ];

  React.useEffect(() => {
    const fetchSettings = async () => {
      try {
        const response = await fetch(`${data.global.restUrl}/ai-assistant/settings`, {
          headers: { 'X-WP-Nonce': data.global.wpRestNonce }
        });
        const res = await response.json();
        if (res.success && res.data) {
          setSettings(prev => ({
            ...prev,
            ...res.data,
            freeModeEnabled: res.data.freeModeEnabled !== undefined ? Boolean(res.data.freeModeEnabled) : true
          }));
        }
      } catch (err) {
        console.error("Failed to fetch AI settings", err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchSettings();
  }, [data.global.restUrl, data.global.wpRestNonce]);

  const handleSave = async (overrideSettings?: Record<string, string | boolean | undefined>) => {
    const dataToSave = overrideSettings || settings;
    setIsSaving(true);
    try {
      const response = await fetch(`${data.global.restUrl}/ai-assistant/settings`, {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'X-WP-Nonce': data.global.wpRestNonce 
        },
        body: JSON.stringify(dataToSave)
      });
      const res = await response.json();
      if (res.success) {
        setStatus('success');
        setTimeout(() => setStatus('idle'), 3000);
      } else {
        throw new Error(res.message);
      }
    } catch (e: unknown) {
      console.error("Failed to save AI settings", e);
      setStatus('error');
    } finally {
      setIsSaving(false);
    }
  };

  const quickSetup = (providerId: string, modelName: string) => {
    const next = { 
      ...settings, 
      [`${providerId}_enabled`]: true, 
      [`${providerId}_model`]: modelName 
    };
    setSettings(next);
    handleSave(next);
  };

  const handleTestConnection = async (providerId: string) => {
    setIsTesting(prev => ({ ...prev, [providerId]: true }));
    setTestResults(prev => ({ ...prev, [providerId]: null }));
    const kVal = settings[`${providerId}_key`];
    const mVal = settings[`${providerId}_model`] || PROVIDERS.find(p => p.id === providerId)?.models[0];
    try {
      const response = await fetch(`${data.global.restUrl}/ai-assistant/chat-proxy`, {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'X-WP-Nonce': data.global.wpRestNonce 
        },
        body: JSON.stringify({
          provider: providerId,
          key: typeof kVal === 'string' ? kVal : '',
          model: typeof mVal === 'string' ? mVal : '',
          messages: [{ role: 'user', content: 'Ping' }]
        })
      });
      const res = await response.json();
      if (res.success) {
        setTestResults(prev => ({ ...prev, [providerId]: { success: true, message: 'Connection successful!' } }));
      } else {
        setTestResults(prev => ({ ...prev, [providerId]: { success: false, message: res.message || 'Connection failed' } }));
      }
    } catch (e: unknown) {
      const message = e instanceof Error ? e.message : 'Connection failed';
      setTestResults(prev => ({ ...prev, [providerId]: { success: false, message } }));
    } finally {
      setIsTesting(prev => ({ ...prev, [providerId]: false }));
    }
  };

  const isUsingAnyPaid = PROVIDERS.some(p => settings[`${p.id}_enabled`] && settings[`${p.id}_key`]);

  if (isLoading) {
    return (
      <div className="flex flex-col h-full items-center justify-center bg-white">
        <Loader2 className="w-8 h-8 animate-spin text-emerald-500" />
        <p className="text-xs text-slate-400 mt-4 uppercase tracking-widest font-bold">Initializing AI Center...</p>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full bg-white">
      <ModernCardHeader 
        title="AI Settings Center" 
        description="Integrate next-generation AI agents and high-performance models."
        icon={Cpu}
        className="!border-none !bg-white !px-8"
        rightAction={
          <GhostButton onClick={onBack} size="sm" className="text-slate-400 hover:text-emerald-600 font-bold uppercase tracking-widest text-[10px]">
            Exit to Chat
          </GhostButton>
        }
      />

      <div className="flex-1 overflow-y-auto custom-scrollbar">
        <div className="max-w-full mx-auto space-y-8 p-8">
          
          {/* Free Mode Active Alert */}
          {!isUsingAnyPaid && (
            <div className="bg-amber-50/50 border border-amber-100 rounded-2xl overflow-hidden shadow-none">
              <ModernCardHeader 
                title={
                  <div className="flex items-center gap-2">
                    Legacy Free Mode Active
                    <Badge variant="outline" className="bg-amber-100 text-amber-700 border-amber-200 text-[8px] h-4 font-black">LIMITED</Badge>
                  </div>
                }
                description="You are currently using shared resources. For GPT-5.5 performance and extended reasoning, connect a premium provider."
                icon={() => (
                  <div className="w-8 h-8 rounded-lg bg-white border border-amber-100 flex items-center justify-center shadow-sm">
                    <Info className="w-4 h-4 text-amber-500" />
                  </div>
                )}
                className="!bg-transparent !border-none !py-5"
                rightAction={
                  <div className="flex flex-col items-center gap-1">
                    <span className="text-[8px] font-black text-amber-600/50 uppercase tracking-widest">FREE MODE</span>
                    <Switch 
                      checked={Boolean(settings.freeModeEnabled)} 
                      onCheckedChange={(val) => {
                        const next = { ...settings, freeModeEnabled: val };
                        setSettings(next);
                        handleSave(next);
                      }}
                    />
                  </div>
                }
              />
              <div className="px-6 pb-6 pt-0">
                <div className="flex flex-wrap gap-3">
                   {RECOMMENDED_MODELS.map(m => (
                     <button
                       key={m.model}
                       onClick={() => quickSetup(m.provider, m.model)}
                       className={cn(
                         "flex items-center gap-2 px-3 py-1.5 rounded-lg border text-[11px] font-bold transition-all active:scale-95 shadow-sm bg-white",
                         m.color === 'blue' ? "border-blue-100 text-blue-600 hover:bg-blue-50" :
                         m.color === 'emerald' ? "border-emerald-100 text-emerald-600 hover:bg-emerald-50" :
                         "border-orange-100 text-orange-600 hover:bg-orange-50"
                       )}
                     >
                       <MousePointer2 className="w-3 h-3" />
                       Quick Set: {m.label}
                     </button>
                   ))}
                </div>
              </div>
            </div>
          )}

          <div className="space-y-6">
            <div className="flex items-center justify-between px-1">
              <h3 className="text-[10px] font-black text-slate-300 uppercase tracking-[0.3em]">AI INFRASTRUCTURE</h3>
              <Badge variant="outline" className="bg-slate-50 text-slate-400 border-slate-100 text-[9px] px-2 font-bold">
                {PROVIDERS.length} ELITE PROVIDERS
              </Badge>
            </div>
            
            <div className="grid gap-6">
              {PROVIDERS.map(provider => (
                <div 
                  key={provider.id}
                  className={cn(
                    "rounded-2xl transition-all bg-white relative overflow-hidden border border-slate-100/80 shadow-none",
                    settings[`${provider.id}_enabled`] ? "opacity-100 ring-4 ring-[#004449]/[0.01]" : "opacity-60 bg-slate-50/30"
                  )}
                >
                  <ModernCardHeader 
                    title={provider.name}
                    description={provider.description}
                    icon={() => (
                      <div className={cn(
                        "w-8 h-8 rounded-lg flex items-center justify-center transition-all bg-white border",
                        settings[`${provider.id}_enabled`] ? "border-emerald-100 shadow-sm" : "border-slate-50"
                      )}>
                        <img src={provider.logo} className="w-4 h-4 object-contain grayscale-[0.5] group-hover:grayscale-0" alt={provider.name} />
                      </div>
                    )}
                    className="!bg-transparent !border-slate-50/50 !py-5"
                    rightAction={
                      <div className="flex items-center gap-4">
                        <Switch 
                          checked={Boolean(settings[`${provider.id}_enabled`])}
                          onCheckedChange={(val) => {
                            setSettings({ ...settings, [`${provider.id}_enabled`]: val });
                          }}
                        />
                        <a href={provider.link} target="_blank" rel="noreferrer" className="w-8 h-8 rounded-lg flex items-center justify-center text-slate-200 hover:text-emerald-500 hover:bg-emerald-50 transition-all border border-transparent hover:border-emerald-100">
                          <ExternalLink className="w-3.5 h-3.5" />
                        </a>
                      </div>
                    }
                  />

                  {settings[`${provider.id}_enabled`] && (
                    <motion.div 
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: 'auto', opacity: 1 }}
                      className="p-6 pt-2 grid grid-cols-1 md:grid-cols-2 gap-6"
                    >
                      {(() => {
                        const kVal = settings[`${provider.id}_key`];
                        return (
                          <SettingInput 
                            label="API Key"
                            type="password"
                            placeholder={`Enter ${provider.name} Key...`}
                            icon={Key}
                            value={typeof kVal === 'string' ? kVal : ''}
                            onChange={(val) => {
                              setSettings({ ...settings, [`${provider.id}_key`]: val });
                            }}
                            className="!bg-transparent"
                          />
                        );
                      })()}

                      <div className="space-y-1.5">
                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5 px-1">
                          <Cpu className="w-3 h-3 opacity-50" /> Preferred Model
                        </label>
                        <div className="relative group/sel">
                          {(() => {
                            const mVal = settings[`${provider.id}_model`];
                            return (
                              <select 
                                className="w-full h-10 bg-slate-50/50 border border-slate-100 rounded-lg px-4 text-[13px] font-bold focus:ring-0 focus:border-emerald-500/50 transition-all appearance-none cursor-pointer text-slate-600 pr-10"
                                value={typeof mVal === 'string' ? mVal : provider.models[0]}
                                onChange={(e) => {
                                  setSettings({ ...settings, [`${provider.id}_model`]: e.target.value });
                                }}
                              >
                                {provider.models.map(m => (
                                  <option key={m} value={m}>{m}</option>
                                ))}
                              </select>
                            );
                          })()}
                          <div className="absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-300">
                            <ChevronDown className="w-4 h-4" strokeWidth={3} />
                          </div>
                        </div>
                      </div>

                      <div className="col-span-1 md:col-span-2 flex flex-col md:flex-row items-start md:items-center justify-between bg-slate-50/50 border border-slate-100/60 p-4 rounded-xl gap-4">
                        <div className="flex flex-col gap-1">
                          <span className="text-[11px] font-bold text-slate-500">
                            Test connection with the provided credentials.
                          </span>
                          {testResults[provider.id] && (
                            <span className={cn(
                              "text-[11px] font-bold mt-1 flex items-center gap-1.5",
                              testResults[provider.id]?.success ? "text-emerald-600" : "text-rose-500"
                            )}>
                              {testResults[provider.id]?.success ? <CheckCircle2 className="w-3.5 h-3.5" /> : <AlertCircle className="w-3.5 h-3.5" />}
                              {testResults[provider.id]?.message}
                            </span>
                          )}
                        </div>
                        <button
                          onClick={() => handleTestConnection(provider.id)}
                          disabled={isTesting[provider.id]}
                          className="h-9 px-4 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-[10px] uppercase tracking-widest rounded-lg flex items-center gap-2 transition-all active:scale-95 shadow-sm shadow-emerald-600/10 disabled:opacity-50 shrink-0"
                        >
                          {isTesting[provider.id] ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Zap className="w-3.5 h-3.5" />}
                          Test Connection
                        </button>
                      </div>
                    </motion.div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Security Protocol Section */}
          <div className="bg-slate-50/20 border border-slate-100 rounded-2xl overflow-hidden shadow-none">
            <ModernCardHeader 
              title="AI Security Protocol"
              description="Standard encryption at rest. Keys never leave your WordPress environment. 100% direct server-to-provider communication."
              icon={() => (
                <div className="w-8 h-8 rounded-lg bg-white border border-slate-100 flex items-center justify-center shadow-sm">
                  <Shield className="w-4 h-4 text-emerald-600" />
                </div>
              )}
              className="!bg-transparent !border-none !py-5"
            />
          </div>
        </div>
      </div>

      <div className="p-8 bg-white border-t border-slate-50 flex items-center justify-between">
        <div className="flex items-center gap-3">
          {status === 'success' && (
            <motion.div initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} className="flex items-center gap-2 text-emerald-600 text-[10px] font-black uppercase tracking-[0.2em]">
              <div className="w-1.5 h-1.5 bg-emerald-500 rounded-full" />
              Engine Synced
            </motion.div>
          )}
          {status === 'error' && (
            <motion.div initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} className="flex items-center gap-2 text-rose-500 text-[10px] font-black uppercase tracking-[0.2em]">
              <AlertCircle className="w-4 h-4" /> Sync Failure
            </motion.div>
          )}
        </div>
        <div className="flex gap-4">
           <GhostButton onClick={onBack} className="font-bold text-[11px] uppercase tracking-widest px-6">Cancel</GhostButton>
           <button
            onClick={() => handleSave()}
            disabled={isSaving}
            className="h-11 px-10 bg-[#004449] text-white rounded-xl font-bold text-[13px] hover:bg-[#003337] transition-all flex items-center gap-2 shadow-lg shadow-[#004449]/10 disabled:opacity-50 active:scale-95 uppercase tracking-widest"
          >
            {isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            Save Configuration
          </button>
        </div>
      </div>
    </div>
  );
}
