import { useState, useEffect } from 'react';
import axios from 'axios';
import PageHeader from '../../components/PageHeader';

/**
 * 🎨 MÓDULO: HOSTING - PLANES
 * 
 * ✅ ESTILO ACTUALIZADO - CRUD Completo
 */

export default function HostingPlans() {
    const [plans, setPlans] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [formData, setFormData] = useState({
        name: '',
        plan_type: 'shared',
        billing_cycle: 'annual',
        price: '',
        currency: 'USD',
        disk_gb: '',
        bandwidth_gb: '',
        email_accounts: '',
        databases: '',
        ssl_included: true,
        backups_included: true,
    });

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

    const fetchPlans = async () => {
        try {
            const res = await axios.get('/api/hosting/plans');
            setPlans(res.data);
        } catch (error) {
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            const payload = {
                name: formData.name,
                plan_type: formData.plan_type,
                billing_cycle: formData.billing_cycle,
                price: parseFloat(formData.price),
                currency: formData.currency,
                features_json: {
                    disk_gb: parseInt(formData.disk_gb),
                    bandwidth_gb: parseInt(formData.bandwidth_gb),
                    email_accounts: parseInt(formData.email_accounts),
                    databases: parseInt(formData.databases),
                    ssl_included: formData.ssl_included,
                    backups_included: formData.backups_included,
                },
                is_active: true,
            };

            await axios.post('/api/hosting/plans', payload);
            alert('Plan creado correctamente');
            setShowModal(false);
            fetchPlans();

            // Reset form
            setFormData({
                name: '',
                plan_type: 'shared',
                billing_cycle: 'annual',
                price: '',
                currency: 'USD',
                disk_gb: '',
                bandwidth_gb: '',
                email_accounts: '',
                databases: '',
                ssl_included: true,
                backups_included: true,
            });
        } catch (error) {
            alert('Error al crear plan');
        }
    };

    if (loading) return <div className="p-8 text-center">Cargando planes...</div>;

    return (
        <div className="animate-fadeIn">
            <PageHeader
                title="Planes de Hosting"
                subtitle="Catálogo de planes disponibles"
                actions={
                    <button onClick={() => setShowModal(true)} className="btn btn-primary">
                        ➕ Nuevo Plan
                    </button>
                }
            />

            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {plans.length === 0 ? (
                    <div className="col-span-3 text-center p-8 text-slate-500">
                        No hay planes creados. Haz clic en "Nuevo Plan" para comenzar.
                    </div>
                ) : (
                    plans.map((plan) => (
                        <div key={plan.id} className="card hover:border-primary-500 transition-colors">
                            <div className="flex justify-between items-start mb-2">
                                <h3 className="text-lg font-bold">{plan.name}</h3>
                                <span className="badge badge-primary text-xs">{plan.plan_type}</span>
                            </div>
                            <div className="text-3xl font-bold text-primary-400 mb-4">
                                {plan.currency} {plan.price}
                                <span className="text-sm text-slate-400">/{plan.billing_cycle}</span>
                            </div>
                            <div className="text-sm text-slate-400 space-y-1">
                                {plan.features_json && Object.entries(plan.features_json).map(([key, value]: any) => (
                                    <div key={key} className="flex justify-between">
                                        <span>✓ {key.replace(/_/g, ' ')}</span>
                                        <span className="text-white font-medium">{typeof value === 'boolean' ? (value ? 'Sí' : 'No') : value}</span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    ))
                )}
            </div>

            {/* Modal Crear Plan - Estilo Marketing */}
            {showModal && (
                <div style={{
                    position: 'fixed',
                    inset: 0,
                    background: 'rgba(0, 0, 0, 0.7)',
                    backdropFilter: 'blur(4px)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 9999,
                    padding: '1rem'
                }} onClick={() => setShowModal(false)}>
                    <div className="card" style={{
                        maxWidth: '600px',
                        width: '100%',
                        maxHeight: '90vh',
                        overflowY: 'auto'
                    }} onClick={(e) => e.stopPropagation()}>
                        <div style={{ padding: '1.5rem', borderBottom: '1px solid var(--border-color)' }}>
                            <h2 style={{ fontSize: '1.5rem', fontWeight: 700, color: 'var(--text-primary)' }}>
                                📋 Nuevo Plan de Hosting
                            </h2>
                            <p style={{ fontSize: '0.9rem', color: 'var(--text-muted)', marginTop: '0.5rem' }}>
                                Crea un nuevo plan de hosting con sus características
                            </p>
                        </div>
                        <form onSubmit={handleSubmit} style={{ padding: '1.5rem' }}>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Nombre del plan
                                    </label>
                                    <input
                                        type="text"
                                        required
                                        className="input"
                                        placeholder="Ej: Hosting Básico"
                                        value={formData.name}
                                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Tipo de plan
                                    </label>
                                    <select
                                        className="input"
                                        value={formData.plan_type}
                                        onChange={(e) => setFormData({ ...formData, plan_type: e.target.value })}
                                    >
                                        <option value="shared">Shared</option>
                                        <option value="vps">VPS</option>
                                        <option value="dedicated">Dedicado</option>
                                        <option value="wordpress">WordPress</option>
                                        <option value="reseller">Reseller</option>
                                        <option value="cloud">Cloud</option>
                                        <option value="other">Otro</option>
                                    </select>
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Precio
                                    </label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        required
                                        className="input"
                                        placeholder="99.99"
                                        value={formData.price}
                                        onChange={(e) => setFormData({ ...formData, price: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Ciclo de facturación
                                    </label>
                                    <select
                                        className="input"
                                        value={formData.billing_cycle}
                                        onChange={(e) => setFormData({ ...formData, billing_cycle: e.target.value })}
                                    >
                                        <option value="monthly">Mensual</option>
                                        <option value="quarterly">Trimestral</option>
                                        <option value="semiannual">Semestral</option>
                                        <option value="annual">Anual</option>
                                        <option value="biennial">Bienal</option>
                                    </select>
                                </div>

                                {/* Características */}
                                <div style={{ borderTop: '1px solid var(--border-color)', paddingTop: '1rem', marginTop: '0.5rem' }}>
                                    <h4 style={{ fontSize: '0.9rem', fontWeight: 600, marginBottom: '1rem', color: 'var(--text-muted)' }}>
                                        Características del plan
                                    </h4>
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                                        <div>
                                            <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.875rem' }}>
                                                Disco (GB)
                                            </label>
                                            <input
                                                type="number"
                                                className="input"
                                                placeholder="50"
                                                value={formData.disk_gb}
                                                onChange={(e) => setFormData({ ...formData, disk_gb: e.target.value })}
                                            />
                                        </div>
                                        <div>
                                            <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.875rem' }}>
                                                Ancho de banda (GB)
                                            </label>
                                            <input
                                                type="number"
                                                className="input"
                                                placeholder="1000"
                                                value={formData.bandwidth_gb}
                                                onChange={(e) => setFormData({ ...formData, bandwidth_gb: e.target.value })}
                                            />
                                        </div>
                                        <div>
                                            <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.875rem' }}>
                                                Cuentas de email
                                            </label>
                                            <input
                                                type="number"
                                                className="input"
                                                placeholder="10"
                                                value={formData.email_accounts}
                                                onChange={(e) => setFormData({ ...formData, email_accounts: e.target.value })}
                                            />
                                        </div>
                                        <div>
                                            <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.875rem' }}>
                                                Bases de datos
                                            </label>
                                            <input
                                                type="number"
                                                className="input"
                                                placeholder="5"
                                                value={formData.databases}
                                                onChange={(e) => setFormData({ ...formData, databases: e.target.value })}
                                            />
                                        </div>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                            <input
                                                type="checkbox"
                                                id="ssl"
                                                checked={formData.ssl_included}
                                                onChange={(e) => setFormData({ ...formData, ssl_included: e.target.checked })}
                                            />
                                            <label htmlFor="ssl" style={{ fontSize: '0.875rem' }}>SSL incluido</label>
                                        </div>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                            <input
                                                type="checkbox"
                                                id="backups"
                                                checked={formData.backups_included}
                                                onChange={(e) => setFormData({ ...formData, backups_included: e.target.checked })}
                                            />
                                            <label htmlFor="backups" style={{ fontSize: '0.875rem' }}>Backups incluidos</label>
                                        </div>
                                    </div>
                                </div>

                                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end', marginTop: '1rem' }}>
                                    <button type="button" className="btn btn-secondary" onClick={() => setShowModal(false)}>
                                        Cancelar
                                    </button>
                                    <button type="submit" className="btn btn-primary">
                                        💾 Guardar Plan
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
