'use client'

import { useState, useEffect } from 'react'
import { Save, Plus, Trash2, Bot, MessageSquare, Key, Link as LinkIcon, Lock, Send, CheckCircle2, XCircle, Loader2, Sparkles, Box } from 'lucide-react'
import { cn } from '@/lib/utils'
import { AIServiceConfig, AppSettings } from '@/lib/types'
import { DashboardLayout } from '@/components/layout/DashboardLayout'

export default function SettingsPage() {
    const [loading, setLoading] = useState(true)
    const [saving, setSaving] = useState(false)
    const [settings, setSettings] = useState<AppSettings>({
        telegram: { botToken: '', chatId: '' },
        aiProviders: []
    })
    const [message, setMessage] = useState<{ text: string, type: 'success' | 'error' } | null>(null)

    // Test loading states
    const [testingTelegram, setTestingTelegram] = useState(false)
    const [testingAI, setTestingAI] = useState<string | null>(null)
    const [detectingModels, setDetectingModels] = useState<string | null>(null)
    const [availableModels, setAvailableModels] = useState<Record<string, string[]>>({})

    useEffect(() => {
        fetch('/api/settings')
            .then(res => res.json())
            .then(data => {
                setSettings(data)
                setLoading(false)
            })
            .catch(err => {
                console.error(err)
                setLoading(false)
                setMessage({ text: 'Error cargando configuración', type: 'error' })
            })
    }, [])

    const handleSave = async () => {
        setSaving(true)
        setMessage(null)
        try {
            const res = await fetch('/api/settings', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(settings)
            })

            if (!res.ok) throw new Error('Error saving')

            setMessage({ text: 'Configuración guardada correctamente', type: 'success' })
        } catch (err) {
            setMessage({ text: 'Error al guardar la configuración', type: 'error' })
        } finally {
            setSaving(false)
        }
    }

    const testTelegram = async () => {
        setTestingTelegram(true)
        setMessage(null)
        try {
            const res = await fetch('/api/test/telegram', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(settings.telegram)
            })
            const data = await res.json()

            if (data.success) {
                setMessage({ text: 'Mensaje de prueba enviado con éxito ✅', type: 'success' })
            } else {
                setMessage({ text: `Error: ${data.error}`, type: 'error' })
            }
        } catch (err: any) {
            setMessage({ text: 'Error de conexión al probar Telegram', type: 'error' })
        } finally {
            setTestingTelegram(false)
        }
    }

    const testAI = async (provider: AIServiceConfig) => {
        setTestingAI(provider.id)
        setMessage(null)
        try {
            const res = await fetch('/api/test/ai', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(provider)
            })
            const data = await res.json()

            if (data.success) {
                setMessage({ text: `Conexión exitosa con ${provider.model || provider.name} (${data.latency}ms) ✅`, type: 'success' })
            } else {
                setMessage({ text: `Error con ${provider.name}: ${data.error}`, type: 'error' })
            }
        } catch (err) {
            setMessage({ text: 'Error al conectar con el proveedor', type: 'error' })
        } finally {
            setTestingAI(null)
        }
    }

    const detectModels = async (provider: AIServiceConfig) => {
        setDetectingModels(provider.id)
        setMessage(null)
        try {
            const res = await fetch('/api/proxy/models', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ endpoint: provider.endpoint, token: provider.token })
            })
            const data = await res.json()

            if (data.success && data.models.length > 0) {
                setAvailableModels(prev => ({ ...prev, [provider.id]: data.models }))
                // Auto select first if none selected
                if (!provider.model) {
                    updateProvider(provider.id, 'model', data.models[0])
                }
                setMessage({ text: `Se detectaron ${data.models.length} modelos ✅`, type: 'success' })
            } else {
                setMessage({ text: `No se pudieron detectar modelos. Ingrésalo manualmente.`, type: 'error' })
            }
        } catch (err) {
            console.error(err)
            setMessage({ text: 'Error al consultar modelos', type: 'error' })
        } finally {
            setDetectingModels(null)
        }
    }

    const addProvider = () => {
        if (settings.aiProviders.length >= 3) return
        setSettings(prev => ({
            ...prev,
            aiProviders: [
                ...prev.aiProviders,
                { id: crypto.randomUUID(), name: '', endpoint: '', token: '', model: '' }
            ]
        }))
    }

    const removeProvider = (id: string) => {
        setSettings(prev => ({
            ...prev,
            aiProviders: prev.aiProviders.filter(p => p.id !== id)
        }))
    }

    const updateProvider = (id: string, field: keyof AIServiceConfig, value: string) => {
        setSettings(prev => ({
            ...prev,
            aiProviders: prev.aiProviders.map(p =>
                p.id === id ? { ...p, [field]: value } : p
            )
        }))
    }

    if (loading) return <div className="p-8 text-center text-slate-400">Cargando configuración...</div>

    return (
        <DashboardLayout title="Configuración">
            <div className="max-w-4xl mx-auto space-y-8 pb-10">

                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-bold text-white">Configuración</h2>
                        <p className="text-slate-400 text-sm">Gestiona la integración con Telegram e Inteligencia Artificial.</p>
                    </div>
                    <button
                        onClick={handleSave}
                        disabled={saving}
                        className="flex items-center gap-2 px-6 py-2 bg-emerald-500 hover:bg-emerald-400 text-white rounded-lg transition shadow-lg shadow-emerald-500/20 font-medium disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        <Save size={18} />
                        {saving ? 'Guardando...' : 'Guardar Cambios'}
                    </button>
                </div>

                {message && (
                    <div className={cn(
                        "p-4 rounded-lg text-sm font-medium border flex items-center gap-2 animate-in fade-in slide-in-from-top-2",
                        message.type === 'success' ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-400" : "bg-red-500/10 border-red-500/20 text-red-400"
                    )}>
                        {message.type === 'success' ? <CheckCircle2 size={18} /> : <XCircle size={18} />}
                        {message.text}
                    </div>
                )}

                {/* Telegram Configuration */}
                <section className="space-y-4">
                    <div className="flex items-center justify-between text-white border-b border-slate-800 pb-2">
                        <div className="flex items-center gap-2">
                            <Bot className="text-cyan-400" />
                            <h2 className="text-lg font-semibold">Telegram Bot</h2>
                        </div>
                        <button
                            onClick={testTelegram}
                            disabled={testingTelegram || !settings.telegram.botToken || !settings.telegram.chatId}
                            className="text-xs flex items-center gap-1.5 bg-cyan-500/10 hover:bg-cyan-500/20 text-cyan-400 border border-cyan-500/20 px-3 py-1.5 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {testingTelegram ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />}
                            Probar Envío
                        </button>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-6 bg-slate-900 border border-slate-800 rounded-xl">
                        <div className="space-y-2">
                            <label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
                                <Key size={12} /> Bot Token
                            </label>
                            <input
                                type="text"
                                placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
                                value={settings.telegram.botToken}
                                onChange={(e) => setSettings({ ...settings, telegram: { ...settings.telegram, botToken: e.target.value } })}
                                className="w-full px-4 py-3 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500 text-white font-mono text-sm outline-none transition-all placeholder:text-slate-700"
                            />
                            <p className="text-[10px] text-slate-500">El token que te da @BotFather.</p>
                        </div>

                        <div className="space-y-2">
                            <label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
                                <MessageSquare size={12} /> Chat ID
                            </label>
                            <input
                                type="text"
                                placeholder="123456789"
                                value={settings.telegram.chatId}
                                onChange={(e) => setSettings({ ...settings, telegram: { ...settings.telegram, chatId: e.target.value } })}
                                className="w-full px-4 py-3 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500 text-white font-mono text-sm outline-none transition-all placeholder:text-slate-700"
                            />
                            <p className="text-[10px] text-slate-500">Tu ID numérico de Telegram (o el ID del grupo).</p>
                        </div>
                    </div>
                </section>

                {/* AI Providers Configuration */}
                <section className="space-y-4">
                    <div className="flex items-center justify-between text-white border-b border-slate-800 pb-2">
                        <div className="flex items-center gap-2">
                            <Bot className="text-purple-400" />
                            <h2 className="text-lg font-semibold">Proveedores de IA</h2>
                        </div>
                        <button
                            onClick={addProvider}
                            disabled={settings.aiProviders.length >= 3}
                            className="text-xs flex items-center gap-1 bg-slate-800 hover:bg-slate-700 text-slate-200 px-3 py-1.5 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            <Plus size={14} /> Agregar Provider ({settings.aiProviders.length}/3)
                        </button>
                    </div>

                    <div className="space-y-4">
                        {settings.aiProviders.length === 0 && (
                            <div className="p-8 text-center text-slate-500 border border-dashed border-slate-800 rounded-xl">
                                No hay proveedores de IA configurados. Agrega uno para empezar.
                            </div>
                        )}

                        {settings.aiProviders.map((provider, index) => (
                            <div key={provider.id} className="p-6 bg-slate-900 border border-slate-800 rounded-xl relative group">
                                <div className="flex justify-between items-start mb-4">
                                    <h3 className="text-sm font-semibold text-slate-300 bg-slate-950 inline-block px-3 py-1 rounded-md border border-slate-800">
                                        Provider #{index + 1}
                                    </h3>
                                    <div className="flex gap-2">
                                        <button
                                            onClick={() => testAI(provider)}
                                            disabled={testingAI === provider.id || !provider.endpoint || !provider.token || !provider.model}
                                            className={cn("text-xs flex items-center gap-1 bg-slate-800 hover:bg-slate-700 text-purple-300 border border-purple-500/20 px-2 py-1.5 rounded-lg transition disabled:opacity-50", !provider.model && "opacity-50")}
                                            title="Verificar conexión"
                                        >
                                            {testingAI === provider.id ? <Loader2 size={12} className="animate-spin" /> : <LinkIcon size={12} />}
                                            Test
                                        </button>
                                        <button
                                            onClick={() => removeProvider(provider.id)}
                                            className="text-slate-500 hover:text-red-400 transition-colors p-1.5 hover:bg-red-500/10 rounded-lg"
                                            title="Eliminar"
                                        >
                                            <Trash2 size={16} />
                                        </button>
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 gap-4">
                                    <div className="space-y-2">
                                        <label className="text-xs font-medium text-slate-400 uppercase tracking-wider">Nombre</label>
                                        <input
                                            type="text"
                                            placeholder="Ej: MiniMax, Z.ai"
                                            value={provider.name}
                                            onChange={(e) => updateProvider(provider.id, 'name', e.target.value)}
                                            className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white text-sm outline-none"
                                        />
                                    </div>

                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div className="space-y-2">
                                            <label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
                                                <LinkIcon size={12} /> Endpoint URL
                                            </label>
                                            <input
                                                type="text"
                                                placeholder="https://api.example.com/v1"
                                                value={provider.endpoint}
                                                onChange={(e) => updateProvider(provider.id, 'endpoint', e.target.value)}
                                                className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white font-mono text-sm outline-none"
                                            />
                                        </div>
                                        <div className="space-y-2">
                                            <label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
                                                <Lock size={12} /> API Key / Token
                                            </label>
                                            <input
                                                type="password"
                                                placeholder="sk-..."
                                                value={provider.token}
                                                onChange={(e) => updateProvider(provider.id, 'token', e.target.value)}
                                                className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white font-mono text-sm outline-none"
                                            />
                                        </div>
                                    </div>

                                    {/* Model Selection */}
                                    <div className="space-y-2">
                                        <div className="flex justify-between items-center">
                                            <label className="text-xs font-medium text-slate-400 uppercase tracking-wider flex items-center gap-2">
                                                <Box size={12} /> Model
                                            </label>
                                            <button
                                                onClick={() => detectModels(provider)}
                                                disabled={detectingModels === provider.id || !provider.endpoint || !provider.token}
                                                className="text-[10px] flex items-center gap-1 text-cyan-400 hover:text-cyan-300 disabled:opacity-50"
                                            >
                                                {detectingModels === provider.id ? <Loader2 size={10} className="animate-spin" /> : <Sparkles size={10} />}
                                                Auto Detectar
                                            </button>
                                        </div>
                                        {availableModels[provider.id] ? (
                                            <select
                                                value={provider.model || ''}
                                                onChange={(e) => updateProvider(provider.id, 'model', e.target.value)}
                                                className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white text-sm outline-none"
                                            >
                                                <option value="" disabled>Selecciona un modelo</option>
                                                {availableModels[provider.id].map(m => (
                                                    <option key={m} value={m}>{m}</option>
                                                ))}
                                            </select>
                                        ) : (
                                            <input
                                                type="text"
                                                placeholder="Ej: gpt-3.5-turbo, glm-4"
                                                value={provider.model || ''}
                                                onChange={(e) => updateProvider(provider.id, 'model', e.target.value)}
                                                className="w-full px-4 py-2.5 bg-slate-950 border border-slate-800 rounded-lg focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 text-white font-mono text-sm outline-none"
                                            />
                                        )}
                                    </div>

                                </div>
                            </div>
                        ))}
                    </div>
                </section>
            </div>
        </DashboardLayout>
    )
}
