import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Key, Eye, EyeOff, CheckCircle, XCircle, Loader2, ExternalLink,
  Save, ShieldCheck, ChevronDown, AlertTriangle, Users,
} from 'lucide-react';
import { system, characters } from '../api/client';

interface ApiConfig {
  kieApiKey: string;
  geminiApiKey: string;
  openrouterApiKey: string;
}

interface CharacterItem {
  id: string;
  identity: { name: string };
  apiCredentials?: { telegramApiId: number; telegramApiHash: string };
}

interface CharCredentials {
  telegramApiId: string;
  telegramApiHash: string;
}

export default function SettingsAPI() {
  // Global config
  const [config, setConfig] = useState<ApiConfig>({ kieApiKey: '', geminiApiKey: '', openrouterApiKey: '' });
  const [showKeys, setShowKeys] = useState<Record<string, boolean>>({});
  const [savingGlobal, setSavingGlobal] = useState(false);
  const [savedGlobal, setSavedGlobal] = useState(false);
  const [globalError, setGlobalError] = useState<string | null>(null);
  const [testing, setTesting] = useState<Record<string, boolean>>({});
  const [testResults, setTestResults] = useState<Record<string, 'ok' | 'fail' | null>>({});

  // Character-based credentials
  const [charList, setCharList] = useState<CharacterItem[]>([]);
  const [selectedCharId, setSelectedCharId] = useState<string | null>(null);
  const [charDropdownOpen, setCharDropdownOpen] = useState(false);
  const [charCreds, setCharCreds] = useState<CharCredentials>({ telegramApiId: '', telegramApiHash: '' });
  const [loadingChars, setLoadingChars] = useState(true);
  const [loadingCreds, setLoadingCreds] = useState(false);
  const [savingChar, setSavingChar] = useState(false);
  const [savedChar, setSavedChar] = useState(false);
  const [charError, setCharError] = useState<string | null>(null);

  useEffect(() => { loadConfig(); loadCharacters(); }, []);

  async function loadConfig() {
    try {
      const { data } = await system.getApiConfig();
      if (data.success) {
        setConfig({
          kieApiKey: data.data.kieApiKey ?? '',
          geminiApiKey: data.data.geminiApiKey ?? '',
          openrouterApiKey: data.data.openrouterApiKey ?? '',
        });
      }
    } catch {}
  }

  const loadCharacters = useCallback(async () => {
    setLoadingChars(true);
    try {
      const res = await characters.list();
      const data = res.data?.data ?? res.data ?? [];
      const list: CharacterItem[] = (Array.isArray(data) ? data : []).map((c: any) => ({
        id: c.id,
        identity: c.identity ?? { name: c.id },
        apiCredentials: c.apiCredentials ?? undefined,
      }));
      setCharList(list);
      if (list.length > 0 && !selectedCharId) {
        setSelectedCharId(list[0].id);
      }
    } catch {
      setCharList([]);
    } finally {
      setLoadingChars(false);
    }
  }, []);

  const loadCharCredentials = useCallback(async (charId: string) => {
    setLoadingCreds(true);
    setCharError(null);
    try {
      const { data } = await characters.getApiCredentials(charId);
      if (data.success && data.data) {
        setCharCreds({
          telegramApiId: data.data.telegramApiId ? String(data.data.telegramApiId) : '',
          telegramApiHash: data.data.telegramApiHash ?? '',
        });
      } else {
        setCharCreds({ telegramApiId: '', telegramApiHash: '' });
      }
    } catch {
      setCharCreds({ telegramApiId: '', telegramApiHash: '' });
    } finally {
      setLoadingCreds(false);
    }
  }, []);

  useEffect(() => {
    if (selectedCharId) loadCharCredentials(selectedCharId);
  }, [selectedCharId, loadCharCredentials]);

  async function saveGlobalConfig() {
    setSavingGlobal(true);
    setGlobalError(null);
    try {
      await system.updateApiConfig(config as unknown as Record<string, unknown>);
      setSavedGlobal(true);
      setTimeout(() => setSavedGlobal(false), 3000);
    } catch {
      setGlobalError('Global API anahtarları kaydedilemedi.');
    } finally {
      setSavingGlobal(false);
    }
  }

  async function saveCharCredentials() {
    if (!selectedCharId) return;
    setSavingChar(true);
    setCharError(null);
    try {
      await characters.updateApiCredentials(selectedCharId, {
        telegramApiId: Number(charCreds.telegramApiId),
        telegramApiHash: charCreds.telegramApiHash,
      });
      setSavedChar(true);
      setTimeout(() => setSavedChar(false), 3000);
      // Update local charList to reflect new credentials
      setCharList(prev => prev.map(c =>
        c.id === selectedCharId
          ? { ...c, apiCredentials: { telegramApiId: Number(charCreds.telegramApiId), telegramApiHash: charCreds.telegramApiHash } }
          : c
      ));
    } catch {
      setCharError('API credentials kaydedilemedi.');
    } finally {
      setSavingChar(false);
    }
  }

  async function testKey(provider: string) {
    setTesting(t => ({ ...t, [provider]: true }));
    setTestResults(r => ({ ...r, [provider]: null }));
    try {
      const { data } = await system.testApiKey(provider);
      setTestResults(r => ({ ...r, [provider]: data.success ? 'ok' : 'fail' }));
    } catch {
      setTestResults(r => ({ ...r, [provider]: 'fail' }));
    } finally {
      setTesting(t => ({ ...t, [provider]: false }));
    }
  }

  function hasCredentials(char: CharacterItem): boolean {
    return !!(char.apiCredentials?.telegramApiId && char.apiCredentials?.telegramApiHash);
  }

  const selectedChar = charList.find(c => c.id === selectedCharId);
  const selectedCharName = selectedChar?.identity?.name ?? 'Seçiniz';

  const globalFields = [
    {
      id: 'kieApiKey',
      label: 'KIE API Key',
      desc: 'Görsel üretim motoru. nano-banana-2 modeli için gerekli.',
      link: 'https://kie.ai',
      linkText: 'kie.ai',
      provider: 'kie',
      placeholder: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    },
    {
      id: 'geminiApiKey',
      label: 'Gemini API Key (Nano Banana)',
      desc: 'Alternatif görsel üretim motoru. KIE yoksa otomatik devreye girer.',
      link: 'https://geminiapi.codefast.app',
      linkText: 'geminiapi.codefast.app',
      provider: 'gemini',
      placeholder: 'sk-...',
    },
    {
      id: 'openrouterApiKey',
      label: 'OpenRouter API Key',
      desc: 'Sohbet ve konuşma motoru. GPT, Claude, Gemini erişimi.',
      link: 'https://openrouter.ai',
      linkText: 'openrouter.ai',
      provider: 'openrouter',
      placeholder: 'sk-or-v1-...',
    },
  ];

  const charFields = [
    {
      id: 'telegramApiId',
      label: 'Telegram API ID',
      desc: 'Telegram MTProto bağlantısı için gerekli.',
      link: 'https://my.telegram.org',
      linkText: 'my.telegram.org',
      placeholder: '12345678',
    },
    {
      id: 'telegramApiHash',
      label: 'Telegram API Hash',
      desc: 'Telegram MTProto bağlantısı için gerekli. API ID ile birlikte kullanılır.',
      link: 'https://my.telegram.org',
      linkText: 'my.telegram.org',
      placeholder: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    },
  ];

  return (
    <div className="max-w-2xl">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center gap-3 mb-2">
          <div className="w-10 h-10 rounded-xl bg-indigo-500/10 flex items-center justify-center">
            <Key className="w-5 h-5 text-indigo-400" />
          </div>
          <div>
            <h1 className="text-xl font-bold text-white">API Anahtarları</h1>
            <p className="text-[13px] text-slate-500">Global API anahtarları ve karakter bazlı Telegram credentials yönetimi.</p>
          </div>
        </div>
      </div>

      {/* ── Global API Keys Section ── */}
      <div className="mb-10">
        <h2 className="text-[15px] font-semibold text-white mb-4 flex items-center gap-2">
          <ShieldCheck className="w-4 h-4 text-indigo-400" />
          Global API Anahtarları
        </h2>

        <div className="space-y-4">
          {globalFields.map((field, i) => {
            const value = config[field.id as keyof ApiConfig];
            const isVisible = showKeys[field.id];
            const isTestLoading = testing[field.provider];
            const testResult = testResults[field.provider];

            return (
              <motion.div
                key={field.id}
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.08 }}
                className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5"
              >
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-start gap-3">
                    <div className="w-8 h-8 rounded-lg bg-white/[0.04] flex items-center justify-center mt-0.5">
                      <ShieldCheck className="w-4 h-4 text-slate-500" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="text-[14px] font-semibold text-white">{field.label}</span>
                        {testResult === 'ok' && (
                          <span className="flex items-center gap-1 text-[11px] text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-full">
                            <CheckCircle className="w-3 h-3" /> Bağlı
                          </span>
                        )}
                        {testResult === 'fail' && (
                          <span className="flex items-center gap-1 text-[11px] text-red-400 bg-red-500/10 px-2 py-0.5 rounded-full">
                            <XCircle className="w-3 h-3" /> Hata
                          </span>
                        )}
                      </div>
                      <p className="text-[12px] text-slate-500 mt-0.5">{field.desc}</p>
                    </div>
                  </div>
                  <a
                    href={field.link}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-1 text-[11px] text-indigo-400 hover:text-indigo-300 transition-colors shrink-0"
                  >
                    {field.linkText}
                    <ExternalLink className="w-3 h-3" />
                  </a>
                </div>

                <div className="flex items-center gap-2">
                  <div className="relative flex-1">
                    <input
                      type={isVisible ? 'text' : 'password'}
                      value={value}
                      onChange={(e) => setConfig(c => ({ ...c, [field.id]: e.target.value }))}
                      placeholder={field.placeholder}
                      className="w-full px-4 py-3 rounded-xl bg-white/[0.03] border border-white/[0.08] text-sm text-slate-300 placeholder-slate-600 focus:outline-none focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/10 transition-all font-mono text-[12px]"
                    />
                    <button
                      onClick={() => setShowKeys(s => ({ ...s, [field.id]: !s[field.id] }))}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors cursor-pointer"
                    >
                      {isVisible ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                    </button>
                  </div>
                  <button
                    onClick={() => testKey(field.provider)}
                    disabled={!value || isTestLoading}
                    className="px-4 py-3 rounded-xl bg-white/[0.04] border border-white/[0.08] text-[12px] font-medium text-slate-400 hover:text-white hover:bg-white/[0.08] transition-all disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer whitespace-nowrap"
                  >
                    {isTestLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Test Et'}
                  </button>
                </div>
              </motion.div>
            );
          })}
        </div>

        {/* Global Save */}
        <div className="mt-4 flex items-center gap-3">
          <motion.button
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            onClick={saveGlobalConfig}
            disabled={savingGlobal}
            className="flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-sm font-semibold shadow-lg shadow-indigo-500/20 disabled:opacity-50 cursor-pointer"
          >
            {savingGlobal ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
            Global Kaydet
          </motion.button>
          {savedGlobal && (
            <motion.span
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              className="text-[12px] text-emerald-400 flex items-center gap-1"
            >
              <CheckCircle className="w-3.5 h-3.5" /> Başarıyla kaydedildi
            </motion.span>
          )}
          {globalError && (
            <motion.span
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              className="text-[12px] text-red-400 flex items-center gap-1"
            >
              <XCircle className="w-3.5 h-3.5" /> {globalError}
            </motion.span>
          )}
        </div>
      </div>

      {/* ── Character-Based Telegram API Credentials Section ── */}
      <div>
        <h2 className="text-[15px] font-semibold text-white mb-4 flex items-center gap-2">
          <Users className="w-4 h-4 text-violet-400" />
          Karakter Bazlı Telegram API Credentials
        </h2>

        {loadingChars ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="w-5 h-5 animate-spin text-indigo-400" />
          </div>
        ) : charList.length === 0 ? (
          <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 text-center">
            <p className="text-[13px] text-slate-500">Henüz karakter oluşturulmamış.</p>
          </div>
        ) : (
          <>
            {/* Character Selector Dropdown */}
            <div className="relative mb-5">
              <button
                onClick={() => setCharDropdownOpen(!charDropdownOpen)}
                className="flex items-center gap-3 px-4 py-3 rounded-xl bg-white/[0.03] border border-white/[0.08] hover:border-white/[0.12] transition-all cursor-pointer w-full"
              >
                <div className="w-8 h-8 rounded-lg bg-violet-500/20 flex items-center justify-center shrink-0">
                  <Users className="w-4 h-4 text-violet-400" />
                </div>
                <div className="flex-1 text-left">
                  <div className="text-[11px] text-slate-500 leading-none">Karakter Seçin</div>
                  <div className="text-[13px] font-medium text-slate-200 mt-0.5 flex items-center gap-2">
                    {selectedCharName}
                    {selectedChar && !hasCredentials(selectedChar) && (
                      <span className="flex items-center gap-1 text-[10px] text-amber-400 bg-amber-500/10 px-2 py-0.5 rounded-full">
                        <AlertTriangle className="w-3 h-3" /> API bilgileri eksik
                      </span>
                    )}
                  </div>
                </div>
                <ChevronDown className={`w-4 h-4 text-slate-500 transition-transform ${charDropdownOpen ? 'rotate-180' : ''}`} />
              </button>
              <AnimatePresence>
                {charDropdownOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: -4 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -4 }}
                    className="absolute top-full left-0 mt-2 w-full rounded-xl bg-[#16162a] border border-white/[0.08] shadow-2xl shadow-black/40 z-50 overflow-hidden max-h-[300px] overflow-y-auto"
                  >
                    {charList.map(c => (
                      <button
                        key={c.id}
                        onClick={() => { setSelectedCharId(c.id); setCharDropdownOpen(false); }}
                        className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors cursor-pointer ${
                          selectedCharId === c.id ? 'bg-indigo-500/[0.1] text-white' : 'text-slate-400 hover:bg-white/[0.04] hover:text-slate-200'
                        }`}
                      >
                        <div className="w-7 h-7 rounded-full bg-gradient-to-br from-violet-500/20 to-pink-500/20 flex items-center justify-center shrink-0">
                          <span className="text-[11px] font-semibold text-violet-300">
                            {(c.identity?.name ?? '?')[0].toUpperCase()}
                          </span>
                        </div>
                        <span className="text-[13px] font-medium flex-1">{c.identity?.name ?? c.id.slice(0, 8)}</span>
                        {!hasCredentials(c) && (
                          <span className="flex items-center gap-1 text-[10px] text-amber-400 bg-amber-500/10 px-2 py-0.5 rounded-full shrink-0">
                            <AlertTriangle className="w-3 h-3" /> Eksik
                          </span>
                        )}
                      </button>
                    ))}
                  </motion.div>
                )}
              </AnimatePresence>
            </div>

            {/* Character Credentials Fields */}
            {loadingCreds ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="w-5 h-5 animate-spin text-indigo-400" />
              </div>
            ) : (
              <div className="space-y-4">
                {charFields.map((field, i) => {
                  const value = charCreds[field.id as keyof CharCredentials];
                  const isVisible = showKeys[`char_${field.id}`];

                  return (
                    <motion.div
                      key={field.id}
                      initial={{ opacity: 0, y: 12 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: i * 0.08 }}
                      className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5"
                    >
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex items-start gap-3">
                          <div className="w-8 h-8 rounded-lg bg-white/[0.04] flex items-center justify-center mt-0.5">
                            <Key className="w-4 h-4 text-slate-500" />
                          </div>
                          <div>
                            <span className="text-[14px] font-semibold text-white">{field.label}</span>
                            <p className="text-[12px] text-slate-500 mt-0.5">{field.desc}</p>
                          </div>
                        </div>
                        <a
                          href={field.link}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center gap-1 text-[11px] text-indigo-400 hover:text-indigo-300 transition-colors shrink-0"
                        >
                          {field.linkText}
                          <ExternalLink className="w-3 h-3" />
                        </a>
                      </div>

                      <div className="relative">
                        <input
                          type={isVisible ? 'text' : 'password'}
                          value={value}
                          onChange={(e) => setCharCreds(c => ({ ...c, [field.id]: e.target.value }))}
                          placeholder={field.placeholder}
                          className="w-full px-4 py-3 rounded-xl bg-white/[0.03] border border-white/[0.08] text-sm text-slate-300 placeholder-slate-600 focus:outline-none focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/10 transition-all font-mono text-[12px]"
                        />
                        <button
                          onClick={() => setShowKeys(s => ({ ...s, [`char_${field.id}`]: !s[`char_${field.id}`] }))}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors cursor-pointer"
                        >
                          {isVisible ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </button>
                      </div>
                    </motion.div>
                  );
                })}

                {/* Character Save */}
                <div className="mt-4 flex items-center gap-3">
                  <motion.button
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                    onClick={saveCharCredentials}
                    disabled={savingChar || !selectedCharId}
                    className="flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-violet-600 to-pink-600 text-sm font-semibold shadow-lg shadow-violet-500/20 disabled:opacity-50 cursor-pointer"
                  >
                    {savingChar ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                    {selectedCharName} için Kaydet
                  </motion.button>
                  {savedChar && (
                    <motion.span
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      className="text-[12px] text-emerald-400 flex items-center gap-1"
                    >
                      <CheckCircle className="w-3.5 h-3.5" /> Başarıyla kaydedildi
                    </motion.span>
                  )}
                  {charError && (
                    <motion.span
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      className="text-[12px] text-red-400 flex items-center gap-1"
                    >
                      <XCircle className="w-3.5 h-3.5" /> {charError}
                    </motion.span>
                  )}
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
