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

const SystemSetupPage = ({ onSetupComplete }) => {
    const [formData, setFormData] = useState({
        username: '',
        password: '',
        confirmPassword: '',
        name: '',
        email: '',
        department: '',
        position: ''
    });
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [validationErrors, setValidationErrors] = useState({});

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
        
        // 입력 시 해당 필드의 에러 메시지 초기화
        if (validationErrors[name]) {
            setValidationErrors(prev => ({
                ...prev,
                [name]: ''
            }));
        }
        if (error) setError('');
    };

    const validateForm = () => {
        const errors = {};

        // 필수 필드 검증
        if (!formData.username.trim()) {
            errors.username = '사용자명을 입력해주세요';
        } else if (formData.username.length < 3 || formData.username.length > 20) {
            errors.username = '사용자명은 3-20자여야 합니다';
        } else if (!/^[a-zA-Z0-9_]+$/.test(formData.username)) {
            errors.username = '사용자명은 영문, 숫자, 언더스코어만 사용 가능합니다';
        }

        if (!formData.password) {
            errors.password = '비밀번호를 입력해주세요';
        } else if (formData.password.length < 8) {
            errors.password = '비밀번호는 8자 이상이어야 합니다';
        }

        if (!formData.confirmPassword) {
            errors.confirmPassword = '비밀번호 확인을 입력해주세요';
        } else if (formData.password !== formData.confirmPassword) {
            errors.confirmPassword = '비밀번호가 일치하지 않습니다';
        }

        if (!formData.name.trim()) {
            errors.name = '이름을 입력해주세요';
        } else if (formData.name.length < 2 || formData.name.length > 50) {
            errors.name = '이름은 2-50자여야 합니다';
        }

        // 이메일 검증 (선택사항)
        if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
            errors.email = '올바른 이메일 형식을 입력해주세요';
        }

        setValidationErrors(errors);
        return Object.keys(errors).length === 0;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        if (!validateForm()) {
            return;
        }

        setIsLoading(true);
        setError('');

        try {
            const setupData = {
                username: formData.username.trim(),
                password: formData.password,
                name: formData.name.trim(),
                email: formData.email.trim() || null,
                department: formData.department.trim() || null,
                position: formData.position.trim() || null
            };

            const response = await api.post('/setup/initialize', setupData);

            if (response.data.success) {
                // 설정 완료 후 콜백 호출
                if (onSetupComplete) {
                    onSetupComplete(response.data);
                }
            } else {
                setError(response.data.message || '시스템 초기화에 실패했습니다');
            }

        } catch (err) {
            console.error('System setup error:', err);
            
            const errorMessage = err.response?.data?.detail || 
                               err.response?.data?.message || 
                               '시스템 초기화 중 오류가 발생했습니다';
            
            setError(errorMessage);
            
            // 오류 로깅
            reportError('System setup failed', {
                error: err.message,
                response: err.response?.data,
                formData: { ...formData, password: '[HIDDEN]', confirmPassword: '[HIDDEN]' }
            });
            
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div style={{
            minHeight: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#f8f9fa',
            padding: '20px'
        }}>
            <div style={{
                maxWidth: '500px',
                width: '100%',
                backgroundColor: 'white',
                borderRadius: '12px',
                boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)',
                padding: '40px'
            }}>
                {/* 헤더 */}
                <div style={{ textAlign: 'center', marginBottom: '32px' }}>
                    <div style={{ fontSize: '48px', marginBottom: '16px' }}>🚀</div>
                    <h1 style={{
                        fontSize: '28px',
                        fontWeight: '700',
                        color: '#2d3748',
                        marginBottom: '8px'
                    }}>
                        시스템 초기 설정
                    </h1>
                    <p style={{
                        fontSize: '16px',
                        color: '#718096',
                        lineHeight: '1.5'
                    }}>
                        TK-MP 시스템을 처음 사용하시는군요!<br />
                        시스템 관리자 계정을 생성해주세요.
                    </p>
                </div>

                {/* 폼 */}
                <form onSubmit={handleSubmit}>
                    {/* 사용자명 */}
                    <div style={{ marginBottom: '20px' }}>
                        <label style={{
                            display: 'block',
                            fontSize: '14px',
                            fontWeight: '600',
                            color: '#374151',
                            marginBottom: '6px'
                        }}>
                            사용자명 *
                        </label>
                        <input
                            type="text"
                            name="username"
                            value={formData.username}
                            onChange={handleChange}
                            placeholder="영문, 숫자, 언더스코어 (3-20자)"
                            style={{
                                width: '100%',
                                padding: '12px',
                                border: validationErrors.username ? '2px solid #ef4444' : '1px solid #d1d5db',
                                borderRadius: '8px',
                                fontSize: '14px',
                                outline: 'none',
                                transition: 'border-color 0.2s',
                                boxSizing: 'border-box'
                            }}
                            onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                            onBlur={(e) => e.target.style.borderColor = validationErrors.username ? '#ef4444' : '#d1d5db'}
                        />
                        {validationErrors.username && (
                            <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                {validationErrors.username}
                            </p>
                        )}
                    </div>

                    {/* 이름 */}
                    <div style={{ marginBottom: '20px' }}>
                        <label style={{
                            display: 'block',
                            fontSize: '14px',
                            fontWeight: '600',
                            color: '#374151',
                            marginBottom: '6px'
                        }}>
                            이름 *
                        </label>
                        <input
                            type="text"
                            name="name"
                            value={formData.name}
                            onChange={handleChange}
                            placeholder="실제 이름을 입력해주세요"
                            style={{
                                width: '100%',
                                padding: '12px',
                                border: validationErrors.name ? '2px solid #ef4444' : '1px solid #d1d5db',
                                borderRadius: '8px',
                                fontSize: '14px',
                                outline: 'none',
                                transition: 'border-color 0.2s',
                                boxSizing: 'border-box'
                            }}
                            onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                            onBlur={(e) => e.target.style.borderColor = validationErrors.name ? '#ef4444' : '#d1d5db'}
                        />
                        {validationErrors.name && (
                            <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                {validationErrors.name}
                            </p>
                        )}
                    </div>

                    {/* 비밀번호 */}
                    <div style={{ marginBottom: '20px' }}>
                        <label style={{
                            display: 'block',
                            fontSize: '14px',
                            fontWeight: '600',
                            color: '#374151',
                            marginBottom: '6px'
                        }}>
                            비밀번호 *
                        </label>
                        <input
                            type="password"
                            name="password"
                            value={formData.password}
                            onChange={handleChange}
                            placeholder="8자 이상 입력해주세요"
                            style={{
                                width: '100%',
                                padding: '12px',
                                border: validationErrors.password ? '2px solid #ef4444' : '1px solid #d1d5db',
                                borderRadius: '8px',
                                fontSize: '14px',
                                outline: 'none',
                                transition: 'border-color 0.2s',
                                boxSizing: 'border-box'
                            }}
                            onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                            onBlur={(e) => e.target.style.borderColor = validationErrors.password ? '#ef4444' : '#d1d5db'}
                        />
                        {validationErrors.password && (
                            <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                {validationErrors.password}
                            </p>
                        )}
                    </div>

                    {/* 비밀번호 확인 */}
                    <div style={{ marginBottom: '20px' }}>
                        <label style={{
                            display: 'block',
                            fontSize: '14px',
                            fontWeight: '600',
                            color: '#374151',
                            marginBottom: '6px'
                        }}>
                            비밀번호 확인 *
                        </label>
                        <input
                            type="password"
                            name="confirmPassword"
                            value={formData.confirmPassword}
                            onChange={handleChange}
                            placeholder="비밀번호를 다시 입력해주세요"
                            style={{
                                width: '100%',
                                padding: '12px',
                                border: validationErrors.confirmPassword ? '2px solid #ef4444' : '1px solid #d1d5db',
                                borderRadius: '8px',
                                fontSize: '14px',
                                outline: 'none',
                                transition: 'border-color 0.2s',
                                boxSizing: 'border-box'
                            }}
                            onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                            onBlur={(e) => e.target.style.borderColor = validationErrors.confirmPassword ? '#ef4444' : '#d1d5db'}
                        />
                        {validationErrors.confirmPassword && (
                            <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                {validationErrors.confirmPassword}
                            </p>
                        )}
                    </div>

                    {/* 이메일 (선택사항) */}
                    <div style={{ marginBottom: '20px' }}>
                        <label style={{
                            display: 'block',
                            fontSize: '14px',
                            fontWeight: '600',
                            color: '#374151',
                            marginBottom: '6px'
                        }}>
                            이메일 (선택사항)
                        </label>
                        <input
                            type="email"
                            name="email"
                            value={formData.email}
                            onChange={handleChange}
                            placeholder="admin@company.com"
                            style={{
                                width: '100%',
                                padding: '12px',
                                border: validationErrors.email ? '2px solid #ef4444' : '1px solid #d1d5db',
                                borderRadius: '8px',
                                fontSize: '14px',
                                outline: 'none',
                                transition: 'border-color 0.2s',
                                boxSizing: 'border-box'
                            }}
                            onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                            onBlur={(e) => e.target.style.borderColor = validationErrors.email ? '#ef4444' : '#d1d5db'}
                        />
                        {validationErrors.email && (
                            <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                {validationErrors.email}
                            </p>
                        )}
                    </div>

                    {/* 부서/직책 (선택사항) */}
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '24px' }}>
                        <div>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: '#374151',
                                marginBottom: '6px'
                            }}>
                                부서 (선택사항)
                            </label>
                            <input
                                type="text"
                                name="department"
                                value={formData.department}
                                onChange={handleChange}
                                placeholder="IT팀"
                                style={{
                                    width: '100%',
                                    padding: '12px',
                                    border: '1px solid #d1d5db',
                                    borderRadius: '8px',
                                    fontSize: '14px',
                                    outline: 'none',
                                    transition: 'border-color 0.2s',
                                    boxSizing: 'border-box'
                                }}
                                onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                                onBlur={(e) => e.target.style.borderColor = '#d1d5db'}
                            />
                        </div>
                        <div>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: '#374151',
                                marginBottom: '6px'
                            }}>
                                직책 (선택사항)
                            </label>
                            <input
                                type="text"
                                name="position"
                                value={formData.position}
                                onChange={handleChange}
                                placeholder="시스템 관리자"
                                style={{
                                    width: '100%',
                                    padding: '12px',
                                    border: '1px solid #d1d5db',
                                    borderRadius: '8px',
                                    fontSize: '14px',
                                    outline: 'none',
                                    transition: 'border-color 0.2s',
                                    boxSizing: 'border-box'
                                }}
                                onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                                onBlur={(e) => e.target.style.borderColor = '#d1d5db'}
                            />
                        </div>
                    </div>

                    {/* 에러 메시지 */}
                    {error && (
                        <div style={{
                            backgroundColor: '#fef2f2',
                            border: '1px solid #fecaca',
                            borderRadius: '8px',
                            padding: '12px',
                            marginBottom: '20px'
                        }}>
                            <p style={{ color: '#dc2626', fontSize: '14px', margin: 0 }}>
                                {error}
                            </p>
                        </div>
                    )}

                    {/* 제출 버튼 */}
                    <button
                        type="submit"
                        disabled={isLoading}
                        style={{
                            width: '100%',
                            padding: '14px',
                            backgroundColor: isLoading ? '#9ca3af' : '#3b82f6',
                            color: 'white',
                            border: 'none',
                            borderRadius: '8px',
                            fontSize: '16px',
                            fontWeight: '600',
                            cursor: isLoading ? 'not-allowed' : 'pointer',
                            transition: 'background-color 0.2s',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            gap: '8px'
                        }}
                        onMouseEnter={(e) => {
                            if (!isLoading) e.target.style.backgroundColor = '#2563eb';
                        }}
                        onMouseLeave={(e) => {
                            if (!isLoading) e.target.style.backgroundColor = '#3b82f6';
                        }}
                    >
                        {isLoading ? (
                            <>
                                <div style={{
                                    width: '16px',
                                    height: '16px',
                                    border: '2px solid #ffffff',
                                    borderTop: '2px solid transparent',
                                    borderRadius: '50%',
                                    animation: 'spin 1s linear infinite'
                                }} />
                                설정 중...
                            </>
                        ) : (
                            <>
                                🚀 시스템 초기화
                            </>
                        )}
                    </button>
                </form>

                {/* 안내 메시지 */}
                <div style={{
                    marginTop: '24px',
                    padding: '16px',
                    backgroundColor: '#f0f9ff',
                    borderRadius: '8px',
                    border: '1px solid #bae6fd'
                }}>
                    <p style={{
                        fontSize: '14px',
                        color: '#0369a1',
                        margin: 0,
                        lineHeight: '1.5'
                    }}>
                        💡 <strong>안내:</strong> 시스템 관리자는 모든 권한을 가지며, 다른 사용자 계정을 생성하고 관리할 수 있습니다. 
                        설정 완료 후 이 계정으로 로그인하여 추가 사용자를 생성하세요.
                    </p>
                </div>
            </div>

            {/* CSS 애니메이션 */}
            <style jsx>{`
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
            `}</style>
        </div>
    );
};

export default SystemSetupPage;
