import React, { useState, useEffect } from 'react';
import { X, Bell, AlertTriangle } from 'lucide-react';

const AlertSettingsModal = ({ isOpen, onClose, onSave }) => {
    const [thresholds, setThresholds] = useState({ cpu: 90, memory: 90, disk: 90 });
    const [containerAlertEnabled, setContainerAlertEnabled] = useState(true);
    const [alertCooldownSeconds, setAlertCooldownSeconds] = useState(300);
    const [loading, setLoading] = useState(false);
    const [notifPermission, setNotifPermission] = useState(Notification.permission);
    const [hasActiveSubscription, setHasActiveSubscription] = useState(false);

    useEffect(() => {
        if (isOpen) {
            // Update permission state
            setNotifPermission(Notification.permission);

            // Check for active subscription
            const checkSubscription = async () => {
                try {
                    if ('serviceWorker' in navigator) {
                        const registration = await navigator.serviceWorker.ready;
                        const subscription = await registration.pushManager.getSubscription();
                        setHasActiveSubscription(!!subscription);
                    }
                } catch (e) {
                    console.error('Failed to check subscription:', e);
                    setHasActiveSubscription(false);
                }
            };
            checkSubscription();

            // Fetch current settings from backend
            const fetchSettings = async () => {
                try {
                    const res = await fetch('/api/docker/config');
                    if (res.ok) {
                        const data = await res.json();
                        if (data.alertThresholds) {
                            setThresholds(prev => ({ ...prev, ...data.alertThresholds }));
                        }
                        if (data.containerAlertEnabled !== undefined) {
                            setContainerAlertEnabled(data.containerAlertEnabled);
                        }
                        if (data.alertCooldownSeconds !== undefined) {
                            setAlertCooldownSeconds(data.alertCooldownSeconds);
                        }
                    }
                } catch (e) {
                    console.error('Failed to fetch alert settings:', e);
                }
            };
            fetchSettings();
        }
    }, [isOpen]);

    const enableNotifications = async () => {
        console.log('=== 알림 권한 요청 시작 ===');
        console.log('Notification support:', 'Notification' in window);
        console.log('ServiceWorker support:', 'serviceWorker' in navigator);
        console.log('Secure context:', window.isSecureContext);
        console.log('Current URL:', window.location.href);
        console.log('User Agent:', navigator.userAgent);

        // Check if browser supports notifications
        if (!('Notification' in window)) {
            alert('이 브라우저는 알림을 지원하지 않습니다.');
            return;
        }

        // Check if Service Worker is supported
        if (!('serviceWorker' in navigator)) {
            console.error('Service Worker not supported');
            alert('이 브라우저는 Service Worker를 지원하지 않습니다.\n\n브라우저 정보:\n- User Agent: ' + navigator.userAgent.substring(0, 100) + '...');
            return;
        }

        // Check if we're on a secure context (HTTPS or localhost)
        if (!window.isSecureContext) {
            alert('푸시 알림은 HTTPS 또는 localhost 환경에서만 사용할 수 있습니다.\n현재 연결이 안전하지 않습니다.');
            return;
        }

        try {
            // Request notification permission
            const permission = await Notification.requestPermission();
            console.log('Notification permission:', permission);
            setNotifPermission(permission);

            if (permission !== 'granted') {
                alert('알림 권한이 거부되었습니다.\n브라우저 설정에서 알림 권한을 허용해주세요.');
                return;
            }

            // Wait for service worker to be ready
            console.log('Waiting for service worker...');
            const registration = await navigator.serviceWorker.ready;
            console.log('Service Worker ready:', registration);

            // Get VAPID public key
            console.log('Fetching VAPID key...');
            const keyRes = await fetch('/api/notifications/vapidPublicKey');
            if (!keyRes.ok) {
                throw new Error(`VAPID 키 가져오기 실패: ${keyRes.status}`);
            }
            const { publicKey } = await keyRes.json();
            console.log('VAPID key received');

            // Subscribe to push notifications
            console.log('Subscribing to push notifications...');
            const subscription = await registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: publicKey
            });
            console.log('Push subscription created:', subscription);

            // Send subscription to backend
            console.log('Sending subscription to backend...');
            const response = await fetch('/api/notifications/subscribe', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(subscription)
            });

            if (!response.ok) {
                throw new Error(`구독 등록 실패: ${response.status}`);
            }

            console.log('Subscription saved successfully');
            alert('푸시 알림이 설정되었습니다!');
        } catch (e) {
            console.error('알림 설정 오류:', e);

            // Provide detailed error messages
            let errorMsg = '알림 설정에 실패했습니다.\n\n';

            if (e.name === 'NotAllowedError') {
                errorMsg += '알림 권한이 거부되었습니다. 브라우저 설정에서 알림을 허용해주세요.';
            } else if (e.message.includes('VAPID')) {
                errorMsg += 'VAPID 키를 가져오는데 실패했습니다. 서버 연결을 확인해주세요.';
            } else if (e.message.includes('구독')) {
                errorMsg += '푸시 알림 구독에 실패했습니다. 서버 연결을 확인해주세요.';
            } else {
                errorMsg += `오류: ${e.message}`;
            }

            errorMsg += '\n\n콘솔(F12)에서 자세한 오류를 확인할 수 있습니다.';
            alert(errorMsg);
        }
    };

    const disableNotifications = async () => {
        try {
            const registration = await navigator.serviceWorker.ready;
            const subscription = await registration.pushManager.getSubscription();

            if (subscription) {
                // Unsubscribe from push notifications
                await subscription.unsubscribe();

                // Notify backend
                await fetch('/api/notifications/unsubscribe', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ endpoint: subscription.endpoint })
                });

                console.log('[Notifications] Unsubscribed from push notifications');
            }

            // CRITICAL: Unregister Service Worker completely
            // This is essential for mobile devices where dev tools aren't available
            await registration.unregister();
            console.log('[Service Worker] Unregistered successfully');

            setNotifPermission('default');
            alert('푸시 알림이 해제되었습니다.\n\n페이지를 새로고침하여 Service Worker를 업데이트합니다.');

            // Reload page to download and register new Service Worker
            window.location.reload();
        } catch (e) {
            console.error('[Notifications] 알림 해제 오류:', e);
            alert('알림 해제 중 오류가 발생했습니다.\n\n페이지를 새로고침 후 다시 시도해주세요.');
        }
    };

    const handleSave = async () => {
        // Validate inputs
        if (!thresholds.cpu || !thresholds.memory || !thresholds.disk || !alertCooldownSeconds) {
            alert('모든 값을 입력해주세요.\n\nCPU, 메모리, 디스크 임계값과 알림 재전송 대기 시간을 입력해야 합니다.');
            return;
        }

        setLoading(true);
        try {
            // Save thresholds
            const thresholdRes = await fetch('/api/settings/thresholds', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    thresholds,
                    containerAlertEnabled,
                    alertCooldownSeconds
                })
            });

            if (thresholdRes.ok) {
                alert('알림 설정이 저장되었습니다.');
                if (onSave) onSave();
                onClose();
            } else {
                alert('설정 저장 실패');
            }
        } catch (e) {
            console.error('Failed to save alert settings:', e);
            alert('설정 저장 중 오류 발생');
        } finally {
            setLoading(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-container" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <div className="modal-title-group">
                        <Bell size={24} className="modal-icon" />
                        <h2>알림 설정</h2>
                    </div>
                    <button className="modal-close-btn" onClick={onClose}>
                        <X size={24} />
                    </button>
                </div>

                <div className="modal-content">
                    <div className="alert-settings-section">
                        <div className="section-header">
                            <Bell size={20} />
                            <h3>푸시 알림 권한</h3>
                        </div>
                        <p className="section-desc">
                            {notifPermission === 'granted'
                                ? '알림이 활성화되었습니다. 해제하려면 아래 버튼을 클릭하세요.'
                                : '리소스 임계값 초과 및 컨테이너 종료 시 푸시 알림을 받으려면 권한을 허용해야 합니다.'}
                        </p>
                        <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                            {!hasActiveSubscription ? (
                                <button className="permission-btn" onClick={enableNotifications}>
                                    알림 권한 받기
                                </button>
                            ) : (
                                <>
                                    <button className="permission-btn" style={{ background: 'var(--success-color)', opacity: 0.8, cursor: 'default' }} disabled>
                                        ✓ 알림 활성화됨
                                    </button>
                                    <button className="permission-btn" style={{ background: 'var(--error-color)' }} onClick={disableNotifications}>
                                        알림 해제
                                    </button>
                                </>
                            )}
                        </div>
                    </div>

                    <div className="alert-settings-section">
                        <div className="section-header">
                            <AlertTriangle size={20} />
                            <h3>리소스 사용률 임계값</h3>
                        </div>
                        <p className="section-desc">설정된 사용률을 초과하면 푸시 알림을 받습니다.</p>

                        <div className="threshold-grid">
                            <div className="threshold-item">
                                <label>CPU 사용률 (%)</label>
                                <input
                                    type="number"
                                    min="1"
                                    max="100"
                                    value={thresholds.cpu}
                                    onChange={(e) => setThresholds({ ...thresholds, cpu: parseInt(e.target.value) || '' })}
                                    className="threshold-input"
                                />
                            </div>

                            <div className="threshold-item">
                                <label>메모리 사용률 (%)</label>
                                <input
                                    type="number"
                                    min="1"
                                    max="100"
                                    value={thresholds.memory}
                                    onChange={(e) => setThresholds({ ...thresholds, memory: parseInt(e.target.value) || '' })}
                                    className="threshold-input"
                                />
                            </div>

                            <div className="threshold-item">
                                <label>디스크 사용률 (%)</label>
                                <input
                                    type="number"
                                    min="1"
                                    max="100"
                                    value={thresholds.disk}
                                    onChange={(e) => setThresholds({ ...thresholds, disk: parseInt(e.target.value) || '' })}
                                    className="threshold-input"
                                />
                            </div>

                            <div className="threshold-item">
                                <label>알림 재전송 대기 시간 (초)</label>
                                <input
                                    type="number"
                                    min="60"
                                    max="3600"
                                    value={alertCooldownSeconds}
                                    onChange={(e) => setAlertCooldownSeconds(parseInt(e.target.value) || '')}
                                    className="threshold-input"
                                />
                                <small style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', marginTop: '0.25rem' }}>
                                    동일한 알림이 다시 전송되기까지의 대기 시간 (최소 10초, 기본 300초)
                                </small>
                            </div>
                        </div>
                    </div>

                    <div className="alert-settings-section">
                        <div className="section-header">
                            <Bell size={20} />
                            <h3>컨테이너 알림</h3>
                        </div>
                        <p className="section-desc">Docker 컨테이너가 중지되거나 종료될 때 알림을 받습니다.</p>

                        <div className="toggle-container">
                            <label className="toggle-label">
                                <span>컨테이너 종료 알림</span>
                                <div className="toggle-wrapper">
                                    <input
                                        type="checkbox"
                                        checked={containerAlertEnabled}
                                        onChange={(e) => setContainerAlertEnabled(e.target.checked)}
                                        className="toggle-checkbox"
                                    />
                                    <span className="toggle-slider"></span>
                                </div>
                            </label>
                        </div>
                    </div>
                </div>

                <div className="modal-footer">
                    <button className="modal-btn modal-btn-secondary" onClick={onClose}>
                        취소
                    </button>
                    <button
                        className="modal-btn modal-btn-primary"
                        onClick={handleSave}
                        disabled={loading}
                    >
                        {loading ? '저장 중...' : '저장'}
                    </button>
                </div>
            </div>

            <style>{`
                .modal-overlay {
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(0, 0, 0, 0.7);
                    backdrop-filter: blur(4px);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 1000;
                    padding: 1rem;
                }

                .modal-container {
                    background: var(--glass-bg);
                    backdrop-filter: blur(12px);
                    border: 1px solid var(--glass-border);
                    border-radius: 16px;
                    box-shadow: var(--glass-shadow);
                    width: 100%;
                    max-width: 600px;
                    max-height: 90vh;
                    overflow: hidden;
                    display: flex;
                    flex-direction: column;
                }

                .modal-header {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 1.5rem;
                    border-bottom: 1px solid var(--glass-border);
                }

                .modal-title-group {
                    display: flex;
                    align-items: center;
                    gap: 0.75rem;
                }

                .modal-icon {
                    color: var(--accent-color);
                }

                .modal-title-group h2 {
                    margin: 0;
                    font-size: 1.5rem;
                    font-weight: 600;
                    color: var(--text-primary);
                }

                .modal-close-btn {
                    background: transparent;
                    border: none;
                    cursor: pointer;
                    padding: 0.5rem;
                    border-radius: 8px;
                    color: var(--text-secondary);
                    transition: all 0.2s;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }

                .modal-close-btn:hover {
                    background: rgba(255, 255, 255, 0.1);
                    color: var(--text-primary);
                }

                .modal-content {
                    flex: 1;
                    overflow-y: auto;
                    padding: 1.5rem;
                    display: flex;
                    flex-direction: column;
                    gap: 2rem;
                }

                .alert-settings-section {
                    display: flex;
                    flex-direction: column;
                    gap: 1rem;
                }

                .section-header {
                    display: flex;
                    align-items: center;
                    gap: 0.5rem;
                    color: var(--accent-color);
                }

                .section-header h3 {
                    margin: 0;
                    font-size: 1.125rem;
                    font-weight: 600;
                    color: var(--text-primary);
                }

                .section-desc {
                    margin: 0;
                    font-size: 0.875rem;
                    color: var(--text-secondary);
                }

                .threshold-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                    gap: 1rem;
                    margin-top: 0.5rem;
                }

                .threshold-item {
                    display: flex;
                    flex-direction: column;
                    gap: 0.5rem;
                }

                .threshold-item label {
                    font-size: 0.875rem;
                    font-weight: 500;
                    color: var(--text-primary);
                }

                .threshold-input {
                    padding: 0.75rem;
                    background: var(--card-bg);
                    border: 1px solid var(--glass-border);
                    border-radius: 8px;
                    font-size: 1rem;
                    color: var(--text-primary);
                    transition: all 0.2s;
                }

                .threshold-input:focus {
                    outline: none;
                    border-color: var(--accent-color);
                    box-shadow: 0 0 0 3px var(--accent-glow);
                }

                .toggle-container {
                    margin-top: 0.5rem;
                }

                .toggle-label {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 1rem;
                    background: var(--card-bg);
                    border: 1px solid var(--glass-border);
                    border-radius: 8px;
                    cursor: pointer;
                    transition: all 0.2s;
                }

                .toggle-label:hover {
                    background: rgba(255, 255, 255, 0.05);
                }

                .toggle-label span {
                    font-size: 0.9375rem;
                    font-weight: 500;
                    color: var(--text-primary);
                }

                .toggle-wrapper {
                    position: relative;
                    width: 50px;
                    height: 26px;
                }

                .toggle-checkbox {
                    opacity: 0;
                    width: 0;
                    height: 0;
                }

                .toggle-slider {
                    position: absolute;
                    cursor: pointer;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background-color: rgba(255, 255, 255, 0.2);
                    transition: 0.3s;
                    border-radius: 34px;
                }

                .toggle-slider:before {
                    position: absolute;
                    content: "";
                    height: 18px;
                    width: 18px;
                    left: 4px;
                    bottom: 4px;
                    background-color: white;
                    transition: 0.3s;
                    border-radius: 50%;
                }

                .toggle-checkbox:checked + .toggle-slider {
                    background-color: var(--accent-color);
                }

                .toggle-checkbox:checked + .toggle-slider:before {
                    transform: translateX(24px);
                }

                .modal-footer {
                    display: flex;
                    align-items: center;
                    justify-content: flex-end;
                    gap: 0.75rem;
                    padding: 1.5rem;
                    border-top: 1px solid var(--glass-border);
                }

                .modal-btn {
                    padding: 0.75rem 1.5rem;
                    border-radius: 8px;
                    font-size: 0.9375rem;
                    font-weight: 600;
                    cursor: pointer;
                    transition: all 0.2s;
                    border: none;
                }

                .modal-btn-secondary {
                    background: transparent;
                    color: var(--text-secondary);
                    border: 1px solid var(--glass-border);
                }

                .modal-btn-secondary:hover {
                    background: rgba(255, 255, 255, 0.05);
                    color: var(--text-primary);
                }

                .modal-btn-primary {
                    background: var(--accent-color);
                    color: white;
                }

                .modal-btn-primary:hover:not(:disabled) {
                    filter: brightness(1.1);
                    transform: translateY(-1px);
                }

                .modal-btn-primary:disabled {
                    opacity: 0.6;
                    cursor: not-allowed;
                }

                .permission-btn {
                    width: 100%;
                    padding: 0.875rem;
                    background: var(--accent-color);
                    color: white;
                    border: none;
                    border-radius: 8px;
                    font-size: 0.9375rem;
                    font-weight: 600;
                    cursor: pointer;
                    transition: all 0.2s;
                    margin-top: 0.75rem;
                    touch-action: manipulation;
                    -webkit-tap-highlight-color: transparent;
                    position: relative;
                    z-index: 10;
                }

                .permission-btn:hover {
                    filter: brightness(1.1);
                    transform: translateY(-1px);
                }

                .permission-btn:active {
                    transform: translateY(0);
                }

                @media (max-width: 768px) {
                    .threshold-grid {
                        grid-template-columns: 1fr;
                    }

                    .modal-container {
                        max-height: 95vh;
                    }
                }
            `}</style>
        </div>
    );
};

export default AlertSettingsModal;
