import React, { useState } from 'react';
import { useAuth } from './contexts/AuthContext';
import api from './api';

const SimpleLogin = () => {
    const { login } = useAuth();
    const [formData, setFormData] = useState({
        username: '',
        password: ''
    });
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [success, setSuccess] = useState('');
    const [showSignup, setShowSignup] = useState(false);
    const [signupData, setSignupData] = useState({
        username: '',
        password: '',
        confirmPassword: '',
        name: '',
        email: '',
        department: '',
        position: '',
        phone: '',
        reason: ''
    });

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
        if (error) setError('');
    };

    const handleSignupChange = (e) => {
        const { name, value } = e.target;
        setSignupData(prev => ({
            ...prev,
            [name]: value
        }));
        if (error) setError('');
    };

    const handleSignupSubmit = async (e) => {
        e.preventDefault();
        
        // 유효성 검사
        if (!signupData.username || !signupData.password || !signupData.name) {
            setError('필수 항목을 모두 입력해주세요.');
            return;
        }
        
        if (signupData.password !== signupData.confirmPassword) {
            setError('비밀번호가 일치하지 않습니다.');
            return;
        }
        
        if (signupData.password.length < 6) {
            setError('비밀번호는 최소 6자 이상이어야 합니다.');
            return;
        }
        
        setIsLoading(true);
        setError('');
        
        try {
            const response = await api.post('/auth/signup-request', {
                username: signupData.username,
                password: signupData.password,
                name: signupData.name,
                email: signupData.email || null,
                department: signupData.department || null,
                position: signupData.position || null,
                phone: signupData.phone || null,
                reason: signupData.reason || null
            });
            
            if (response.data.success) {
                setSuccess('회원가입 요청이 전송되었습니다. 관리자 승인 후 이용 가능합니다.');
                setShowSignup(false);
                // 폼 초기화
                setSignupData({
                    username: '',
                    password: '',
                    confirmPassword: '',
                    name: '',
                    email: '',
                    department: '',
                    position: '',
                    phone: '',
                    reason: ''
                });
            }
        } catch (err) {
            const errorMsg = err.response?.data?.detail || '회원가입 요청 중 오류가 발생했습니다.';
            setError(errorMsg);
        } finally {
            setIsLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        if (!formData.username || !formData.password) {
            setError('사용자명과 비밀번호를 입력해주세요.');
            return;
        }

        setIsLoading(true);
        setError('');

        try {
            await login(formData.username, formData.password);
            setSuccess('로그인 성공! 대시보드로 이동합니다...');
        } catch (err) {
            console.error('Login error:', err);
            setError(err.message || '서버 연결에 실패했습니다.');
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div style={{
            minHeight: '100vh',
            margin: '0',
            padding: '0',
            background: 'url("/img/login-bg.jpeg") no-repeat center center fixed',
            backgroundSize: 'cover',
            fontFamily: 'Malgun Gothic, sans-serif',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
        }}>
            <div style={{
                background: 'rgba(0, 0, 0, 0.65)',
                width: '400px',
                padding: '40px',
                borderRadius: '12px',
                textAlign: 'center',
                color: 'white',
                boxShadow: '0 0 20px rgba(0,0,0,0.3)'
            }}>
                <img 
                    src="/img/logo.png" 
                    alt="테크니컬코리아 로고" 
                    style={{
                        width: '200px',
                        marginBottom: '20px'
                    }}
                />
                <h1 style={{ 
                    color: 'white', 
                    fontSize: '24px', 
                    fontWeight: '700', 
                    margin: '0 0 8px 0' 
                }}>
                    (주)테크니컬코리아
                </h1>
                <h3 style={{ 
                    color: 'rgba(255, 255, 255, 0.9)', 
                    fontSize: '18px', 
                    fontWeight: '400',
                    margin: '0 0 32px 0' 
                }}>
                    통합 관리 시스템
                </h3>

                <form onSubmit={handleSubmit}>
                    <input
                        type="text"
                        name="username"
                        value={formData.username}
                        onChange={handleChange}
                        placeholder="아이디"
                        disabled={isLoading}
                        required
                        autoComplete="username"
                        style={{
                            display: 'block',
                            width: '100%',
                            margin: '15px 0',
                            padding: '12px',
                            fontSize: '1rem',
                            borderRadius: '6px',
                            border: 'none',
                            boxSizing: 'border-box'
                        }}
                    />
                    <input
                        type="password"
                        name="password"
                        value={formData.password}
                        onChange={handleChange}
                        placeholder="비밀번호"
                        disabled={isLoading}
                        required
                        autoComplete="current-password"
                        style={{
                            display: 'block',
                            width: '100%',
                            margin: '15px 0',
                            padding: '12px',
                            fontSize: '1rem',
                            borderRadius: '6px',
                            border: 'none',
                            boxSizing: 'border-box'
                        }}
                    />

                    <button 
                        type="submit" 
                        disabled={isLoading}
                        style={{
                            padding: '12px 20px',
                            fontSize: '1rem',
                            cursor: isLoading ? 'not-allowed' : 'pointer',
                            border: 'none',
                            backgroundColor: isLoading ? '#a0aec0' : '#1976d2',
                            color: 'white',
                            borderRadius: '6px',
                            transition: 'background-color 0.3s',
                            width: '100%',
                            marginTop: '10px'
                        }}
                        onMouseEnter={(e) => {
                            if (!isLoading) {
                                e.target.style.backgroundColor = '#1565c0';
                            }
                        }}
                        onMouseLeave={(e) => {
                            if (!isLoading) {
                                e.target.style.backgroundColor = '#1976d2';
                            }
                        }}
                    >
                        {isLoading ? '로그인 중...' : '로그인'}
                    </button>
                </form>
                
                {/* 회원가입 버튼 */}
                <div style={{ marginTop: '20px', textAlign: 'center' }}>
                    <button
                        type="button"
                        onClick={() => {
                            setShowSignup(!showSignup);
                            setError('');
                            setSuccess('');
                        }}
                        style={{
                            width: '100%',
                            padding: '14px',
                            backgroundColor: showSignup ? '#6b7280' : '#10b981',
                            color: 'white',
                            border: 'none',
                            borderRadius: '8px',
                            fontSize: '16px',
                            fontWeight: '600',
                            cursor: 'pointer',
                            transition: 'background-color 0.3s ease'
                        }}
                    >
                        {showSignup ? '✕ 닫기' : '➕ 회원가입 신청'}
                    </button>
                </div>
                
                {/* 회원가입 폼 */}
                {showSignup && (
                    <div style={{
                        marginTop: '20px',
                        padding: '20px',
                        background: '#f0fdf4',
                        border: '2px solid #10b981',
                        borderRadius: '12px',
                        maxHeight: '500px',
                        overflowY: 'auto'
                    }}>
                        <form onSubmit={handleSignupSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
                            <input type="text" name="username" value={signupData.username} onChange={handleSignupChange} placeholder="사용자명*" required style={{ padding: '12px', border: '1px solid #d1d5db', borderRadius: '6px', fontSize: '14px' }} />
                            <input type="password" name="password" value={signupData.password} onChange={handleSignupChange} placeholder="비밀번호 (최소 6자)*" required style={{ padding: '12px', border: '1px solid #d1d5db', borderRadius: '6px', fontSize: '14px' }} />
                            <input type="password" name="confirmPassword" value={signupData.confirmPassword} onChange={handleSignupChange} placeholder="비밀번호 확인*" required style={{ padding: '12px', border: '1px solid #d1d5db', borderRadius: '6px', fontSize: '14px' }} />
                            <input type="text" name="name" value={signupData.name} onChange={handleSignupChange} placeholder="이름*" required style={{ padding: '12px', border: '1px solid #d1d5db', borderRadius: '6px', fontSize: '14px' }} />
                            <button type="submit" disabled={isLoading} style={{ padding: '14px', background: isLoading ? '#9ca3af' : '#10b981', color: 'white', border: 'none', borderRadius: '8px', fontSize: '16px', fontWeight: '600', cursor: isLoading ? 'not-allowed' : 'pointer', marginTop: '8px' }}>
                                {isLoading ? '처리 중...' : '✓ 회원가입 신청'}
                            </button>
                        </form>
                    </div>
                )}

                {error && (
                    <div style={{
                        marginTop: '10px',
                        color: '#ff6b6b',
                        fontWeight: 'bold',
                        fontSize: '14px'
                    }}>
                        {error}
                    </div>
                )}

                {success && (
                    <div style={{
                        marginTop: '10px',
                        color: '#4caf50',
                        fontWeight: 'bold',
                        fontSize: '14px'
                    }}>
                        ✅ {success}
                    </div>
                )}

                <div style={{ marginTop: '32px', textAlign: 'center' }}>
                    <div>
                        <small style={{ color: 'rgba(255, 255, 255, 0.6)', fontSize: '12px' }}>
                            TK-MP 통합 관리 시스템 v2.0
                        </small>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default SimpleLogin;
