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

export default function Configuracion() {
    const { user, refreshUser } = useUser();
    const { theme } = useTheme();
    const isDarkMode = theme === 'dark';

    const isAdmin = user?.rol === 'admin';

    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState({ type: '', text: '' });
    const [activeTab, setActiveTab] = useState<'perfil' | 'password'>('perfil');

    const [formData, setFormData] = useState({
        nombre: '',
        apellido: '',
        telefono: '',
        horario: 'manana',
    });

    useEffect(() => {
        if (user) {
            setFormData({
                nombre: user.nombre || '',
                apellido: user.apellido || '',
                telefono: user.telefono || '',
                horario: user.horario || 'manana',
            });
        }
    }, [user]);

    const horarioOptions = isAdmin
        ? [
            { value: '24_7', label: '🕐 24/7 (Administrador)' },
            { value: 'manana', label: '🌅 Mañana (7:00 AM - 2:00 PM)' },
            { value: 'tarde', label: '🌆 Tarde (2:00 PM - 9:00 PM)' },
        ]
        : [
            { value: 'manana', label: '🌅 Mañana (7:00 AM - 2:00 PM)' },
            { value: 'tarde', label: '🌆 Tarde (2:00 PM - 9:00 PM)' },
        ];

    const [passwordData, setPasswordData] = useState({
        current_password: '',
        new_password: '',
        new_password_confirmation: '',
    });

    const handleProfileChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setPasswordData({ ...passwordData, [e.target.name]: e.target.value });
    };

    const handleProfileSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setMessage({ type: '', text: '' });

        try {
            const res = await axios.put('/user/profile', formData);
            if (res.data.success) {
                setMessage({ type: 'success', text: res.data.message });
                refreshUser();
            }
        } catch (error: any) {
            setMessage({ type: 'error', text: error.response?.data?.message || 'Error al actualizar perfil' });
        } finally {
            setLoading(false);
        }
    };

    const handlePasswordSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setMessage({ type: '', text: '' });

        if (passwordData.new_password !== passwordData.new_password_confirmation) {
            setMessage({ type: 'error', text: 'Las contraseñas no coinciden' });
            setLoading(false);
            return;
        }

        try {
            const res = await axios.put('/user/password', {
                current_password: passwordData.current_password,
                new_password: passwordData.new_password,
            });
            if (res.data.success) {
                setMessage({ type: 'success', text: res.data.message });
                setPasswordData({ current_password: '', new_password: '', new_password_confirmation: '' });
            }
        } catch (error: any) {
            setMessage({ type: 'error', text: error.response?.data?.message || 'Error al cambiar contraseña' });
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="space-y-6">
            <div>
                <h1 className={`text-3xl font-bold ${isDarkMode ? 'text-white' : 'text-gray-900'}`}>
                    ⚙️ Configuración
                </h1>
                <p className={`${isDarkMode ? 'text-gray-400' : 'text-gray-600'} mt-1`}>
                    Gestiona tu perfil y preferencias
                </p>
            </div>

            {/* Tabs */}
            <div className={`flex gap-2 p-1 rounded-xl ${isDarkMode ? 'bg-gray-800' : 'bg-gray-100'} w-full md:w-fit`}>
                <button
                    onClick={() => setActiveTab('perfil')}
                    className={`flex-1 md:flex-none px-6 py-2 rounded-lg font-semibold transition-all ${activeTab === 'perfil'
                            ? isDarkMode ? 'bg-blue-600 text-white' : 'bg-white text-gray-900 shadow'
                            : isDarkMode ? 'text-gray-400 hover:text-white' : 'text-gray-600 hover:text-gray-900'
                        }`}
                >
                    👤 Mi Perfil
                </button>
                <button
                    onClick={() => setActiveTab('password')}
                    className={`flex-1 md:flex-none px-6 py-2 rounded-lg font-semibold transition-all ${activeTab === 'password'
                            ? isDarkMode ? 'bg-blue-600 text-white' : 'bg-white text-gray-900 shadow'
                            : isDarkMode ? 'text-gray-400 hover:text-white' : 'text-gray-600 hover:text-gray-900'
                        }`}
                >
                    🔒 Contraseña
                </button>
            </div>

            {/* Mensaje */}
            {message.text && (
                <div className={`p-4 rounded-xl border ${message.type === 'success'
                        ? isDarkMode ? 'bg-green-900/30 border-green-700 text-green-400' : 'bg-green-50 border-green-500 text-green-700'
                        : isDarkMode ? 'bg-red-900/30 border-red-700 text-red-400' : 'bg-red-50 border-red-500 text-red-700'
                    }`}>
                    {message.text}
                </div>
            )}

            {/* Perfil */}
            {activeTab === 'perfil' && (
                <div className={`rounded-2xl p-8 ${isDarkMode ? 'bg-gray-800/50 border border-gray-700/50' : 'bg-white border border-gray-200'} shadow-lg`}>
                    <h2 className={`text-xl font-bold ${isDarkMode ? 'text-white' : 'text-gray-900'} mb-6`}>
                        📝 Información Personal
                    </h2>

                    <form onSubmit={handleProfileSubmit} className="space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            {/* Nombre */}
                            <div>
                                <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                    👤 Nombre
                                </label>
                                <input
                                    type="text"
                                    name="nombre"
                                    value={formData.nombre}
                                    onChange={handleProfileChange}
                                    className={`w-full px-4 py-3 rounded-xl border-2 transition-all outline-none ${isDarkMode
                                            ? 'bg-gray-700 border-gray-600 text-white focus:border-blue-500'
                                            : 'bg-white border-gray-200 text-gray-900 focus:border-blue-500'
                                        }`}
                                />
                            </div>

                            {/* Apellido */}
                            <div>
                                <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                    👤 Apellido
                                </label>
                                <input
                                    type="text"
                                    name="apellido"
                                    value={formData.apellido}
                                    onChange={handleProfileChange}
                                    className={`w-full px-4 py-3 rounded-xl border-2 transition-all outline-none ${isDarkMode
                                            ? 'bg-gray-700 border-gray-600 text-white focus:border-blue-500'
                                            : 'bg-white border-gray-200 text-gray-900 focus:border-blue-500'
                                        }`}
                                />
                            </div>

                            {/* Teléfono */}
                            <div>
                                <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                    📱 Teléfono
                                </label>
                                <input
                                    type="text"
                                    name="telefono"
                                    value={formData.telefono}
                                    onChange={handleProfileChange}
                                    placeholder="Ingresa tu número de teléfono"
                                    className={`w-full px-4 py-3 rounded-xl border-2 transition-all outline-none ${isDarkMode
                                            ? 'bg-gray-700 border-gray-600 text-white placeholder-gray-500 focus:border-blue-500'
                                            : 'bg-white border-gray-200 text-gray-900 placeholder-gray-400 focus:border-blue-500'
                                        }`}
                                />
                            </div>

                            {/* Horario */}
                            <div>
                                <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                    🕐 Horario
                                </label>
                                <select
                                    name="horario"
                                    value={formData.horario}
                                    onChange={handleProfileChange}
                                    className={`w-full px-4 py-3 rounded-xl border-2 transition-all outline-none ${isDarkMode
                                            ? 'bg-gray-700 border-gray-600 text-white focus:border-blue-500'
                                            : 'bg-white border-gray-200 text-gray-900 focus:border-blue-500'
                                        }`}
                                >
                                    {horarioOptions.map(option => (
                                        <option key={option.value} value={option.value}>
                                            {option.label}
                                        </option>
                                    ))}
                                </select>
                            </div>
                        </div>

                        {/* Email (solo lectura) */}
                        <div>
                            <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                📧 Email
                            </label>
                            <input
                                type="email"
                                value={user?.email || ''}
                                disabled
                                className={`w-full px-4 py-3 rounded-xl border-2 ${isDarkMode
                                        ? 'bg-gray-800 border-gray-700 text-gray-500'
                                        : 'bg-gray-100 border-gray-200 text-gray-500'
                                    } cursor-not-allowed`}
                            />
                            <p className={`text-xs mt-1 ${isDarkMode ? 'text-gray-500' : 'text-gray-400'}`}>
                                El email no se puede modificar
                            </p>
                        </div>

                        {/* Rol */}
                        <div>
                            <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                🏷️ Rol
                            </label>
                            <input
                                type="text"
                                value={user?.rol === 'admin' ? 'Administrador' : user?.rol || ''}
                                disabled
                                className={`w-full px-4 py-3 rounded-xl border-2 ${isDarkMode
                                        ? 'bg-gray-800 border-gray-700 text-gray-500'
                                        : 'bg-gray-100 border-gray-200 text-gray-500'
                                    } capitalize cursor-not-allowed`}
                            />
                        </div>

                        <button
                            type="submit"
                            disabled={loading}
                            className={`px-8 py-3 rounded-xl font-bold transition-all transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed ${isDarkMode
                                    ? 'bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:from-blue-700 hover:to-purple-700'
                                    : 'bg-gradient-to-r from-blue-600 to-cyan-500 text-white hover:from-blue-700 hover:to-cyan-600'
                                }`}
                        >
                            {loading ? 'Guardando...' : '💾 Guardar Cambios'}
                        </button>
                    </form>
                </div>
            )}

            {/* Contraseña */}
            {activeTab === 'password' && (
                <div className={`rounded-2xl p-8 ${isDarkMode ? 'bg-gray-800/50 border border-gray-700/50' : 'bg-white border border-gray-200'} shadow-lg`}>
                    <h2 className={`text-xl font-bold ${isDarkMode ? 'text-white' : 'text-gray-900'} mb-6`}>
                        🔐 Cambiar Contraseña
                    </h2>

                    <form onSubmit={handlePasswordSubmit} className="space-y-6 max-w-xl">
                        {/* Contraseña actual */}
                        <div>
                            <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                🔑 Contraseña Actual
                            </label>
                            <input
                                type="password"
                                name="current_password"
                                value={passwordData.current_password}
                                onChange={handlePasswordChange}
                                required
                                className={`w-full px-4 py-3 rounded-xl border-2 transition-all outline-none ${isDarkMode
                                        ? 'bg-gray-700 border-gray-600 text-white placeholder-gray-500 focus:border-blue-500'
                                        : 'bg-white border-gray-200 text-gray-900 placeholder-gray-400 focus:border-blue-500'
                                    }`}
                                placeholder="Ingresa tu contraseña actual"
                            />
                        </div>

                        {/* Nueva contraseña */}
                        <div>
                            <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                🆕 Nueva Contraseña
                            </label>
                            <input
                                type="password"
                                name="new_password"
                                value={passwordData.new_password}
                                onChange={handlePasswordChange}
                                required
                                minLength={8}
                                className={`w-full px-4 py-3 rounded-xl border-2 transition-all outline-none ${isDarkMode
                                        ? 'bg-gray-700 border-gray-600 text-white placeholder-gray-500 focus:border-blue-500'
                                        : 'bg-white border-gray-200 text-gray-900 placeholder-gray-400 focus:border-blue-500'
                                    }`}
                                placeholder="Mínimo 8 caracteres"
                            />
                        </div>

                        {/* Confirmar contraseña */}
                        <div>
                            <label className={`block text-sm font-semibold mb-2 ${isDarkMode ? 'text-gray-300' : 'text-gray-700'}`}>
                                ✅ Confirmar Nueva Contraseña
                            </label>
                            <input
                                type="password"
                                name="new_password_confirmation"
                                value={passwordData.new_password_confirmation}
                                onChange={handlePasswordChange}
                                required
                                className={`w-full px-4 py-3 rounded-xl border-2 transition-all outline-none ${isDarkMode
                                        ? 'bg-gray-700 border-gray-600 text-white placeholder-gray-500 focus:border-blue-500'
                                        : 'bg-white border-gray-200 text-gray-900 placeholder-gray-400 focus:border-blue-500'
                                    }`}
                                placeholder="Repite la nueva contraseña"
                            />
                        </div>

                        <button
                            type="submit"
                            disabled={loading}
                            className={`px-8 py-3 rounded-xl font-bold transition-all transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed ${isDarkMode
                                    ? 'bg-gradient-to-r from-red-600 to-pink-600 text-white hover:from-red-700 hover:to-pink-700'
                                    : 'bg-gradient-to-r from-red-500 to-rose-500 text-white hover:from-red-600 hover:to-rose-600'
                                }`}
                        >
                            {loading ? 'Cambiando...' : '🔒 Cambiar Contraseña'}
                        </button>
                    </form>
                </div>
            )}
        </div>
    );
}
