import React, { useState } from 'react';
import { useSettings } from '../context/SettingsContext';
import { Lock } from 'lucide-react';

const DockerAuth = ({ children }) => {
    const { dockerEnabled } = useSettings();
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [checking, setChecking] = useState(false);

    // If disabled globablly (from backend), show message
    if (!dockerEnabled) {
        return (
            <div className="docker-auth-container glass-card centered">
                <Lock size={48} className="auth-icon locked" />
                <h2>기능 비활성화</h2>
                <p>Docker 관리 기능이 현재 비활성화되어 있습니다.</p>
                <p className="sub-text">설정 페이지에서 기능을 활성화해주세요.</p>
            </div>
        );
    }

    const handleLogin = async (e) => {
        e.preventDefault();
        setChecking(true);
        setError('');

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

            if (res.ok && data.success) {
                setIsAuthenticated(true);
            } else {
                setError('비밀번호가 올바르지 않습니다.');
            }
        } catch (err) {
            setError('서버 연결 실패');
        } finally {
            setChecking(false);
        }
    };

    if (isAuthenticated) {
        return <>{children}</>;
    }

    return (
        <div className="docker-auth-container">
            <div className="glass-card auth-card">
                <div className="auth-header">
                    <Lock size={32} className="auth-icon" />
                    <h2>Docker 보안 접근</h2>
                </div>
                <p className="auth-desc">이 기능에 접근하려면 비밀번호를 입력하세요.</p>

                <form onSubmit={handleLogin} className="auth-form">
                    <input
                        type="password"
                        placeholder="비밀번호"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        className="auth-input"
                        autoFocus
                    />
                    {error && <p className="auth-error">{error}</p>}
                    <button type="submit" className="auth-btn" disabled={checking}>
                        {checking ? '확인 중...' : '잠금 해제'}
                    </button>
                </form>
            </div>

            <style>{`
                .docker-auth-container {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100%;
                    min-height: 400px;
                    width: 100%;
                }
                .auth-card {
                    width: 100%;
                    max-width: 400px;
                    padding: 2rem;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    text-align: center;
                }
                .auth-header {
                    margin-bottom: 1rem;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    gap: 1rem;
                }
                .auth-icon { color: var(--accent-color); }
                .auth-icon.locked { color: var(--text-secondary); }
                
                .auth-desc { color: var(--text-secondary); margin-bottom: 2rem; }
                .sub-text { font-size: 0.9rem; color: var(--text-secondary); margin-top: 0.5rem; }

                .auth-form {
                    width: 100%;
                    display: flex;
                    flex-direction: column;
                    gap: 1rem;
                }
                .auth-input {
                    width: 100%;
                    padding: 1rem;
                    border-radius: 8px;
                    border: 1px solid var(--glass-border);
                    background: rgba(0,0,0,0.05);
                    color: var(--text-primary);
                    font-size: 1rem;
                }
                .auth-btn {
                    padding: 1rem;
                    border-radius: 8px;
                    background: var(--accent-color);
                    color: white;
                    border: none;
                    font-weight: 600;
                    cursor: pointer;
                    transition: opacity 0.2s;
                }
                .auth-btn:hover { opacity: 0.9; }
                .auth-error { color: var(--error-color); font-size: 0.9rem; }
            `}</style>
        </div>
    );
};

export default DockerAuth;
