import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import authService from '../services/authService';
import api from '../services/api';
import { toast } from 'react-toastify';

const ChangePasswordPage = () => {
    const [currentPassword, setCurrentPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [notifLoading, setNotifLoading] = useState(false);
    const { user, updateUser } = useAuth();
    const navigate = useNavigate();

    const emailNotificationsEnabled = user?.email_notifications !== false && user?.email_notifications !== 0;

    const handleToggleNotifications = async () => {
        setNotifLoading(true);
        try {
            const newValue = !emailNotificationsEnabled;
            const res = await api.put('/auth/notifications', { email_notifications: newValue });
            const updatedUser = { ...user, email_notifications: newValue ? 1 : 0 };
            localStorage.setItem('user', JSON.stringify(updatedUser));
            updateUser(updatedUser);
            toast.success(newValue ? 'E-Mail-Benachrichtigungen aktiviert' : 'E-Mail-Benachrichtigungen deaktiviert');
        } catch {
            toast.error('Fehler beim Speichern');
        } finally {
            setNotifLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        // Validation
        if (newPassword !== confirmPassword) {
            toast.error('Passwörter stimmen nicht überein');
            return;
        }

        if (newPassword.length < 8) {
            toast.error('Passwort muss mindestens 8 Zeichen lang sein');
            return;
        }

        if (!/[A-Z]/.test(newPassword)) {
            toast.error('Passwort muss mindestens einen Großbuchstaben enthalten');
            return;
        }

        if (!/[a-z]/.test(newPassword)) {
            toast.error('Passwort muss mindestens einen Kleinbuchstaben enthalten');
            return;
        }

        if (!/[0-9]/.test(newPassword)) {
            toast.error('Passwort muss mindestens eine Zahl enthalten');
            return;
        }

        if (!/[!@#$%^&*(),.?":{}|<>]/.test(newPassword)) {
            toast.error('Passwort muss mindestens ein Sonderzeichen enthalten');
            return;
        }

        setLoading(true);

        try {
            await authService.changePassword(currentPassword, newPassword);

            // Update user in context (must_change_password = false)
            const updatedUser = { ...user, must_change_password: false };
            localStorage.setItem('user', JSON.stringify(updatedUser));
            updateUser(updatedUser);

            toast.success('Passwort erfolgreich geändert!');
            navigate('/dashboard');
        } catch (error) {
            toast.error(error.message || 'Passwort ändern fehlgeschlagen');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="page-container">
            <div className="page-header">
                <h1>Passwort ändern</h1>
            </div>

            {/* Persistente Warnung - kann nicht geschlossen werden */}
            <div style={{
                backgroundColor: '#fef3c7',
                borderLeft: '4px solid #f59e0b',
                padding: '16px',
                marginBottom: '24px',
                borderRadius: '4px',
                display: 'flex',
                alignItems: 'center',
                gap: '12px'
            }}>
                <span style={{ fontSize: '24px' }}>⚠️</span>
                <div>
                    <strong style={{ color: '#92400e', display: 'block', marginBottom: '4px' }}>
                        Passwortänderung erforderlich
                    </strong>
                    <span style={{ color: '#78350f' }}>
                        Bitte ändern Sie Ihr Passwort beim ersten Login. Diese Meldung bleibt sichtbar bis das Passwort geändert wurde.
                    </span>
                </div>
            </div>

            {/* E-Mail-Benachrichtigungen */}
            <div className="card" style={{ marginBottom: '24px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0' }}>
                    <div>
                        <div style={{ fontWeight: 600, fontSize: '0.9375rem', color: 'var(--text-primary)', marginBottom: '4px' }}>
                            E-Mail-Benachrichtigungen
                        </div>
                        <div style={{ fontSize: '0.8125rem', color: 'var(--text-muted)', lineHeight: 1.5 }}>
                            {emailNotificationsEnabled
                                ? 'Du erhältst E-Mails bei Ticket-Updates und Support-Antworten.'
                                : 'Du erhältst keine E-Mails bei Ticket-Aktivitäten.'}
                        </div>
                    </div>
                    <button
                        type="button"
                        onClick={handleToggleNotifications}
                        disabled={notifLoading}
                        style={{
                            position: 'relative',
                            width: '48px', height: '26px',
                            borderRadius: '13px',
                            border: 'none',
                            cursor: notifLoading ? 'not-allowed' : 'pointer',
                            background: emailNotificationsEnabled ? 'var(--cereda-primary)' : 'var(--bg-tertiary)',
                            transition: 'background 0.2s',
                            flexShrink: 0,
                            padding: 0,
                        }}
                    >
                        <span style={{
                            position: 'absolute',
                            top: '3px',
                            left: emailNotificationsEnabled ? '25px' : '3px',
                            width: '20px', height: '20px',
                            borderRadius: '50%',
                            background: '#fff',
                            transition: 'left 0.2s',
                            boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
                        }} />
                    </button>
                </div>
            </div>

            <div className="card">
                <form onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label className="form-label">Aktuelles Passwort</label>
                        <input
                            type="password"
                            className="form-input"
                            value={currentPassword}
                            onChange={(e) => setCurrentPassword(e.target.value)}
                            required
                            autoFocus
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Neues Passwort</label>
                        <input
                            type="password"
                            className="form-input"
                            value={newPassword}
                            onChange={(e) => setNewPassword(e.target.value)}
                            required
                            minLength={8}
                        />
                        <small className="form-help">
                            Mindestens 8 Zeichen, 1 Großbuchstabe, 1 Kleinbuchstabe, 1 Zahl und 1 Sonderzeichen (!@#$%^&*(),.?":{}|&lt;&gt;)
                        </small>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Neues Passwort bestätigen</label>
                        <input
                            type="password"
                            className="form-input"
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                            required
                            minLength={8}
                        />
                    </div>

                    <div className="modal-footer">
                        <button
                            type="submit"
                            className="btn btn-primary"
                            disabled={loading}
                        >
                            {loading ? 'Speichern...' : 'Passwort ändern'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default ChangePasswordPage;
