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



interface FormErrors {
    [key: string]: string[];
}

export default function Settings() {
    const { theme, toggleTheme } = useTheme();
    const { user: contextUser, updateUser } = useUser();

    // Profile State
    const [profile, setProfile] = useState<any>(null);
    const [profileData, setProfileData] = useState({
        name: '',
        email: '',
        phone: '',
        position: ''
    });
    const [profileLoading, setProfileLoading] = useState(false);
    const [profileErrors, setProfileErrors] = useState<FormErrors>({});
    const [profileSuccess, setProfileSuccess] = useState('');

    // Password State
    const [passwordData, setPasswordData] = useState({
        current_password: '',
        password: '',
        password_confirmation: ''
    });
    const [passwordLoading, setPasswordLoading] = useState(false);
    const [passwordErrors, setPasswordErrors] = useState<FormErrors>({});
    const [passwordSuccess, setPasswordSuccess] = useState('');

    // Load user profile on mount
    useEffect(() => {
        loadProfile();
    }, []);

    const loadProfile = async () => {
        try {
            const res = await axios.get('/api/me');
            setProfile(res.data.data);
            setProfileData({
                name: res.data.data.name || '',
                email: res.data.data.email || '',
                phone: res.data.data.phone || '',
                position: res.data.data.position || ''
            });
        } catch (error) {
            console.error('Error loading profile:', error);
        }
    };

    const handleProfileSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setProfileLoading(true);
        setProfileErrors({});
        setProfileSuccess('');

        try {
            const res = await axios.put('/api/me/profile', profileData);
            setProfileSuccess(res.data.message || '¡Perfil actualizado!');
            setProfile(res.data.data);

            // Update global user context so header updates immediately
            updateUser(res.data.data);

            // Clear success message after 3 seconds
            setTimeout(() => setProfileSuccess(''), 3000);
        } catch (error: any) {
            console.error("Profile Save Error:", error);
            if (error.response?.status === 422) {
                setProfileErrors(error.response.data.errors || {});
            } else {
                const msg = error.response?.data?.message || error.message || 'Error desconocido al guardar el perfil';
                setProfileErrors({ general: [`Error: ${msg}`] });
            }
        } finally {
            setProfileLoading(false);
        }
    };

    const handlePasswordSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setPasswordLoading(true);
        setPasswordErrors({});
        setPasswordSuccess('');

        try {
            const res = await axios.put('/api/me/password', passwordData);
            setPasswordSuccess(res.data.message || '¡Contraseña actualizada!');

            // Clear form
            setPasswordData({
                current_password: '',
                password: '',
                password_confirmation: ''
            });

            // Clear success message after 3 seconds
            setTimeout(() => setPasswordSuccess(''), 3000);
        } catch (error: any) {
            console.error("Password Change Error:", error);
            if (error.response?.status === 422) {
                setPasswordErrors(error.response.data.errors || {});
            } else if (error.response?.status === 429) {
                setPasswordErrors({ general: ['Demasiados intentos. Intenta de nuevo más tarde.'] });
            } else {
                const msg = error.response?.data?.message || error.message || 'Error desconocido';
                setPasswordErrors({ general: [`Error: ${msg}`] });
            }
        } finally {
            setPasswordLoading(false);
        }
    };

    const ErrorMessage = ({ errors }: { errors: string[] }) => (
        <div style={{ color: '#ef4444', fontSize: '0.875rem', marginTop: '0.25rem' }}>
            {errors.map((error, i) => <div key={i}>{error}</div>)}
        </div>
    );

    const SuccessMessage = ({ message }: { message: string }) => (
        <div style={{
            padding: '0.75rem 1rem',
            background: 'rgba(16, 185, 129, 0.1)',
            border: '1px solid rgba(16, 185, 129, 0.3)',
            borderRadius: '0.5rem',
            color: '#10b981',
            marginBottom: '1rem'
        }}>
            ✓ {message}
        </div>
    );

    return (
        <div className="animate-fadeIn">
            <h1 className="page-title">Configuración</h1>

            <div style={{ display: 'grid', gap: '1.5rem', maxWidth: '800px' }}>
                {/* Appearance */}
                <div className="card">
                    <h2 style={{ fontSize: '1.125rem', fontWeight: 600, marginBottom: '1rem' }}>
                        🎨 Apariencia
                    </h2>

                    <div style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        padding: '1rem',
                        background: 'var(--glass-bg)',
                        borderRadius: '0.5rem',
                    }}>
                        <div>
                            <div style={{ fontWeight: 500 }}>Modo oscuro</div>
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)' }}>
                                Activa el tema oscuro para reducir el cansancio visual
                            </div>
                        </div>
                        <button
                            className={`btn ${theme === 'dark' ? 'btn-primary' : 'btn-secondary'}`}
                            onClick={toggleTheme}
                        >
                            {theme === 'dark' ? '🌙 Oscuro' : '☀️ Claro'}
                        </button>
                    </div>
                </div>

                {/* Profile */}
                <div className="card">
                    <h2 style={{ fontSize: '1.125rem', fontWeight: 600, marginBottom: '1rem' }}>
                        👤 Perfil de Usuario
                    </h2>

                    {profileSuccess && <SuccessMessage message={profileSuccess} />}
                    {profileErrors.general && <ErrorMessage errors={profileErrors.general} />}

                    <form onSubmit={handleProfileSubmit} style={{ display: 'grid', gap: '1rem' }}>
                        <div className="form-group">
                            <label className="form-label">Nombre completo *</label>
                            <input
                                type="text"
                                className="form-input"
                                value={profileData.name}
                                onChange={(e) => setProfileData({ ...profileData, name: e.target.value })}
                                required
                            />
                            {profileErrors.name && <ErrorMessage errors={profileErrors.name} />}
                        </div>

                        <div className="form-group">
                            <label className="form-label">Email *</label>
                            <input
                                type="email"
                                className="form-input"
                                value={profileData.email}
                                onChange={(e) => setProfileData({ ...profileData, email: e.target.value })}
                                required
                            />
                            {profileErrors.email && <ErrorMessage errors={profileErrors.email} />}
                        </div>

                        <div className="form-group">
                            <label className="form-label">Teléfono</label>
                            <input
                                type="tel"
                                className="form-input"
                                value={profileData.phone}
                                onChange={(e) => setProfileData({ ...profileData, phone: e.target.value })}
                                placeholder="+58 412 1234567"
                            />
                            {profileErrors.phone && <ErrorMessage errors={profileErrors.phone} />}
                        </div>

                        <div className="form-group">
                            <label className="form-label">Cargo / Posición</label>
                            <input
                                type="text"
                                className="form-input"
                                value={profileData.position}
                                onChange={(e) => setProfileData({ ...profileData, position: e.target.value })}
                                placeholder="Ej: Administrador, CEO"
                            />
                            {profileErrors.position && <ErrorMessage errors={profileErrors.position} />}
                        </div>

                        <button
                            type="submit"
                            className="btn btn-primary"
                            style={{ width: 'fit-content' }}
                            disabled={profileLoading}
                        >
                            {profileLoading ? 'Guardando...' : 'Guardar cambios'}
                        </button>
                    </form>
                </div>

                {/* Change Password */}
                <div className="card">
                    <h2 style={{ fontSize: '1.125rem', fontWeight: 600, marginBottom: '1rem' }}>
                        🔐 Cambiar Contraseña
                    </h2>

                    {passwordSuccess && <SuccessMessage message={passwordSuccess} />}
                    {passwordErrors.general && <ErrorMessage errors={passwordErrors.general} />}

                    <form onSubmit={handlePasswordSubmit} style={{ display: 'grid', gap: '1rem' }}>
                        <div className="form-group">
                            <label className="form-label">Contraseña actual *</label>
                            <input
                                type="password"
                                className="form-input"
                                value={passwordData.current_password}
                                onChange={(e) => setPasswordData({ ...passwordData, current_password: e.target.value })}
                                required
                                autoComplete="current-password"
                            />
                            {passwordErrors.current_password && <ErrorMessage errors={passwordErrors.current_password} />}
                        </div>

                        <div className="form-group">
                            <label className="form-label">Nueva contraseña *</label>
                            <input
                                type="password"
                                className="form-input"
                                value={passwordData.password}
                                onChange={(e) => setPasswordData({ ...passwordData, password: e.target.value })}
                                required
                                autoComplete="new-password"
                            />
                            <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '0.25rem' }}>
                                Mínimo 8 caracteres, debe incluir mayúsculas, minúsculas, números y símbolos
                            </div>
                            {passwordErrors.password && <ErrorMessage errors={passwordErrors.password} />}
                        </div>

                        <div className="form-group">
                            <label className="form-label">Confirmar nueva contraseña *</label>
                            <input
                                type="password"
                                className="form-input"
                                value={passwordData.password_confirmation}
                                onChange={(e) => setPasswordData({ ...passwordData, password_confirmation: e.target.value })}
                                required
                                autoComplete="new-password"
                            />
                            {passwordErrors.password_confirmation && <ErrorMessage errors={passwordErrors.password_confirmation} />}
                        </div>

                        <button
                            type="submit"
                            className="btn btn-primary"
                            style={{ width: 'fit-content', background: '#ef4444', borderColor: '#ef4444' }}
                            disabled={passwordLoading}
                        >
                            {passwordLoading ? 'Cambiando...' : 'Cambiar contraseña'}
                        </button>
                    </form>
                </div>
            </div>
        </div>
    );
}
