import React, { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useTheme, THEMES } from '../context/ThemeContext';
import api from '../services/api';
import { toast } from 'react-toastify';

const STAFF_ROLES = ['super_admin', 'admin', 'support', 'bearbeiter'];

const Toggle = ({ checked, onChange, disabled }) => (
    <button
        disabled={disabled}
        onClick={onChange}
        style={{
            width: '44px', height: '24px', borderRadius: '12px', border: 'none',
            background: checked ? 'var(--cereda-primary)' : 'var(--border-color)',
            cursor: disabled ? 'not-allowed' : 'pointer',
            position: 'relative', transition: 'background 0.2s', flexShrink: 0,
            opacity: disabled ? 0.6 : 1,
        }}
    >
        <span style={{
            position: 'absolute', top: '3px',
            left: checked ? '22px' : '3px',
            width: '18px', height: '18px', borderRadius: '50%',
            background: '#fff', transition: 'left 0.2s',
            boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
        }} />
    </button>
);

const Section = ({ title, children }) => (
    <div style={{
        background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
        borderRadius: '12px', padding: '24px', marginBottom: '20px',
    }}>
        <div style={{ fontWeight: 700, fontSize: '0.9375rem', color: 'var(--text-primary)', marginBottom: '18px' }}>
            {title}
        </div>
        {children}
    </div>
);

const MyAccountPage = () => {
    const { user, updateUser } = useAuth();
    const { theme, setTheme } = useTheme();
    const isStaff = STAFF_ROLES.includes(user?.role_name);

    // Simple notification toggle (non-staff)
    const [emailNotif, setEmailNotif] = useState(user?.email_notifications !== 0);
    const [savingNotif, setSavingNotif] = useState(false);

    // Staff notification toggles
    const [staffNotif, setStaffNotif] = useState({
        notif_ticket_created:  !!(user?.notif_ticket_created),
        notif_ticket_assigned: user?.notif_ticket_assigned !== 0,
        notif_new_comment:     user?.notif_new_comment !== 0,
        notif_weekly_report:   user?.notif_weekly_report !== 0,
    });
    const [savingStaffNotif, setSavingStaffNotif] = useState(false);

    const saveEmailNotif = async (enabled) => {
        setSavingNotif(true);
        try {
            await api.put('/auth/notifications', { email_notifications: enabled });
            setEmailNotif(enabled);
            updateUser({ ...user, email_notifications: enabled ? 1 : 0 });
            toast.success(enabled ? 'Benachrichtigungen aktiviert' : 'Benachrichtigungen deaktiviert');
        } catch {
            toast.error('Fehler beim Speichern');
        } finally {
            setSavingNotif(false);
        }
    };

    const toggleStaffNotif = async (key) => {
        const updated = { ...staffNotif, [key]: !staffNotif[key] };
        setStaffNotif(updated);
        setSavingStaffNotif(true);
        try {
            await api.put('/auth/staff-notifications', updated);
            updateUser({ ...user, ...Object.fromEntries(Object.entries(updated).map(([k, v]) => [k, v ? 1 : 0])) });
            toast.success('Einstellung gespeichert');
        } catch {
            setStaffNotif(staffNotif);
            toast.error('Fehler beim Speichern');
        } finally {
            setSavingStaffNotif(false);
        }
    };

    const initials = [user?.first_name, user?.last_name]
        .filter(Boolean).map(n => n[0].toUpperCase()).join('') || user?.username?.[0]?.toUpperCase() || '?';

    return (
        <div style={{ padding: '32px', maxWidth: '600px', margin: '0 auto' }}>
            <h1 style={{ fontWeight: 800, fontSize: '1.5rem', color: 'var(--text-primary)', marginBottom: '28px', marginTop: 0 }}>
                Mein Konto
            </h1>

            {/* Profil */}
            <Section title="👤 Profil">
                <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
                    <div style={{
                        width: '64px', height: '64px', borderRadius: '50%', flexShrink: 0,
                        background: 'var(--cereda-primary)', display: 'flex', alignItems: 'center',
                        justifyContent: 'center', fontSize: '24px', fontWeight: 800, color: '#fff',
                    }}>
                        {initials}
                    </div>
                    <div>
                        <div style={{ fontWeight: 700, fontSize: '1.0625rem', color: 'var(--text-primary)' }}>
                            {[user?.first_name, user?.last_name].filter(Boolean).join(' ') || user?.username}
                        </div>
                        {(user?.first_name || user?.last_name) && (
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginTop: '2px' }}>
                                @{user?.username}
                            </div>
                        )}
                        {user?.email && (
                            <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)', marginTop: '2px' }}>
                                {user.email}
                            </div>
                        )}
                        <span style={{
                            display: 'inline-block', marginTop: '6px', fontSize: '0.75rem', fontWeight: 600,
                            padding: '2px 10px', borderRadius: '12px',
                            background: 'rgba(59,130,246,0.1)', color: 'var(--cereda-primary)',
                        }}>
                            {user?.role_name}
                        </span>
                    </div>
                </div>
            </Section>

            {/* Darstellung */}
            <Section title="🎨 Darstellung">
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                    {Object.entries(THEMES).map(([key, t]) => {
                        const active = theme === key;
                        return (
                            <button key={key} onClick={() => setTheme(key)} style={{
                                background: 'var(--bg-primary)', border: `2px solid ${active ? t.preview.accent : 'var(--border-color)'}`,
                                borderRadius: '10px', padding: '14px', cursor: 'pointer', textAlign: 'left',
                                transition: 'border-color 0.15s', position: 'relative', overflow: 'hidden',
                            }}>
                                {/* Mini-Preview */}
                                <div style={{ display: 'flex', gap: '6px', marginBottom: '10px', borderRadius: '6px', overflow: 'hidden', height: '52px', border: '1px solid rgba(255,255,255,0.06)' }}>
                                    <div style={{ width: '30%', background: t.preview.sidebar, display: 'flex', flexDirection: 'column', gap: '4px', padding: '6px 5px' }}>
                                        {[1,2,3].map(i => (
                                            <div key={i} style={{ height: '4px', borderRadius: '2px', background: i === 1 ? t.preview.accent : 'rgba(255,255,255,0.1)' }} />
                                        ))}
                                    </div>
                                    <div style={{ flex: 1, background: t.preview.bg, padding: '6px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
                                        <div style={{ height: '4px', width: '60%', borderRadius: '2px', background: t.preview.accent, opacity: 0.8 }} />
                                        <div style={{ height: '3px', width: '80%', borderRadius: '2px', background: 'rgba(255,255,255,0.12)' }} />
                                        <div style={{ height: '3px', width: '50%', borderRadius: '2px', background: 'rgba(255,255,255,0.08)' }} />
                                    </div>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <div>
                                        <div style={{ fontWeight: 700, fontSize: '0.875rem', color: 'var(--text-primary)' }}>{t.label}</div>
                                        <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '2px' }}>{t.desc}</div>
                                    </div>
                                    {active && (
                                        <div style={{ width: '18px', height: '18px', borderRadius: '50%', background: t.preview.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                                            <span style={{ fontSize: '10px', color: '#fff', fontWeight: 800 }}>✓</span>
                                        </div>
                                    )}
                                </div>
                            </button>
                        );
                    })}
                </div>
            </Section>

            {/* E-Mail-Benachrichtigungen */}
            <Section title="📧 E-Mail-Benachrichtigungen">
                {!isStaff ? (
                    <>
                        <div style={{
                            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                            padding: '14px 16px', borderRadius: '8px',
                            background: 'var(--bg-primary)', border: '1px solid var(--border-color)',
                            marginBottom: '12px',
                        }}>
                            <div>
                                <div style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--text-primary)' }}>
                                    E-Mail-Benachrichtigungen aktivieren
                                </div>
                                <div style={{ fontSize: '0.775rem', color: 'var(--text-muted)', marginTop: '3px' }}>
                                    Erhalte E-Mails bei Aktualisierungen deiner IT-Anfragen
                                </div>
                            </div>
                            <Toggle checked={emailNotif} onChange={() => saveEmailNotif(!emailNotif)} disabled={savingNotif} />
                        </div>
                        {emailNotif && (
                            <ul style={{ margin: 0, paddingLeft: '16px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
                                {[
                                    'Bestätigung wenn du eine neue Anfrage erstellst',
                                    'Neue Kommentare des IT-Supports',
                                    'Statusänderungen deiner Anfragen',
                                    'Zufriedenheits-Umfrage nach Abschluss',
                                ].map(t => (
                                    <li key={t} style={{ fontSize: '0.775rem', color: 'var(--text-muted)' }}>{t}</li>
                                ))}
                            </ul>
                        )}
                    </>
                ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                        <div style={{ fontSize: '0.8125rem', color: 'var(--text-muted)', marginBottom: '6px' }}>
                            Wähle für welche Ereignisse du E-Mails erhalten möchtest.
                        </div>
                        {[
                            { key: 'notif_ticket_created',  label: 'Neues Ticket eingegangen',   desc: 'Wenn ein neues Ticket im System erstellt wird' },
                            { key: 'notif_ticket_assigned', label: 'Ticket zugewiesen',           desc: 'Wenn dir ein Ticket zugewiesen wird' },
                            { key: 'notif_new_comment',     label: 'Neue Antwort auf Ticket',     desc: 'Wenn ein Mitarbeiter auf dein Ticket antwortet' },
                            { key: 'notif_weekly_report',   label: 'Wöchentlicher Report',        desc: 'Montags: Zusammenfassung offener und geschlossener Tickets' },
                        ].map(({ key, label, desc }) => (
                            <div key={key} style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                                padding: '14px 16px', borderRadius: '8px',
                                background: 'var(--bg-primary)', border: '1px solid var(--border-color)',
                            }}>
                                <div>
                                    <div style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--text-primary)' }}>{label}</div>
                                    <div style={{ fontSize: '0.775rem', color: 'var(--text-muted)', marginTop: '3px' }}>{desc}</div>
                                </div>
                                <Toggle
                                    checked={staffNotif[key]}
                                    onChange={() => toggleStaffNotif(key)}
                                    disabled={savingStaffNotif}
                                />
                            </div>
                        ))}
                    </div>
                )}
            </Section>
        </div>
    );
};

export default MyAccountPage;
