import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { PluginService, PairService } from '../services/api';
import { Puzzle, Power, Save, Settings2, Link2, CheckCircle2, AlertTriangle, ExternalLink, Zap } from 'lucide-react';
import Modal from '../components/Modal';

type PairStep = 1 | 2 | 3;

export default function PluginsPage() {
  const navigate = useNavigate();
  const [plugins, setPlugins] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // Config modal
  const [isConfigOpen, setIsConfigOpen] = useState(false);
  const [selectedPlugin, setSelectedPlugin] = useState<any>(null);
  const [configData, setConfigData] = useState<Record<string, string>>({});
  const [savingConfig, setSavingConfig] = useState(false);

  // Pairing modal
  const [isPairOpen, setIsPairOpen] = useState(false);
  const [pairStep, setPairStep] = useState<PairStep>(1);
  const [pairEmail, setPairEmail] = useState('');
  const [pairUrl, setPairUrl] = useState('');
  const [pairCode, setPairCode] = useState('');
  const [pairLoading, setPairLoading] = useState(false);
  const [pairError, setPairError] = useState('');
  const [pairDevCode, setPairDevCode] = useState('');

  const fetchPlugins = async () => {
    setLoading(true);
    try {
      const data = await PluginService.list();
      setPlugins(data);
    } catch {
      // interceptor handles 401
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchPlugins(); }, []);

  const handleToggle = async (plugin: any) => {
    const action = plugin.active ? 'Desativar' : 'Ativar';
    if (!confirm(`Deseja ${action} o plugin ${plugin.name}?`)) return;
    try {
      plugin.active ? await PluginService.deactivate(plugin.id) : await PluginService.activate(plugin.id);
      fetchPlugins();
    } catch (e: any) {
      alert(e.response?.data?.error || `Erro ao ${action} plugin`);
    }
  };

  const handleOpenConfig = async (plugin: any) => {
    setSelectedPlugin(plugin);
    try {
      const cfg = await PluginService.getConfig(plugin.id);
      setConfigData(cfg || {});
      setIsConfigOpen(true);
    } catch {
      alert('Erro ao carregar configurações');
    }
  };

  const handleSaveConfig = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedPlugin) return;
    setSavingConfig(true);
    try {
      await PluginService.setConfig(selectedPlugin.id, configData);
      setIsConfigOpen(false);
      alert('Configuração salva com sucesso!');
    } catch (e: any) {
      alert(e.response?.data?.error || 'Erro ao salvar');
    } finally {
      setSavingConfig(false);
    }
  };

  // Pairing flow
  const openPairModal = async (plugin: any) => {
    setPairStep(1);
    setPairEmail('');
    setPairCode('');
    setPairError('');
    setPairDevCode('');
    // Pre-fill URL from existing config
    try {
      const cfg = await PluginService.getConfig(plugin.id);
      setPairUrl(cfg?.newwhats_url || cfg?.motor_url || '');
    } catch {
      setPairUrl('');
    }
    setIsPairOpen(true);
  };

  const handlePairStep1 = async () => {
    if (!pairEmail || !pairUrl) { setPairError('Preencha a URL e o e-mail.'); return; }
    setPairLoading(true);
    setPairError('');
    try {
      const data = await PairService.request(pairEmail, pairUrl.replace(/\/$/, ''));
      if (data.dev_code) {
        setPairCode(data.dev_code);
        setPairDevCode(data.dev_code);
      }
      setPairStep(2);
    } catch (err: any) {
      setPairError(err.message);
    } finally {
      setPairLoading(false);
    }
  };

  const handlePairStep2 = async () => {
    if (pairCode.length !== 6) { setPairError('Digite o código de 6 dígitos.'); return; }
    setPairLoading(true);
    setPairError('');
    try {
      const data = await PairService.confirm(pairEmail, pairCode, pairUrl.replace(/\/$/, ''));
      await PluginService.setConfig('newwhats', { integration_key: data.integration_key, newwhats_url: pairUrl });
      setPairStep(3);
      fetchPlugins();
    } catch (err: any) {
      setPairError(err.message);
    } finally {
      setPairLoading(false);
    }
  };

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <header>
        <h2 className="text-3xl font-black text-white tracking-tighter uppercase italic">Integrações & Plugins</h2>
        <p className="text-slate-400 mt-1 font-medium">Gerencie conexões do sistema, como Automação IA no WhatsApp.</p>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {loading ? (
          [1, 2].map(i => (
            <div key={i} className="bg-slate-900/40 border border-slate-800 h-64 rounded-[2rem] animate-pulse" />
          ))
        ) : plugins.length === 0 ? (
          <div className="col-span-full py-20 text-center text-slate-500 italic bg-slate-900/40 rounded-[2rem] border border-slate-800">
            Nenhum plugin instalado no servidor.
          </div>
        ) : plugins.map(plugin => (
          <div key={plugin.id} className={`bg-slate-900/40 backdrop-blur-md border rounded-[2rem] overflow-hidden transition-all group flex flex-col relative ${plugin.active ? 'border-cyan-500/30' : 'border-slate-800'}`}>
            <div className="p-8 flex flex-col gap-5">
              {/* Header: icon + status badge */}
              <div className="flex justify-between items-start">
                <div className={`p-4 rounded-2xl flex items-center justify-center border transition-all ${plugin.active ? 'bg-cyan-500/10 text-cyan-400 border-cyan-500/20' : 'bg-slate-800/50 text-slate-500 border-white/5 grayscale'}`}>
                  <Puzzle size={32} />
                </div>
                <div className={`px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest border ${plugin.active ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20' : 'bg-slate-800 text-slate-500 border-slate-700'}`}>
                  {plugin.active ? 'Ativo' : 'Desativado'}
                </div>
              </div>

              {/* Name + version */}
              <div>
                <h3 className="text-xl font-black text-white group-hover:text-cyan-400 transition-colors tracking-tight">
                  {plugin.name}
                </h3>
                <span className="text-[11px] text-slate-600 font-bold">v{plugin.version}</span>
              </div>

              {/* Description */}
              <p className="text-slate-500 text-sm line-clamp-2 font-medium italic leading-relaxed">{plugin.description}</p>

              {/* Feature badges */}
              {plugin.features?.length > 0 && (
                <div className="flex flex-wrap gap-1.5">
                  {plugin.features.map((f: string) => (
                    <span key={f} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-lg text-[10px] font-semibold bg-slate-800 text-slate-400 border border-slate-700">
                      <Zap size={9} className="text-cyan-500" />
                      {f}
                    </span>
                  ))}
                </div>
              )}

              {/* CTA buttons */}
              <div className="flex flex-col gap-2 pt-1">
                {/* Open UI (inbox, dashboard, etc.) */}
                {plugin.ui_path && plugin.active && (
                  <button
                    onClick={() => navigate(plugin.ui_path)}
                    className="w-full py-3 px-4 rounded-xl font-black text-xs uppercase tracking-widest border border-emerald-500/30 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20 transition-all flex items-center justify-center gap-2"
                  >
                    <ExternalLink size={14} />
                    Abrir Inbox
                  </button>
                )}
                {/* Pair button for newwhats */}
                {plugin.id === 'newwhats' && (
                  <button
                    onClick={() => openPairModal(plugin)}
                    className="w-full py-3 px-4 rounded-xl font-black text-xs uppercase tracking-widest border border-cyan-500/30 bg-cyan-500/10 text-cyan-400 hover:bg-cyan-500/20 transition-all flex items-center justify-center gap-2"
                  >
                    <Link2 size={14} />
                    Parear com NewWhats
                  </button>
                )}
              </div>
            </div>

            {/* Footer: toggle + config */}
            <div className="mt-auto p-6 bg-slate-800/20 border-t border-slate-800 flex items-center gap-3 group-hover:bg-slate-800/40 transition-all">
              <button
                onClick={() => handleToggle(plugin)}
                className={`flex-1 py-3 px-4 rounded-xl font-black text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 ${plugin.active ? 'bg-rose-500/10 text-rose-500 hover:bg-rose-500 hover:text-white border border-rose-500/20' : 'bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500 hover:text-white border border-emerald-500/20'}`}
              >
                <Power size={14} />
                {plugin.active ? 'Desativar' : 'Ativar'}
              </button>
              <button
                onClick={() => handleOpenConfig(plugin)}
                className="p-3 bg-slate-800 text-slate-400 hover:text-white hover:bg-slate-700 rounded-xl transition-all border border-slate-700"
                title="Configurações"
              >
                <Settings2 size={16} />
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* CONFIG MODAL */}
      <Modal isOpen={isConfigOpen} onClose={() => setIsConfigOpen(false)} title={`Setup: ${selectedPlugin?.name}`}>
        <form onSubmit={handleSaveConfig} className="space-y-6">
          <p className="text-sm text-slate-400 font-medium italic mb-6">
            Preencha os campos de acordo com a documentação da integração.
          </p>
          {selectedPlugin?.config_schema?.map((field: any) => (
            <div key={field.key} className="space-y-2">
              <label className="block text-[10px] font-black uppercase tracking-widest text-slate-400">
                {field.label} {field.required && <span className="text-rose-500">*</span>}
              </label>
              <input
                required={field.required}
                type={field.type === 'password' ? 'password' : 'text'}
                value={configData[field.key] || ''}
                onChange={e => setConfigData({ ...configData, [field.key]: e.target.value })}
                className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-cyan-500 outline-none transition-all"
              />
              {field.help && <p className="text-[11px] text-slate-500 italic">{field.help}</p>}
            </div>
          ))}
          <button
            type="submit"
            disabled={savingConfig}
            className="w-full bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 text-slate-950 font-black py-4 rounded-2xl flex items-center justify-center gap-2 transition-all shadow-lg shadow-cyan-500/20 uppercase italic text-sm mt-8"
          >
            <Save size={20} />
            {savingConfig ? 'Salvando...' : 'Salvar Chaves'}
          </button>
        </form>
      </Modal>

      {/* PAIRING MODAL */}
      <Modal isOpen={isPairOpen} onClose={() => setIsPairOpen(false)} title="Parear com NewWhats">
        <div className="space-y-6">
          {pairStep === 1 && (
            <div className="space-y-5">
              <p className="text-sm text-slate-400 font-medium">
                Informe o servidor NewWhats e o e-mail da sua conta. Um código de confirmação será enviado.
              </p>
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">URL do servidor NewWhats</label>
                <input
                  type="text"
                  value={pairUrl}
                  onChange={e => setPairUrl(e.target.value)}
                  placeholder="http://newwhats.local:8008"
                  className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-cyan-500 outline-none transition-all"
                />
              </div>
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">E-mail da conta NewWhats</label>
                <input
                  type="email"
                  value={pairEmail}
                  onChange={e => setPairEmail(e.target.value)}
                  placeholder="seu@email.com"
                  className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-cyan-500 outline-none transition-all"
                />
              </div>
              {pairError && <p className="text-rose-400 text-sm font-medium">{pairError}</p>}
              <button
                onClick={handlePairStep1}
                disabled={pairLoading}
                className="w-full bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 text-slate-950 font-black py-4 rounded-2xl flex items-center justify-center gap-2 transition-all shadow-lg shadow-cyan-500/20 uppercase italic text-sm"
              >
                {pairLoading ? 'Enviando...' : 'Enviar Código →'}
              </button>
            </div>
          )}

          {pairStep === 2 && (
            <div className="space-y-5">
              {pairDevCode ? (
                <div className="flex items-start gap-3 p-4 bg-amber-500/10 border border-amber-500/20 rounded-xl">
                  <AlertTriangle size={18} className="text-amber-400 shrink-0 mt-0.5" />
                  <p className="text-amber-400 text-sm font-medium">
                    SMTP não configurado — código gerado localmente e preenchido automaticamente. Clique em <strong>Confirmar</strong> para continuar.
                  </p>
                </div>
              ) : (
                <p className="text-sm text-slate-400 font-medium">
                  Código enviado para <strong className="text-white">{pairEmail}</strong>. Digite abaixo:
                </p>
              )}
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Código de Confirmação</label>
                <input
                  type="text"
                  value={pairCode}
                  onChange={e => setPairCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                  placeholder="000000"
                  maxLength={6}
                  className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-4 text-white focus:ring-1 ring-cyan-500 outline-none transition-all text-center text-2xl font-black tracking-[0.4em]"
                />
              </div>
              {pairError && <p className="text-rose-400 text-sm font-medium">{pairError}</p>}
              <button
                onClick={handlePairStep2}
                disabled={pairLoading}
                className="w-full bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 text-slate-950 font-black py-4 rounded-2xl flex items-center justify-center gap-2 transition-all shadow-lg shadow-cyan-500/20 uppercase italic text-sm"
              >
                {pairLoading ? 'Confirmando...' : 'Confirmar ✓'}
              </button>
            </div>
          )}

          {pairStep === 3 && (
            <div className="text-center space-y-4 py-4">
              <div className="w-16 h-16 bg-emerald-500/10 border border-emerald-500/20 rounded-2xl flex items-center justify-center mx-auto">
                <CheckCircle2 size={40} className="text-emerald-400" />
              </div>
              <h3 className="text-xl font-black text-white">Pareamento Concluído!</h3>
              <p className="text-slate-400 text-sm">A chave de integração foi salva automaticamente no plugin.</p>
              <button
                onClick={() => setIsPairOpen(false)}
                className="mx-auto px-8 py-3 bg-slate-800 hover:bg-slate-700 text-white font-black rounded-xl transition-all text-sm uppercase tracking-widest"
              >
                Fechar
              </button>
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
}
