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

interface Plan {
    id: number;
    name: string;
    app_type: string;
    pricing_model: string;
    base_price?: number;
    hourly_rate?: number;
    currency: string;
    sla_days?: number;
    is_active: boolean;
}

const appTypeLabels: Record<string, string> = {
    web: '🌐 Web',
    desktop: '💻 Desktop',
    android: '🤖 Android',
    ios: '🍎 iOS',
    cross_platform: '📱 Multiplataforma',
};

const pricingModelLabels: Record<string, string> = {
    fixed: 'Precio Fijo',
    hourly: 'Por Hora',
    retainer: 'Retainer',
};

export default function AppDevPlans() {
    const [plans, setPlans] = useState<Plan[]>([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [formData, setFormData] = useState({
        name: '',
        app_type: 'web',
        pricing_model: 'fixed',
        base_price: '',
        hourly_rate: '',
        sla_days: '',
        is_active: true,
    });

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

    useEffect(() => {
        const handleEscape = (e: KeyboardEvent) => {
            if (e.key === 'Escape') setShowModal(false);
        };
        if (showModal) {
            document.addEventListener('keydown', handleEscape);
            return () => document.removeEventListener('keydown', handleEscape);
        }
    }, [showModal]);


    const fetchPlans = async () => {
        try {
            const res = await axios.get('/api/app-dev/plans');
            setPlans(res.data);
        } catch (error) {
            console.error('Error cargando planes:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            await axios.post('/api/app-dev/plans', formData);
            setShowModal(false);
            fetchPlans();
            setFormData({
                name: '',
                app_type: 'web',
                pricing_model: 'fixed',
                base_price: '',
                hourly_rate: '',
                sla_days: '',
                is_active: true,
            });
        } catch (error) {
            console.error('Error creando plan:', error);
            alert('Error al crear el plan');
        }
    };

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

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

            <div className="table-container">
                <div className="table-header">
                    <h2 className="table-title">📋 Planes Disponibles</h2>
                </div>
                <div className="table-wrapper">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>Nombre</th>
                                <th>Tipo</th>
                                <th>Modelo de Precio</th>
                                <th>Precio Base</th>
                                <th>Tarifa/Hora</th>
                                <th>SLA (días)</th>
                                <th>Estado</th>
                            </tr>
                        </thead>
                        <tbody>
                            {plans.length === 0 ? (
                                <tr>
                                    <td colSpan={7} style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-muted)' }}>
                                        No hay planes registrados
                                    </td>
                                </tr>
                            ) : (
                                plans.map((plan) => (
                                    <tr key={plan.id}>
                                        <td style={{ fontWeight: 600 }}>{plan.name}</td>
                                        <td>{appTypeLabels[plan.app_type]}</td>
                                        <td>
                                            <span className="badge badge-default">
                                                {pricingModelLabels[plan.pricing_model]}
                                            </span>
                                        </td>
                                        <td>
                                            {plan.base_price
                                                ? `$${plan.base_price} ${plan.currency}`
                                                : '-'}
                                        </td>
                                        <td>
                                            {plan.hourly_rate
                                                ? `$${plan.hourly_rate}/h`
                                                : '-'}
                                        </td>
                                        <td>{plan.sla_days ? `${plan.sla_days} días` : '-'}</td>
                                        <td>
                                            <span className={`badge ${plan.is_active ? 'badge-success' : 'badge-default'}`}>
                                                {plan.is_active ? '✅ Activo' : '⏸️ Inactivo'}
                                            </span>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Modal Crear Plan */}
            {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)', position: 'relative' }}>
                            <button
                                type="button"
                                onClick={() => setShowModal(false)}
                                style={{
                                    position: 'absolute',
                                    top: '1rem',
                                    right: '1rem',
                                    background: 'transparent',
                                    border: 'none',
                                    fontSize: '1.5rem',
                                    cursor: 'pointer',
                                    color: 'var(--text-muted)',
                                    padding: '0.25rem',
                                    lineHeight: 1,
                                }}
                            >
                                ✕
                            </button>
                            <h2 style={{ fontSize: '1.5rem', fontWeight: 700, color: 'var(--text-primary)' }}>
                                📋 Nuevo Plan
                            </h2>
                            <p style={{ fontSize: '0.9rem', color: 'var(--text-muted)', marginTop: '0.5rem' }}>
                                Crea un nuevo plan de desarrollo
                            </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: App Básica Web"
                                        value={formData.name}
                                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Tipo de aplicación
                                    </label>
                                    <select
                                        className="input"
                                        value={formData.app_type}
                                        onChange={(e) => setFormData({ ...formData, app_type: e.target.value })}
                                    >
                                        <option value="web">🌐 Web</option>
                                        <option value="desktop">💻 Desktop</option>
                                        <option value="android">🤖 Android</option>
                                        <option value="ios">🍎 iOS</option>
                                        <option value="cross_platform">📱 Multiplataforma</option>
                                    </select>
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Modelo de precio
                                    </label>
                                    <select
                                        className="input"
                                        value={formData.pricing_model}
                                        onChange={(e) => setFormData({ ...formData, pricing_model: e.target.value })}
                                    >
                                        <option value="fixed">Precio Fijo</option>
                                        <option value="hourly">Por Hora</option>
                                        <option value="retainer">Retainer</option>
                                    </select>
                                </div>
                                {formData.pricing_model === 'fixed' && (
                                    <div>
                                        <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                            Precio base (USD)
                                        </label>
                                        <input
                                            type="number"
                                            step="0.01"
                                            className="input"
                                            placeholder="5000.00"
                                            value={formData.base_price}
                                            onChange={(e) => setFormData({ ...formData, base_price: e.target.value })}
                                        />
                                    </div>
                                )}
                                {formData.pricing_model === 'hourly' && (
                                    <div>
                                        <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                            Tarifa por hora (USD)
                                        </label>
                                        <input
                                            type="number"
                                            step="0.01"
                                            className="input"
                                            placeholder="50.00"
                                            value={formData.hourly_rate}
                                            onChange={(e) => setFormData({ ...formData, hourly_rate: e.target.value })}
                                        />
                                    </div>
                                )}
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        SLA (días de entrega)
                                    </label>
                                    <input
                                        type="number"
                                        className="input"
                                        placeholder="30"
                                        value={formData.sla_days}
                                        onChange={(e) => setFormData({ ...formData, sla_days: e.target.value })}
                                    />
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                    <input
                                        type="checkbox"
                                        id="is_active"
                                        checked={formData.is_active}
                                        onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                                    />
                                    <label htmlFor="is_active" style={{ fontSize: '0.875rem' }}>Plan activo</label>
                                </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>
    );
}
