'use client';

import { useSession, signOut } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

export default function MyAccountPage() {
    const { data: session, status } = useSession();
    const router = useRouter();

    const [showDropdown, setShowDropdown] = useState(false);
    const [activeTab, setActiveTab] = useState('dashboard');

    // ALL hooks first
    const [loginEmail, setLoginEmail] = useState('');
    const [loginPassword, setLoginPassword] = useState('');
    const [loginError, setLoginError] = useState('');
    const [loginLoading, setLoginLoading] = useState(false);
    const [showPassword, setShowPassword] = useState(false);
    const [regEmail, setRegEmail] = useState('');
    const [regMessage, setRegMessage] = useState('');
    const [regLoading, setRegLoading] = useState(false);

    useEffect(() => {
        const handleClick = (e: MouseEvent) => {
            const target = e.target as HTMLElement;
            if (!target.closest('#user-dropdown-wrapper')) {
                setShowDropdown(false);
            }
        };
        document.addEventListener('click', handleClick);
        return () => document.removeEventListener('click', handleClick);
    }, []);

    const handleLogout = async () => {
        await signOut({ redirect: false });
        window.location.href = '/my-account';
    };

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoginLoading(true);
        setLoginError('');
        const { signIn } = await import('next-auth/react');
        const result = await signIn('credentials', {
            email: loginEmail,
            password: loginPassword,
            redirect: false,
        });
        if (result?.error) {
            setLoginError('Invalid email or password');
            setLoginLoading(false);
            return;
        }
        const res = await fetch('/api/auth/session');
        const sessionData = await res.json();
        const role = sessionData?.user?.role;
        if (role === 0) window.location.href = '/super-admin';
        else if (role === 1) window.location.href = '/admin';
        else window.location.href = '/my-account';
    };

    const handleRegister = async (e: React.FormEvent) => {
        e.preventDefault();
        setRegLoading(true);
        setRegMessage('');
        const res = await fetch('/api/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email: regEmail }),
        });
        const data = await res.json();
        setRegMessage(res.ok ? 'Registration successful! Check your email.' : (data.message || 'Registration failed.'));
        setRegLoading(false);
    };

    // Loading state
    if (status === 'loading') return (
        <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <p>Loading...</p>
        </div>
    );

    // If admin/super-admin, redirect away
    if (status === 'authenticated') {
        const role = (session?.user as any)?.role;
        if (role === 0) { window.location.href = '/super-admin'; return null; }
        if (role === 1) { window.location.href = '/admin'; return null; }
    }

    // ── LOGGED IN AS USER (role 2) — show user dashboard ──
    if (status === 'authenticated') {
        return (
            <div style={{ minHeight: '100vh', background: '#f1f1f1', fontFamily: 'sans-serif', display: 'flex', flexDirection: 'column' }}>

                {/* TOP BAR */}
                <div style={{ background: '#1d2327', height: '32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 16px', position: 'sticky', top: 0, zIndex: 9999, flexShrink: 0 }}>
                    <span style={{ color: '#a7aaad', fontSize: '13px', padding: '0 8px' }}>Nyra Leadership — My Account</span>

                    <div id="user-dropdown-wrapper" style={{ position: 'relative' }}>
                        <div onClick={() => setShowDropdown(!showDropdown)}
                            style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '0 12px', height: '32px', cursor: 'pointer', color: '#a7aaad', fontSize: '13px' }}
                            onMouseEnter={e => { (e.currentTarget.style.background = '#2c3338'); (e.currentTarget.style.color = '#fff'); }}
                            onMouseLeave={e => { (e.currentTarget.style.background = 'transparent'); (e.currentTarget.style.color = '#a7aaad'); }}>
                            <div style={{ width: '26px', height: '26px', borderRadius: '50%', background: '#3c434a', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="#a7aaad"><path d="M12 12c2.7 0 4.8-2.1 4.8-4.8S14.7 2.4 12 2.4 7.2 4.5 7.2 7.2 9.3 12 12 12zm0 2.4c-3.2 0-9.6 1.6-9.6 4.8v2.4h19.2v-2.4c0-3.2-6.4-4.8-9.6-4.8z" /></svg>
                            </div>
                            <span>{session?.user?.name}</span>
                            <span style={{ fontSize: '10px' }}>▼</span>
                        </div>

                        {showDropdown && (
                            <div style={{ position: 'absolute', right: 0, top: '32px', background: '#1d2327', border: '1px solid #3c434a', minWidth: '200px', zIndex: 9999, boxShadow: '0 3px 8px rgba(0,0,0,0.5)' }}>
                                <div style={{ padding: '12px 16px', borderBottom: '1px solid #3c434a', display: 'flex', gap: '12px', alignItems: 'center' }}>
                                    <div style={{ width: '44px', height: '44px', borderRadius: '50%', background: '#3c434a', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="#a7aaad"><path d="M12 12c2.7 0 4.8-2.1 4.8-4.8S14.7 2.4 12 2.4 7.2 4.5 7.2 7.2 9.3 12 12 12zm0 2.4c-3.2 0-9.6 1.6-9.6 4.8v2.4h19.2v-2.4c0-3.2-6.4-4.8-9.6-4.8z" /></svg>
                                    </div>
                                    <div>
                                        <p style={{ color: '#fff', fontSize: '14px', fontWeight: 600, margin: 0 }}>{session?.user?.name}</p>
                                        <p style={{ color: '#a7aaad', fontSize: '12px', margin: 0 }}>Subscriber</p>
                                    </div>
                                </div>
                                <div style={{ padding: '10px 16px', color: '#a7aaad', fontSize: '13px', cursor: 'pointer', borderBottom: '1px solid #3c434a' }}
                                    onMouseEnter={e => { (e.currentTarget.style.background = '#2c3338'); (e.currentTarget.style.color = '#72aee6'); }}
                                    onMouseLeave={e => { (e.currentTarget.style.background = 'transparent'); (e.currentTarget.style.color = '#a7aaad'); }}>
                                    Edit Profile
                                </div>
                                <div onClick={handleLogout}
                                    style={{ padding: '10px 16px', color: '#a7aaad', fontSize: '13px', cursor: 'pointer' }}
                                    onMouseEnter={e => { (e.currentTarget.style.background = '#2c3338'); (e.currentTarget.style.color = '#72aee6'); }}
                                    onMouseLeave={e => { (e.currentTarget.style.background = 'transparent'); (e.currentTarget.style.color = '#a7aaad'); }}>
                                    Log Out
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                {/* MAIN */}
                <div style={{ display: 'flex', flex: 1 }}>
                    {/* SIDEBAR */}
                    <div style={{ width: '200px', background: '#2c3338', minHeight: 'calc(100vh - 32px)', flexShrink: 0 }}>
                        <div style={{ padding: '14px 16px', borderBottom: '1px solid #3c434a' }}>
                            <p style={{ color: '#fff', fontWeight: 700, fontSize: '13px', margin: 0 }}>My Account</p>
                            <p style={{ color: '#72aee6', fontSize: '11px', margin: '2px 0 0' }}>Subscriber</p>
                        </div>
                        {[
                            { id: 'dashboard', label: 'Dashboard', icon: '⊞' },
                            { id: 'orders', label: 'My Orders', icon: '📦' },
                            { id: 'profile', label: 'My Profile', icon: '👤' },
                        ].map((item) => (
                            <div key={item.id} onClick={() => setActiveTab(item.id)}
                                style={{ padding: '12px 16px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '10px', fontSize: '13px', color: activeTab === item.id ? '#fff' : '#a7aaad', background: activeTab === item.id ? '#0073aa' : 'transparent', borderLeft: activeTab === item.id ? '3px solid #72aee6' : '3px solid transparent' }}
                                onMouseEnter={e => { if (activeTab !== item.id) { (e.currentTarget.style.background = '#3c434a'); (e.currentTarget.style.color = '#fff'); } }}
                                onMouseLeave={e => { if (activeTab !== item.id) { (e.currentTarget.style.background = 'transparent'); (e.currentTarget.style.color = '#a7aaad'); } }}>
                                <span>{item.icon}</span><span>{item.label}</span>
                            </div>
                        ))}
                    </div>

                    {/* CONTENT */}
                    <div style={{ flex: 1, padding: '24px', background: '#f1f1f1' }}>
                        {activeTab === 'dashboard' && (
                            <div>
                                <h1 style={{ color: '#1d2327', marginTop: 0, fontSize: '23px', fontWeight: 400, borderBottom: '1px solid #c3c4c7', paddingBottom: '12px', marginBottom: '20px' }}>Dashboard</h1>
                                <div style={{ background: '#fff', border: '1px solid #c3c4c7', padding: '24px', marginBottom: '20px' }}>
                                    <p style={{ fontSize: '14px', color: '#3c434a', margin: 0, lineHeight: '1.7' }}>
                                        Hello, <strong>{session?.user?.name}</strong>! Welcome to your account dashboard.
                                        From here you can view your <a href="#" onClick={() => setActiveTab('orders')} style={{ color: '#0073aa' }}>recent orders</a> and
                                        manage your <a href="#" onClick={() => setActiveTab('profile')} style={{ color: '#0073aa' }}>profile details</a>.
                                    </p>
                                </div>
                                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px' }}>
                                    {[
                                        { label: 'My Orders', value: '0', color: '#0073aa', icon: '📦' },
                                        { label: 'Masterclasses', value: '0', color: '#b53855', icon: '🎓' },
                                        { label: 'Account Status', value: 'Active', color: '#2a6e35', icon: '✅' },
                                    ].map((stat) => (
                                        <div key={stat.label} style={{ background: '#fff', padding: '20px', border: '1px solid #c3c4c7', borderTop: `4px solid ${stat.color}` }}>
                                            <div style={{ fontSize: '24px', marginBottom: '6px' }}>{stat.icon}</div>
                                            <p style={{ fontSize: '22px', fontWeight: 700, color: stat.color, margin: '0 0 4px' }}>{stat.value}</p>
                                            <p style={{ fontSize: '13px', color: '#646970', margin: 0 }}>{stat.label}</p>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                        {activeTab === 'orders' && (
                            <div>
                                <h1 style={{ color: '#1d2327', marginTop: 0, fontSize: '23px', fontWeight: 400, borderBottom: '1px solid #c3c4c7', paddingBottom: '12px', marginBottom: '20px' }}>My Orders</h1>
                                <div style={{ background: '#fff', border: '1px solid #c3c4c7', padding: '40px', textAlign: 'center' }}>
                                    <p style={{ fontSize: '16px', color: '#646970', margin: 0 }}>No orders found.</p>
                                </div>
                            </div>
                        )}
                        {activeTab === 'profile' && (
                            <div>
                                <h1 style={{ color: '#1d2327', marginTop: 0, fontSize: '23px', fontWeight: 400, borderBottom: '1px solid #c3c4c7', paddingBottom: '12px', marginBottom: '20px' }}>My Profile</h1>
                                <div style={{ background: '#fff', border: '1px solid #c3c4c7', padding: '24px', maxWidth: '500px' }}>
                                    {[
                                        { label: 'Name', value: session?.user?.name },
                                        { label: 'Email', value: session?.user?.email },
                                        { label: 'Role', value: 'Subscriber' },
                                    ].map((field) => (
                                        <div key={field.label} style={{ marginBottom: '20px' }}>
                                            <label style={{ display: 'block', fontSize: '13px', fontWeight: 600, color: '#1d2327', marginBottom: '6px' }}>{field.label}</label>
                                            <input readOnly value={field.value || ''} style={{ width: '100%', padding: '8px 12px', border: '1px solid #c3c4c7', fontSize: '14px', color: '#3c434a', background: '#f6f7f7' }} />
                                        </div>
                                    ))}
                                    <button style={{ padding: '8px 20px', background: '#0073aa', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '13px', fontWeight: 600 }}>
                                        Update Profile
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        );
    }

    // ── NOT LOGGED IN — show Login / Register form ──
    return (
        <>
            <div className="min-h-screen bg-white">
                <div className="ma-wrapper">
                    <div className="ma-container">
                        <div className="ma-grid">

                            {/* LEFT — Login */}
                            <div className="ma-col">
                                <h2 className="ma-heading">Login</h2>
                                <div className="ma-card">
                                    <form onSubmit={handleLogin} autoComplete="off">
                                        {loginError && <div className="ma-error">{loginError}</div>}
                                        <div className="ma-field">
                                            <label htmlFor="username">Username or email address <span className="ma-required">*</span></label>
                                            <input type="email" id="username" required autoComplete="off" value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} />
                                        </div>
                                        <div className="ma-field">
                                            <label htmlFor="password">Password <span className="ma-required">*</span></label>
                                            <span className="ma-password-wrap">
                                                <input type={showPassword ? 'text' : 'password'} id="password" required autoComplete="off" value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} className="ma-input-password" />
                                                <span className="ma-eye" onClick={() => setShowPassword(!showPassword)}>
                                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /></svg>
                                                </span>
                                            </span>
                                        </div>
                                        <div className="ma-actions">
                                            <button type="submit" className="ma-btn" disabled={loginLoading}
                                                onMouseEnter={(e) => (e.currentTarget.style.background = '#9d3a63')}
                                                onMouseLeave={(e) => (e.currentTarget.style.background = '#B74273')}>
                                                {loginLoading ? 'Logging in...' : 'Log in'}
                                            </button>
                                            <label className="ma-remember">
                                                <input type="checkbox" name="rememberme" value="forever" />
                                                <span>Remember me</span>
                                            </label>
                                        </div>
                                        <div className="ma-lost-wrap">
                                            <a href="#" className="ma-lost">Lost your password?</a>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            {/* RIGHT — Register */}
                            <div className="ma-col">
                                <h2 className="ma-heading">Register</h2>
                                <div className="ma-card">
                                    <form onSubmit={handleRegister} autoComplete="off">
                                        {regMessage && <div className={regMessage.includes('successful') ? 'ma-success' : 'ma-error'}>{regMessage}</div>}
                                        <div className="ma-field">
                                            <label htmlFor="reg_email">Email address <span className="ma-required">*</span></label>
                                            <input type="email" id="reg_email" required autoComplete="off" value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
                                        </div>
                                        <p className="ma-info-text">A link to set a new password will be sent to your email address.</p>
                                        <p className="ma-info-text">Your personal data will be used to support your experience throughout this website, to manage access to your account, and for other purposes described in our <a href="/privacy-policy" className="ma-policy-link">privacy policy</a>.</p>
                                        <div className="ma-actions">
                                            <button type="submit" className="ma-btn" disabled={regLoading}
                                                onMouseEnter={(e) => (e.currentTarget.style.background = '#9d3a63')}
                                                onMouseLeave={(e) => (e.currentTarget.style.background = '#B74273')}>
                                                {regLoading ? 'Registering...' : 'Register'}
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
                <div className="ma-footer-bar" />
            </div>

            <style jsx global>{`
                *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
                .ma-wrapper { margin-top: 105px; padding: 60px 0 100px; }
                .ma-container { max-width: 1140px; margin: 0 auto; padding: 0 5.5%; }
                .ma-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 80px; align-items: start; }
                .ma-col { display: flex; flex-direction: column; }
                .ma-heading { font-size: 42px; font-weight: 700; color: #181B31; margin-bottom: 28px; line-height: 1.2; font-family: Helvetica, Arial, sans-serif; }
                .ma-card { border: 1px solid #E0E0E0; border-radius: 8px; padding: 40px 35px; background: #FAFAFA; flex: 1; }
                .ma-field { margin-bottom: 24px; }
                .ma-field label { display: block; font-size: 16px; color: #6B6B6B; margin-bottom: 10px; font-weight: 400; font-family: Helvetica, Arial, sans-serif; }
                .ma-required { color: #B74273; }
                .ma-field input[type="email"], .ma-field input[type="text"], .ma-input-password { width: 100%; padding: 14px 18px; font-size: 15px; color: #333; background: #fff; border: 1px solid #DEDEDE; border-radius: 4px; outline: none; transition: border-color 0.3s; font-family: Helvetica, Arial, sans-serif; }
                .ma-input-password { padding-right: 50px; }
                .ma-field input:focus, .ma-input-password:focus { border-color: #B74273; }
                .ma-password-wrap { position: relative; display: block; }
                .ma-eye { position: absolute; right: 16px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #888; display: flex; align-items: center; }
                .ma-actions { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; margin-top: 24px; margin-bottom: 16px; }
                .ma-remember { display: inline-flex; align-items: center; gap: 10px; font-size: 15px; color: #6B6B6B; cursor: pointer; font-family: Helvetica, Arial, sans-serif; margin: 0; }
                .ma-remember input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; accent-color: #B74273; flex-shrink: 0; }
                .ma-lost-wrap { margin-top: 4px; }
                .ma-btn { padding: 13px 36px; font-size: 14px; font-weight: 600; color: #fff; background: #B74273; border: none; border-radius: 4px; cursor: pointer; transition: background 0.3s; font-family: Helvetica, Arial, sans-serif; }
                .ma-btn:disabled { opacity: 0.6; cursor: not-allowed; }
                .ma-lost { font-size: 15px; color: #B74273; text-decoration: none; font-family: Helvetica, Arial, sans-serif; }
                .ma-lost:hover { text-decoration: underline; }
                .ma-info-text { font-size: 16px; line-height: 1.7; color: #5D6371; margin-bottom: 16px; font-family: Helvetica, Arial, sans-serif; }
                .ma-policy-link { color: #B74273; text-decoration: none; }
                .ma-error { background: #fff0f0; border: 1px solid #ffcccc; color: #cc0000; padding: 10px 14px; border-radius: 4px; font-size: 13px; margin-bottom: 16px; }
                .ma-success { background: #f0fff4; border: 1px solid #b2dfdb; color: #2e7d32; padding: 10px 14px; border-radius: 4px; font-size: 13px; margin-bottom: 16px; }
                .ma-footer-bar { height: 10px; background: #CF87B0; }
                @media (max-width: 900px) { .ma-grid { grid-template-columns: 1fr; gap: 48px; } }
                @media (max-width: 768px) { .ma-wrapper { margin-top: 80px; padding: 40px 0 70px; } .ma-container { padding: 0 24px; } .ma-heading { font-size: 28px; } .ma-card { padding: 28px 22px; } }
            `}</style>
        </>
    );
}