import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import axios from 'axios';
import PageHeader from '../../components/PageHeader';

/**
 * 🎨 MÓDULO: HOSTING - DETALLE DE SERVICIO
 * 
 * ✅ ESTILO ACTUALIZADO - 6 Tabs completos con Vault PIN
 */

export default function HostingShow() {
    const { id } = useParams();
    const [service, setService] = useState<any>(null);
    const [activeTab, setActiveTab] = useState<'overview' | 'vault' | 'renewals' | 'backups' | 'monitoring' | 'audit'>('overview');
    const [loading, setLoading] = useState(true);

    // Vault State
    const [showVaultModal, setShowVaultModal] = useState(false);
    const [revealingItem, setRevealingItem] = useState<any>(null);
    const [pin, setPin] = useState('');
    const [revealedSecret, setRevealedSecret] = useState('');
    const [secretTimer, setSecretTimer] = useState(0);

    useEffect(() => {
        fetchService();
    }, [id]);

    useEffect(() => {
        if (secretTimer > 0) {
            const interval = setInterval(() => {
                setSecretTimer(prev => {
                    if (prev <= 1) {
                        setRevealedSecret('');
                        return 0;
                    }
                    return prev - 1;
                });
            }, 1000);
            return () => clearInterval(interval);
        }
    }, [secretTimer]);

    const fetchService = async () => {
        try {
            const res = await axios.get(`/api/hosting/services/${id}`);
            setService(res.data);
        } catch (error) {
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const handleRevealSecret = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            const res = await axios.post(`/api/hosting/vault-items/${revealingItem.id}/reveal`, { pin });
            setRevealedSecret(res.data.secret);
            setSecretTimer(30);
            setPin('');
        } catch (error: any) {
            if (error.response?.status === 422) {
                alert('PIN incorrecto');
            } else if (error.response?.status === 429) {
                alert(error.response.data.message);
            } else {
                alert('Error al revelar secreto');
            }
        }
    };

    const handleRenew = async () => {
        if (!confirm('¿Renovar este servicio?')) return;
        try {
            await axios.post(`/api/hosting/services/${id}/renew`, {});
            alert('Servicio renovado correctamente');
            fetchService();
        } catch (error) {
            alert('Error al renovar');
        }
    };

    if (loading) return <div className="p-8 text-center">Cargando servicio...</div>;
    if (!service) return <div className="p-8 text-center text-red-400">Servicio no encontrado</div>;

    const tabs = [
        { id: 'overview', label: '📊 Resumen' },
        { id: 'vault', label: '🔐 Credenciales' },
        { id: 'renewals', label: '🔄 Renovaciones' },
        { id: 'backups', label: '💾 Backups' },
        { id: 'monitoring', label: '📈 Monitoreo' },
        { id: 'audit', label: '📜 Auditoría' },
    ];

    return (
        <div className="animate-fadeIn">
            <Link to="/app/hosting/services" className="text-sm text-slate-400 hover:text-white mb-4 inline-block">← Volver a servicios</Link>

            <PageHeader
                title={service.label}
                subtitle={`Vence: ${service.next_due_at}`}
                actions={
                    <button onClick={handleRenew} className="btn btn-primary">🔄 Renovar</button>
                }
            />

            {/* Tabs */}
            <div className="flex border-b border-slate-700 mb-6 overflow-x-auto">
                {tabs.map(tab => (
                    <button
                        key={tab.id}
                        onClick={() => setActiveTab(tab.id as any)}
                        className={`px-6 py-3 font-medium transition-colors border-b-2 whitespace-nowrap ${activeTab === tab.id
                                ? 'border-primary-500 text-white bg-slate-800/50'
                                : 'border-transparent text-slate-400 hover:text-slate-200'
                            }`}
                    >
                        {tab.label}
                    </button>
                ))}
            </div>

            {/* Tab Content */}
            <div className="min-h-[300px]">
                {activeTab === 'overview' && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="card">
                            <h3 className="text-lg font-bold mb-4">Información General</h3>
                            <div className="space-y-3 text-sm">
                                <div className="flex justify-between border-b border-slate-700 pb-2">
                                    <span className="text-slate-400">Plan:</span>
                                    <span>{service.plan?.name || 'N/A'}</span>
                                </div>
                                <div className="flex justify-between border-b border-slate-700 pb-2">
                                    <span className="text-slate-400">Servidor:</span>
                                    <span>{service.server?.name || 'N/A'}</span>
                                </div>
                                <div className="flex justify-between border-b border-slate-700 pb-2">
                                    <span className="text-slate-400">Dominio:</span>
                                    <span>{service.domain_fqdn || 'N/A'}</span>
                                </div>
                                <div className="flex justify-between border-b border-slate-700 pb-2">
                                    <span className="text-slate-400">Estado:</span>
                                    <span className="badge badge-success">{service.status}</span>
                                </div>
                                <div className="flex justify-between border-b border-slate-700 pb-2">
                                    <span className="text-slate-400">Precio:</span>
                                    <span className="font-bold">{service.currency} {service.price}</span>
                                </div>
                            </div>
                        </div>

                        <div className="card">
                            <h3 className="text-lg font-bold mb-4">Provisioning</h3>
                            {service.provisioning_meta_json ? (
                                <div className="space-y-2 text-sm">
                                    {Object.entries(service.provisioning_meta_json).map(([key, value]: any) => (
                                        <div key={key} className="flex justify-between">
                                            <span className="text-slate-400">{key}:</span>
                                            <span>{value}</span>
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <p className="text-slate-500 text-sm">No hay información de provisioning</p>
                            )}
                        </div>
                    </div>
                )}

                {activeTab === 'vault' && (
                    <div className="table-container">
                        <div className="table-header flex justify-between">
                            <h3 className="table-title">🔐 Credenciales Cifradas</h3>
                        </div>
                        <div className="table-wrapper">
                            <table className="table">
                                <thead>
                                    <tr>
                                        <th>Proveedor</th>
                                        <th>Etiqueta</th>
                                        <th>Usuario</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {service.vault_items && service.vault_items.length > 0 ? service.vault_items.map((item: any) => (
                                        <tr key={item.id}>
                                            <td><span className="badge badge-purple">{item.provider}</span></td>
                                            <td className="font-bold">{item.label}</td>
                                            <td className="text-sm">{item.username || 'N/A'}</td>
                                            <td>
                                                <button
                                                    className="btn btn-sm btn-ghost hover:text-blue-400"
                                                    onClick={() => {
                                                        setRevealingItem(item);
                                                        setShowVaultModal(true);
                                                    }}
                                                >
                                                    👁️ Revelar
                                                </button>
                                            </td>
                                        </tr>
                                    )) : (
                                        <tr><td colSpan={4} className="text-center p-4 text-slate-500">No hay credenciales</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {activeTab === 'renewals' && (
                    <div className="card">
                        <h3 className="text-lg font-bold mb-4">Historial de Renovaciones</h3>
                        <p className="text-slate-500">Próximamente: historial de renovaciones</p>
                    </div>
                )}

                {activeTab === 'backups' && (
                    <div className="card">
                        <h3 className="text-lg font-bold mb-4">Backups Programados</h3>
                        <p className="text-slate-500">Próximamente: gestión de backups</p>
                    </div>
                )}

                {activeTab === 'monitoring' && (
                    <div className="card">
                        <h3 className="text-lg font-bold mb-4">Métricas del Servidor</h3>
                        <p className="text-slate-500">Próximamente: gráficas de CPU, RAM, Disco</p>
                    </div>
                )}

                {activeTab === 'audit' && (
                    <div className="card">
                        <h3 className="text-lg font-bold mb-4">Registro de Auditoría</h3>
                        <p className="text-slate-500">Próximamente: log de accesos a credenciales</p>
                    </div>
                )}
            </div>

            {/* Modal Revelar Secreto (Reutilizado de Dominios) */}
            {showVaultModal && revealingItem && (
                <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
                    <div className="card w-full max-w-md shadow-2xl border border-slate-700">
                        <div className="flex justify-between items-center border-b border-slate-700 pb-4 mb-4">
                            <h3 className="text-xl font-bold text-white">🔐 Revelar Credencial</h3>
                            <button onClick={() => {
                                setShowVaultModal(false);
                                setRevealedSecret('');
                                setPin('');
                            }} className="text-slate-400 hover:text-white">✕</button>
                        </div>

                        <div className="mb-4">
                            <p className="text-sm text-slate-400">Proveedor: <span className="text-white">{revealingItem.provider}</span></p>
                            <p className="text-sm text-slate-400">Etiqueta: <span className="text-white">{revealingItem.label}</span></p>
                        </div>

                        {!revealedSecret ? (
                            <form onSubmit={handleRevealSecret} className="space-y-4">
                                <div>
                                    <label className="block text-sm font-medium text-slate-300 mb-1">PIN de Seguridad (4 dígitos)</label>
                                    <input
                                        type="password"
                                        maxLength={4}
                                        pattern="\d{4}"
                                        required
                                        className="input w-full text-center text-2xl tracking-widest"
                                        placeholder="••••"
                                        value={pin}
                                        onChange={(e) => setPin(e.target.value.replace(/\D/g, ''))}
                                        autoFocus
                                    />
                                </div>

                                <div className="flex justify-end gap-3">
                                    <button type="button" onClick={() => setShowVaultModal(false)} className="btn btn-ghost">
                                        Cancelar
                                    </button>
                                    <button type="submit" className="btn btn-primary">
                                        🔓 Revelar
                                    </button>
                                </div>
                            </form>
                        ) : (
                            <div className="space-y-4">
                                <div className="p-4 bg-green-500/10 border border-green-500/30 rounded">
                                    <p className="text-xs text-slate-400 mb-2">Contraseña revelada:</p>
                                    <p className="font-mono text-lg text-green-400 break-all select-all">{revealedSecret}</p>
                                </div>
                                <div className="text-center">
                                    <p className="text-sm text-orange-400">
                                        ⏱️ Se ocultará en {secretTimer} segundos
                                    </p>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}
