import React, { useState, useEffect } from 'react';
import { useTheme } from '../../context/ThemeContext';
import { useUser } from '../../context/UserContext';
import axios from 'axios';

interface Estudio {
    id: number;
    nombre: string;
    descripcion: string;
    categoria: string;
    codigo: string;
    precio: number;
    duracion_minutos: number;
    estado: string;
}

interface Categoria {
    id: number;
    nombre: string;
    descripcion: string;
    icono: string;
    color: string;
    estado: string;
}

export default function Examenes() {
    const { theme } = useTheme();
    const { user } = useUser();
    const isDarkMode = theme === 'dark';
    const isAdmin = user?.rol === 'admin';

    const [estudios, setEstudios] = useState<Estudio[]>([]);
    const [categorias, setCategorias] = useState<Categoria[]>([]);
    const [loading, setLoading] = useState(true);
    const [buscar, setBuscar] = useState('');
    const [filtroCategoria, setFiltroCategoria] = useState('');
    const [mostrarModal, setMostrarModal] = useState(false);
    const [estudioEditando, setEstudioEditando] = useState<Estudio | null>(null);
    const [guardando, setGuardando] = useState(false);
    const [mensaje, setMensaje] = useState({ tipo: '', texto: '' });

    const [formData, setFormData] = useState({
        nombre: '',
        descripcion: '',
        categoria: '',
        codigo: '',
        precio: 0,
        duracion_minutos: 30,
    });

    useEffect(() => {
        cargarCategorias();
        cargarEstudios();
    }, [buscar, filtroCategoria]);

    const cargarCategorias = async () => {
        try {
            const res = await axios.get('/categorias/activas');
            setCategorias(res.data.data);
            if (res.data.data.length > 0 && !formData.categoria) {
                setFormData(prev => ({ ...prev, categoria: res.data.data[0].nombre }));
            }
        } catch (error) {
            console.error('Error cargando categorías:', error);
        }
    };

    const cargarEstudios = async () => {
        setLoading(true);
        try {
            const params: any = {};
            if (buscar) params.buscar = buscar;
            if (filtroCategoria) params.categoria = filtroCategoria;

            const res = await axios.get('/estudios', { params });
            setEstudios(res.data.data);
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false);
        }
    };

    const abrirModalNuevo = () => {
        setEstudioEditando(null);
        setFormData({ nombre: '', descripcion: '', categoria: 'Análisis Clínicos', codigo: '', precio: 0, duracion_minutos: 30 });
        setMensaje({ tipo: '', texto: '' });
        setMostrarModal(true);
    };

    const abrirModalEditar = (estudio: Estudio) => {
        setEstudioEditando(estudio);
        setFormData({
            nombre: estudio.nombre,
            descripcion: estudio.descripcion || '',
            categoria: estudio.categoria,
            codigo: estudio.codigo,
            precio: estudio.precio,
            duracion_minutos: estudio.duracion_minutos,
        });
        setMensaje({ tipo: '', texto: '' });
        setMostrarModal(true);
    };

    const guardarEstudio = async (e: React.FormEvent) => {
        e.preventDefault();
        setGuardando(true);
        setMensaje({ tipo: '', texto: '' });

        try {
            if (estudioEditando) {
                await axios.put(`/estudios/${estudioEditando.id}`, formData);
                setMensaje({ tipo: 'success', texto: 'Estudio actualizado' });
            } else {
                await axios.post('/estudios', formData);
                setMensaje({ tipo: 'success', texto: 'Estudio creado' });
            }
            cargarEstudios();
            setTimeout(() => setMostrarModal(false), 1000);
        } catch (error: any) {
            setMensaje({ tipo: 'error', texto: error.response?.data?.message || 'Error al guardar' });
        } finally {
            setGuardando(false);
        }
    };

    const cambiarEstado = async (estudio: Estudio) => {
        const nuevoEstado = estudio.estado === 'activo' ? 'inactivo' : 'activo';
        try {
            await axios.put(`/estudios/${estudio.id}`, { estado: nuevoEstado });
            cargarEstudios();
        } catch (error) { console.error(error); }
    };

    const eliminarEstudio = async (id: number) => {
        if (!confirm('¿Eliminar estudio?')) return;
        try { await axios.delete(`/estudios/${id}`); cargarEstudios(); } catch (error) { console.error(error); }
    };

    const getCategoriaColor = (categoria: string) => {
        const colors: any = {
            'Análisis Clínicos': isDarkMode ? 'bg-blue-900 text-blue-400 border-blue-700' : 'bg-blue-100 text-blue-700 border-blue-300',
            'Rayos X': isDarkMode ? 'bg-gray-700 text-gray-300 border-gray-600' : 'bg-gray-200 text-gray-700 border-gray-300',
            'Ecografías': isDarkMode ? 'bg-pink-900 text-pink-400 border-pink-700' : 'bg-pink-100 text-pink-700 border-pink-300',
            'Cardiología': isDarkMode ? 'bg-red-900 text-red-400 border-red-700' : 'bg-red-100 text-red-700 border-red-300',
            'Laboratorio': isDarkMode ? 'bg-green-900 text-green-400 border-green-700' : 'bg-green-100 text-green-700 border-green-300',
        };
        return colors[categoria] || (isDarkMode ? 'bg-gray-700 text-gray-300 border-gray-600' : 'bg-gray-100 text-gray-700 border-gray-300');
    };

    const formatPrecio = (precio: number) => {
        return 'Bs. ' + new Intl.NumberFormat('es-BO').format(precio);
    };

    return (
        <div className="space-y-6">
            <div>
                <h1 className={`text-3xl font-bold ${isDarkMode ? 'text-white' : 'text-gray-900'}`}>
                    🔬 Catálogo de Estudios
                </h1>
                <p className={`${isDarkMode ? 'text-gray-400' : 'text-gray-600'} mt-1`}>
                    Gestión del catálogo de estudios y análisis clínicos
                </p>
            </div>

            <div className={`rounded-2xl p-6 ${isDarkMode ? 'bg-gray-800/50 border border-gray-700/50' : 'bg-white border border-gray-200'} shadow-lg`}>
                <div className="flex flex-col md:flex-row gap-4 items-center justify-between mb-6">
                    <div className="flex flex-col md:flex-row gap-3 items-center w-full md:w-auto">
                        <input type="text" placeholder="Buscar estudio..." value={buscar} onChange={(e) => setBuscar(e.target.value)}
                            className={`w-full md:w-auto px-4 py-2 rounded-xl border-2 outline-none ${isDarkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-200'}`} />
                        <select value={filtroCategoria} onChange={(e) => setFiltroCategoria(e.target.value)}
                            className={`w-full md:w-auto px-4 py-2 rounded-xl border-2 outline-none ${isDarkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-200'}`}>
                            <option value="">Todas las categorías</option>
                            {categorias.map((cat: Categoria) => <option key={cat.id} value={cat.nombre}>{cat.nombre}</option>)}
                        </select>
                    </div>
                    {isAdmin && (
                        <button onClick={abrirModalNuevo}
                            className="w-full md:w-auto px-6 py-2 rounded-xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors">
                            ➕ Nuevo Estudio
                        </button>
                    )}
                </div>

                {loading ? (
                    <div className="text-center py-8">
                        <div className={`animate-spin rounded-full h-12 w-12 border-b-2 mx-auto ${isDarkMode ? 'border-white' : 'border-blue-600'}`}></div>
                    </div>
                ) : (
                    <>
                        {/* Mobile Card View */}
                        <div className="md:hidden space-y-4">
                            {estudios.length === 0 ? (
                                <div className={`text-center p-8 ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>Sin estudios registrados</div>
                            ) : (
                                estudios.map((estudio) => (
                                    <div key={estudio.id} className={`p-4 rounded-xl ${isDarkMode ? 'bg-gray-800 border border-gray-700' : 'bg-white border border-gray-100'} shadow-sm`}>
                                        <div className="flex justify-between items-start mb-2">
                                            <div className="flex-1 pr-2">
                                                <div className="flex items-center gap-2">
                                                    <span className={`font-mono text-xs ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>{estudio.codigo}</span>
                                                    <span className={`px-2 py-0.5 rounded textxs border ${getCategoriaColor(estudio.categoria)}`}>
                                                        {estudio.categoria}
                                                    </span>
                                                </div>
                                                <h3 className={`font-bold text-lg mt-1 ${isDarkMode ? 'text-white' : 'text-gray-900'} break-words`}>{estudio.nombre}</h3>
                                            </div>
                                            <div className="flex gap-2">
                                                {isAdmin && (
                                                    <>
                                                        <button onClick={() => abrirModalEditar(estudio)} className={`p-2 rounded-lg ${isDarkMode ? 'bg-gray-700 text-gray-300' : 'bg-gray-100 text-gray-600'}`}>✏️</button>
                                                        <button onClick={() => eliminarEstudio(estudio.id)} className={`p-2 rounded-lg ${isDarkMode ? 'bg-red-900/30 text-red-400' : 'bg-red-100 text-red-600'}`}>🗑️</button>
                                                    </>
                                                )}
                                            </div>
                                        </div>

                                        {estudio.descripcion && <p className={`text-sm mb-3 ${isDarkMode ? 'text-gray-400' : 'text-gray-500'} break-words`}>{estudio.descripcion}</p>}

                                        <div className="flex items-center justify-between mt-4 pt-3 border-t dark:border-gray-700">
                                            <span className={`text-lg font-bold ${isDarkMode ? 'text-green-400' : 'text-green-700'}`}>{formatPrecio(estudio.precio)}</span>
                                            <div className="flex items-center gap-3">
                                                <span className={`text-sm ${isDarkMode ? 'text-gray-400' : 'text-gray-600'}`}>⏱️ {estudio.duracion_minutos} min</span>
                                                <button onClick={() => cambiarEstado(estudio)}
                                                    className={`px-3 py-1 rounded-lg text-xs font-semibold ${estudio.estado === 'activo' ? (isDarkMode ? 'bg-green-900 text-green-400' : 'bg-green-100 text-green-700') : (isDarkMode ? 'bg-red-900 text-red-400' : 'bg-red-100 text-red-700')}`}>
                                                    {estudio.estado}
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>

                        {/* Desktop Table View */}
                        <div className="hidden md:block overflow-x-auto">
                            <table className="w-full">
                                <thead>
                                    <tr className={isDarkMode ? 'text-gray-400' : 'text-gray-600'}>
                                        <th className="text-left p-3">Código</th>
                                        <th className="text-left p-3">Estudio</th>
                                        <th className="text-left p-3">Categoría</th>
                                        <th className="text-left p-3">Precio</th>
                                        <th className="text-left p-3">Duración</th>
                                        <th className="text-left p-3">Estado</th>
                                        <th className="text-center p-3">Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {estudios.length === 0 ? (
                                        <tr><td colSpan={7} className={`text-center p-8 ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>Sin estudios registrados</td></tr>
                                    ) : (
                                        estudios.map((estudio) => (
                                            <tr key={estudio.id} className={`border-t ${isDarkMode ? 'border-gray-700' : 'border-gray-200'}`}>
                                                <td className={`p-3 font-mono ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>{estudio.codigo}</td>
                                                <td className="p-3">
                                                    <div>
                                                        <p className={`font-semibold ${isDarkMode ? 'text-white' : 'text-gray-900'}`}>{estudio.nombre}</p>
                                                        {estudio.descripcion && <p className={`text-xs ${isDarkMode ? 'text-gray-500' : 'text-gray-500'}`}>{estudio.descripcion}</p>}
                                                    </div>
                                                </td>
                                                <td className="p-3">
                                                    <span className={`px-2 py-1 rounded text-xs border ${getCategoriaColor(estudio.categoria)}`}>
                                                        {estudio.categoria}
                                                    </span>
                                                </td>
                                                <td className={`p-3 font-semibold ${isDarkMode ? 'text-green-400' : 'text-green-700'}`}>{formatPrecio(estudio.precio)}</td>
                                                <td className={`p-3 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>{estudio.duracion_minutos} min</td>
                                                <td className="p-3">
                                                    <button onClick={() => cambiarEstado(estudio)}
                                                        className={`px-3 py-1 rounded-lg text-xs font-semibold ${estudio.estado === 'activo' ? (isDarkMode ? 'bg-green-900 text-green-400' : 'bg-green-100 text-green-700') : (isDarkMode ? 'bg-red-900 text-red-400' : 'bg-red-100 text-red-700')}`}>
                                                        {estudio.estado}
                                                    </button>
                                                </td>
                                                <td className="p-3">
                                                    <div className="flex justify-center gap-2">
                                                        {isAdmin && (<>
                                                            <button onClick={() => abrirModalEditar(estudio)} className={`p-2 rounded-lg ${isDarkMode ? 'hover:bg-gray-700' : 'hover:bg-gray-100'}`}>✏️</button>
                                                            <button onClick={() => eliminarEstudio(estudio.id)} className={`p-2 rounded-lg ${isDarkMode ? 'hover:bg-gray-700 text-red-400' : 'hover:bg-gray-100 text-red-600'}`}>🗑️</button>
                                                        </>)}
                                                    </div>
                                                </td>
                                            </tr>
                                        ))
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </>
                )}
            </div>

            {mostrarModal && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
                    <div className={`rounded-2xl p-6 w-full max-w-md ${isDarkMode ? 'bg-gray-800 border border-gray-700' : 'bg-white border border-gray-200'}`}>
                        <h2 className={`text-2xl font-bold mb-6 ${isDarkMode ? 'text-white' : 'text-gray-900'}`}>
                            {estudioEditando ? '✏️ Editar Estudio' : '➕ Nuevo Estudio'}
                        </h2>
                        {mensaje.texto && (
                            <div className={`mb-4 p-3 rounded ${mensaje.tipo === 'success' ? (isDarkMode ? 'bg-green-900 text-green-400' : 'bg-green-100 text-green-700') : (isDarkMode ? 'bg-red-900 text-red-400' : 'bg-red-100 text-red-700')}`}>
                                {mensaje.texto}
                            </div>
                        )}
                        <form onSubmit={guardarEstudio} className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="col-span-2">
                                    <label className={`block text-sm mb-1 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>Nombre del Estudio *</label>
                                    <input type="text" value={formData.nombre} onChange={(e) => setFormData({ ...formData, nombre: e.target.value })} required
                                        className={`w-full p-2 rounded border ${isDarkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-200'}`} />
                                </div>
                                <div>
                                    <label className={`block text-sm mb-1 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>Código *</label>
                                    <input type="text" value={formData.codigo} onChange={(e) => setFormData({ ...formData, codigo: e.target.value })} required={!estudioEditando} disabled={!!estudioEditando}
                                        className={`w-full p-2 rounded border ${isDarkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-200'} ${estudioEditando ? 'opacity-50' : ''}`} />
                                </div>
                                <div>
                                    <label className={`block text-sm mb-1 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>Categoría *</label>
                                    <select value={formData.categoria} onChange={(e) => setFormData({ ...formData, categoria: e.target.value })}
                                        className={`w-full p-2 rounded border ${isDarkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-200'}`}>
                                        {categorias.map((cat: Categoria) => <option key={cat.id} value={cat.nombre}>{cat.nombre}</option>)}
                                    </select>
                                </div>
                                <div>
                                    <label className={`block text-sm mb-1 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>Precio (Bs.) *</label>
                                    <input type="number" value={formData.precio} onChange={(e) => setFormData({ ...formData, precio: parseFloat(e.target.value) || 0 })} required min="0" step="0.01"
                                        className={`w-full p-2 rounded border ${isDarkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-200'}`} />
                                </div>
                                <div>
                                    <label className={`block text-sm mb-1 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>Duración (min)</label>
                                    <input type="number" value={formData.duracion_minutos} onChange={(e) => setFormData({ ...formData, duracion_minutos: parseInt(e.target.value) || 30 })} min="1"
                                        className={`w-full p-2 rounded border ${isDarkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-200'}`} />
                                </div>
                                <div className="col-span-2">
                                    <label className={`block text-sm mb-1 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>Descripción</label>
                                    <textarea value={formData.descripcion} onChange={(e) => setFormData({ ...formData, descripcion: e.target.value })} rows={2}
                                        className={`w-full p-2 rounded border ${isDarkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-200'}`} />
                                </div>
                            </div>
                            <div className="flex gap-3 pt-4">
                                <button type="button" onClick={() => setMostrarModal(false)} className={`flex-1 p-2 rounded ${isDarkMode ? 'bg-gray-700 text-gray-300' : 'bg-gray-200 text-gray-700'}`}>Cancelar</button>
                                <button type="submit" disabled={guardando} className={`flex-1 p-2 rounded text-white bg-blue-600 disabled:opacity-50`}>
                                    {guardando ? '...' : estudioEditando ? 'Actualizar' : 'Crear'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
