import React, { useState, useEffect } from 'react';
import { useSettings } from '../context/SettingsContext';
import {
    BarChart2,
    Activity,
    Layout,
    Settings as SettingsIcon,
    Network,
    Clock,
    Sun,
    Moon,
    Bell,
    Loader2
} from 'lucide-react';
import AlertSettingsModal from '../components/AlertSettingsModal';

const Settings = () => {
    const { chartType, setChartType, dockerEnabled, refreshDockerConfig, hiddenInterfaces, toggleInterfaceVisibility, theme, toggleTheme } = useSettings();
    const [interfaces, setInterfaces] = useState([]);
    const [retentionHours, setRetentionHours] = useState(24);
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        // Fetch current interfaces
        const fetchInterfaces = async () => {
            try {
                const response = await fetch('/api/stats');
                const data = await response.json();
                if (data.network) {
                    setInterfaces(data.network.map(n => n.iface));
                }
            } catch (error) {
                console.error('Failed to fetch stats:', error);
            }
        };
        fetchInterfaces();

        // Fetch retention settings
        const fetchRetention = async () => {
            try {
                const response = await fetch('/api/settings/retention');
                if (response.ok) {
                    const data = await response.json();
                    setRetentionHours(data.hours);
                }
            } catch (error) {
                console.error('Failed to fetch retention settings:', error);
            }
        };
        fetchRetention();
    }, []);

    const saveRetention = async () => {
        setSaving(true);
        try {
            const response = await fetch('/api/settings/retention', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ hours: retentionHours })
            });
            if (response.ok) {
                alert('설정이 저장되었습니다.');
            } else {
                alert('설정 저장 실패');
            }
        } catch (error) {
            console.error('Failed to save settings:', error);
            alert('설정 저장 중 오류 발생');
        } finally {
            setSaving(false);
        }
    };

    const [showAlertModal, setShowAlertModal] = useState(false);
    const [passwordInput, setPasswordInput] = useState('');
    const [showPasswordInput, setShowPasswordInput] = useState(false);

    const handleDockerToggle = () => {
        // Whether enabling or disabling, require password interaction
        setShowPasswordInput(true);
    };

    const confirmDockerChange = async () => {
        if (!passwordInput) return alert('비밀번호를 입력해주세요.');

        const targetState = !dockerEnabled; // Toggle intent

        try {
            const res = await fetch('/api/docker/config', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ enabled: targetState, password: passwordInput })
            });

            if (res.ok) {
                await refreshDockerConfig();
                setShowPasswordInput(false);
                setPasswordInput('');
                alert(`Docker 기능이 ${targetState ? '활성화' : '비활성화'}되었습니다.`);
            } else {
                const data = await res.json();
                alert(data.error || '설정 실패');
            }
        } catch (e) {
            console.error(e);
            alert('서버 요청 실패');
        }
    };

    return (
        <>
            <style>{`
                @media (max-width: 768px) {
                    .settings-container .page-header h2 {
                        display: none;
                    }
                    .settings-container {
                        padding: 0 !important;
                    }
                }
            `}</style>
            <div className="settings-container">
                <header className="page-header desktop-only">
                    <h1>설정</h1>
                </header>

                <div className="settings-grid">
                    {/* Theme Settings */}
                    <div className="glass-card settings-card">
                        <div className="card-header">
                            {theme === 'dark' ? <Moon className="card-icon" /> : <Sun className="card-icon" />}
                            <h3>테마 설정</h3>
                        </div>

                        <div className="setting-item">
                            <div className="setting-label">
                                <span className="setting-title">화면 모드</span>
                                <span className="setting-desc">라이트 모드와 다크 모드를 전환합니다.</span>
                            </div>
                            <div className="setting-control">
                                <button className="toggle-option active" onClick={toggleTheme} style={{ width: 'auto', padding: '0.5rem 1.5rem' }}>
                                    {theme === 'dark' ? (
                                        <>
                                            <Moon size={16} /> 다크 모드
                                        </>
                                    ) : (
                                        <>
                                            <Sun size={16} /> 라이트 모드
                                        </>
                                    )}
                                </button>
                            </div>
                        </div>
                    </div>

                    {/* Chart Settings */}
                    <div className="glass-card settings-card">
                        <div className="card-header">
                            <SettingsIcon className="card-icon" />
                            <h3>대시보드 설정</h3>
                        </div>

                        <div className="setting-item">
                            <div className="setting-label">
                                <span className="setting-title">차트 시각화</span>
                                <span className="setting-desc">시스템 리소스 표시 방식을 선택하세요.</span>
                            </div>
                            <div className="setting-control toggle-group">
                                <button
                                    className={`toggle-option ${chartType === 'bar' ? 'active' : ''}`}
                                    onClick={() => setChartType('bar')}
                                >
                                    <BarChart2 size={16} /> 막대 차트
                                </button>
                                <button
                                    className={`toggle-option ${chartType === 'line' ? 'active' : ''}`}
                                    onClick={() => setChartType('line')}
                                >
                                    <Activity size={16} /> 라인 차트
                                </button>
                            </div>
                        </div>
                    </div>

                    {/* Docker Security Settings */}
                    <div className="glass-card settings-card">
                        <div className="card-header">
                            <Layout className="card-icon" />
                            <h3>Docker 보안 설정</h3>
                        </div>

                        <div className="setting-item">
                            <div className="setting-label">
                                <span className="setting-title">도커 관리 기능</span>
                                <span className="setting-desc">기능 활성화 시 비밀번호 설정이 필요합니다.</span>
                            </div>
                            <div className="setting-control column-control">
                                <div className="toggle-row">
                                    <button
                                        className={`toggle-switch ${dockerEnabled ? 'on' : 'off'}`}
                                        onClick={handleDockerToggle}
                                    >
                                        <div className="knob" />
                                        <span className="status-text">{dockerEnabled ? '활성화' : '비활성화'}</span>
                                    </button>
                                </div>

                                {/* Password Prompt */}
                                {showPasswordInput && (
                                    <div className="password-setup-box">
                                        <input
                                            type="password"
                                            placeholder={dockerEnabled ? "비밀번호를 입력하여 비활성화" : "설정할 비밀번호 입력"}
                                            value={passwordInput}
                                            onChange={(e) => setPasswordInput(e.target.value)}
                                            className="password-input"
                                            autoFocus
                                        />
                                        <div className="btn-row">
                                            <button className="confirm-btn" onClick={confirmDockerChange}>
                                                {dockerEnabled ? '해제 확인' : '활성화 확인'}
                                            </button>
                                            <button className="cancel-btn" onClick={() => { setShowPasswordInput(false); setPasswordInput(''); }}>취소</button>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>

                    {/* Network Interface Settings */}
                    <div className="glass-card settings-card">
                        <div className="card-header">
                            <Network className="card-icon" />
                            <h3>네트워크 인터페이스</h3>
                        </div>

                        <div className="setting-item">
                            <div className="setting-label">
                                <span className="setting-title">인터페이스 표시 설정</span>
                                <span className="setting-desc">대시보드에 표시할 네트워크 인터페이스를 선택하세요.</span>
                            </div>
                            <div className="interfaces-grid">
                                {interfaces.map(iface => (
                                    <button
                                        key={iface}
                                        className={`interface-toggle ${!hiddenInterfaces.includes(iface) ? 'active' : ''}`}
                                        onClick={() => toggleInterfaceVisibility(iface)}
                                    >
                                        <span className="iface-name">{iface}</span>
                                        <div className={`status-dot ${!hiddenInterfaces.includes(iface) ? 'active' : ''}`} />
                                    </button>
                                ))}
                                {interfaces.length === 0 && (
                                    <div style={{ display: 'flex', justifyContent: 'center', padding: '1rem', color: 'var(--text-secondary)' }}>
                                        <Loader2 className="spin-animation" size={24} />
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>

                    {/* Notification Settings */}
                    <div className="glass-card settings-card">
                        <div className="card-header">
                            <Bell className="card-icon" />
                            <h3>알림 설정</h3>
                        </div>

                        <div className="setting-item">
                            <div className="setting-label">
                                <span className="setting-title">푸시 알림 및 임계값 설정</span>
                                <span className="setting-desc">리소스 사용률 임계값과 컨테이너 종료 알림을 설정합니다.</span>
                            </div>
                            <div className="setting-control">
                                <button className="save-btn" onClick={() => setShowAlertModal(true)}>
                                    설정 열기
                                </button>
                            </div>
                        </div>
                    </div>

                    {/* Alert Settings Modal */}
                    <AlertSettingsModal
                        isOpen={showAlertModal}
                        onClose={() => setShowAlertModal(false)}
                        onSave={() => {
                            // Optionally refresh settings or show success message
                        }}
                    />

                    {/* Data Retention Settings */}
                    <div className="glass-card settings-card">
                        <div className="card-header">
                            <Clock className="card-icon" />
                            <h3>데이터 보관 설정</h3>
                        </div>

                        <div className="setting-item">
                            <div className="setting-label">
                                <span className="setting-title">히스토리 보관 기간</span>
                                <span className="setting-desc">시스템 리소스 사용 기록을 보관할 기간을 설정합니다. (시간 단위)</span>
                            </div>
                            <div className="setting-control retention-control">
                                <input
                                    type="number"
                                    min="1"
                                    max="168"
                                    value={retentionHours}
                                    onChange={(e) => setRetentionHours(parseInt(e.target.value) || 0)}
                                    className="number-input"
                                />
                                <span className="unit-text">시간</span>
                                <button
                                    className="save-btn"
                                    onClick={saveRetention}
                                    disabled={saving}
                                >
                                    {saving ? '저장 중...' : '저장'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <style>{`
        .page-header {
            margin-bottom: 2rem;
        }
        .settings-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 1.5rem;
        }
        .settings-card {
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }
        .card-header {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--glass-border);
            margin-bottom: 0.5rem;
        }
        .card-icon { color: var(--accent-color); }
        
        .setting-item {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        .setting-label {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
        }
        .setting-title {
            font-weight: 600;
            font-size: 1rem;
        }
        .setting-desc {
            font-size: 0.85rem;
            color: var(--text-secondary);
        }
        
        .setting-control {
            display: flex;
            align-items: center;
        }
        
        /* Toggle Group for Charts */
        .toggle-group {
            background: rgba(0,0,0,0.05);
            padding: 4px;
            border-radius: 8px;
            display: flex;
            gap: 4px;
        }
        .toggle-option {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            border: none;
            background: transparent;
            color: var(--text-secondary);
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s;
        }
        .toggle-option.active {
            background: var(--card-bg);
            color: var(--accent-color);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        /* Toggle Switch for Docker */
        .toggle-switch {
            position: relative;
            width: 120px;
            height: 36px;
            border-radius: 18px;
            background: rgba(0,0,0,0.1);
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            padding: 4px;
            transition: all 0.3s ease;
        }
        .toggle-switch.on { background: var(--success-color); }
        .toggle-switch.off { background: var(--text-secondary); }
        
        .knob {
            width: 28px;
            height: 28px;
            background: white;
            border-radius: 50%;
            transition: transform 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .toggle-switch.on .knob { transform: translateX(84px); }
        .toggle-switch.off .knob { transform: translateX(0); }
        
        .status-text {
            position: absolute;
            color: white;
            font-weight: 600;
            font-size: 0.85rem;
            width: 100%;
            text-align: center;
            left: 0;
            pointer-events: none;
        }
        .toggle-switch.on .status-text { padding-right: 28px; }
        .toggle-switch.off .status-text { padding-left: 28px; }

        /* Interfaces Grid */
        .interfaces-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 0.75rem;
        }
        .interface-toggle {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: rgba(0,0,0,0.05);
            border: 1px solid transparent;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            color: var(--text-secondary);
        }
        .interface-toggle:hover {
            background: rgba(0,0,0,0.08);
        }
        .interface-toggle.active {
            background: var(--card-bg);
            border-color: var(--accent-color);
            color: var(--accent-color);
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .iface-name {
            font-weight: 600;
            font-size: 0.9rem;
        }
        .status-dot.active {
            background: var(--success-color);
            opacity: 1;
            box-shadow: 0 0 8px var(--success-color);
        }
        
        /* Retention Control */
        .retention-control {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        .number-input {
            background: rgba(0,0,0,0.05);
            border: 1px solid var(--glass-border);
            border-radius: 6px;
            padding: 0.5rem 1rem;
            color: var(--text-primary);
            width: 80px;
            font-size: 1rem;
        }
        .unit-text {
            color: var(--text-secondary);
            font-size: 0.9rem;
        }
        .save-btn {
            background: var(--accent-color);
            border: none;
            border-radius: 6px;
            color: white;
            padding: 0.5rem 1.5rem;
            cursor: pointer;
            font-weight: 500;
            transition: opacity 0.2s;
            margin-left: auto;
        }
        .save-btn:hover {
            opacity: 0.9;
        }
        .save-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Password Setup UI */
        .column-control {
            flex-direction: column;
            width: 100%;
            align-items: flex-start;
            gap: 1rem;
        }
        .toggle-row { width: 100%; display: flex; align-items: center; }
        .password-setup-box {
            width: 100%;
            background: rgba(0,0,0,0.05);
            padding: 1rem;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            animation: fadeIn 0.3s ease;
        }
        .password-input {
            width: 100%;
            padding: 0.75rem;
            border-radius: 6px;
            border: 1px solid var(--glass-border);
            background: var(--card-bg);
            color: var(--text-primary);
        }
        .btn-row {
            display: flex;
            gap: 0.5rem;
            justify-content: flex-end;
        }
        .confirm-btn {
            background: var(--success-color);
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
        }
        .cancel-btn {
            background: transparent;
            color: var(--text-secondary);
            border: 1px solid var(--glass-border);
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-5px); }
            to { opacity: 1; transform: translateY(0); }
        }
        `}</style>
            </div>
        </>
    );
};

export default Settings;
