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

const SimpleLogin = ({ onLoginSuccess }) => {
    const [formData, setFormData] = useState({
        username: '',
        password: ''
    });
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [success, setSuccess] = useState('');

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

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

        setIsLoading(true);
        setError('');

        try {
            const response = await api.post('/auth/login', formData);
            const data = response.data;

            if (data.success) {
                // 토큰과 사용자 정보 저장
                localStorage.setItem('access_token', data.access_token);
                localStorage.setItem('user_data', JSON.stringify(data.user));
                
                setSuccess('로그인 성공! 대시보드로 이동합니다...');
                
                // 잠깐 성공 메시지 보여준 후 대시보드로 이동
                setTimeout(() => {
                    if (onLoginSuccess) {
                        onLoginSuccess();
                    }
                }, 1000);
            } else {
                setError(data.error?.message || '로그인에 실패했습니다.');
            }
        } catch (err) {
            console.error('Login error:', err);
            setError(err.response?.data?.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>

                {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;
