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

const BOMUploadPage = ({ projectInfo, onNavigate, onBack }) => {
    const [selectedFile, setSelectedFile] = useState(null);
    const [jobNo, setJobNo] = useState(projectInfo?.job_no || '');
    const [revision, setRevision] = useState('Rev.0');
    const [bomName, setBomName] = useState('');
    const [isUploading, setIsUploading] = useState(false);
    const [uploadResult, setUploadResult] = useState(null);

    useEffect(() => {
        if (projectInfo) {
            setJobNo(projectInfo.job_no);
            setBomName(projectInfo.project_name || '');
        }
    }, [projectInfo]);

    const handleFileSelect = (event) => {
        const file = event.target.files[0];
        if (file) {
            setSelectedFile(file);
            setUploadResult(null);
        }
    };

    const handleUpload = async () => {
        if (!selectedFile) {
            alert('파일을 선택해주세요.');
            return;
        }

        if (!jobNo.trim()) {
            alert('Job 번호를 입력해주세요.');
            return;
        }

        setIsUploading(true);
        setUploadResult(null);

        try {
            const formData = new FormData();
            formData.append('file', selectedFile);
            formData.append('job_no', jobNo.trim());
            formData.append('revision', revision);
            if (bomName.trim()) {
                formData.append('bom_name', bomName.trim());
            }

            const response = await api.post('/files/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            if (response.data.success) {
                setUploadResult({
                    success: true,
                    message: response.data.message,
                    fileId: response.data.file_id,
                    materialsCount: response.data.materials_count,
                    revision: response.data.revision,
                    uploadedBy: response.data.uploaded_by
                });
                
                // 파일 선택 초기화
                setSelectedFile(null);
                const fileInput = document.getElementById('file-input');
                if (fileInput) fileInput.value = '';
            } else {
                setUploadResult({
                    success: false,
                    message: response.data.message || '업로드에 실패했습니다.'
                });
            }
        } catch (error) {
            console.error('업로드 오류:', error);
            setUploadResult({
                success: false,
                message: error.response?.data?.detail || '업로드 중 오류가 발생했습니다.'
            });
        } finally {
            setIsUploading(false);
        }
    };

    const handleViewMaterials = () => {
        if (uploadResult && uploadResult.fileId) {
            onNavigate('materials', {
                file_id: uploadResult.fileId,
                jobNo: jobNo,
                bomName: bomName,
                revision: uploadResult.revision,
                filename: selectedFile?.name
            });
        }
    };

    return (
        <div style={{
            padding: '32px',
            background: '#f7fafc',
            minHeight: '100vh'
        }}>
            <div style={{ maxWidth: '800px', margin: '0 auto' }}>
                {/* 헤더 */}
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    marginBottom: '32px'
                }}>
                    {onBack && (
                        <button
                            onClick={onBack}
                            style={{
                                background: 'none',
                                border: 'none',
                                fontSize: '24px',
                                cursor: 'pointer',
                                marginRight: '16px',
                                padding: '8px'
                            }}
                        >
                            ←
                        </button>
                    )}
                    <div>
                        <h1 style={{
                            margin: '0 0 8px 0',
                            fontSize: '28px',
                            fontWeight: 'bold',
                            color: '#2d3748'
                        }}>
                            📤 BOM 파일 업로드
                        </h1>
                        {projectInfo && (
                            <div style={{
                                fontSize: '16px',
                                color: '#718096'
                            }}>
                                {projectInfo.project_name} ({projectInfo.job_no})
                            </div>
                        )}
                    </div>
                </div>

                {/* 업로드 폼 */}
                <div style={{
                    background: 'white',
                    borderRadius: '16px',
                    padding: '32px',
                    boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
                    marginBottom: '24px'
                }}>
                    <div style={{
                        display: 'grid',
                        gap: '24px'
                    }}>
                        {/* Job 번호 */}
                        <div>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: '#374151',
                                marginBottom: '8px'
                            }}>
                                Job 번호 *
                            </label>
                            <input
                                type="text"
                                value={jobNo}
                                onChange={(e) => setJobNo(e.target.value)}
                                placeholder="예: TK-2024-001"
                                disabled={!!projectInfo?.job_no}
                                style={{
                                    width: '100%',
                                    padding: '12px 16px',
                                    border: '1px solid #d1d5db',
                                    borderRadius: '8px',
                                    fontSize: '16px',
                                    backgroundColor: projectInfo?.job_no ? '#f9fafb' : 'white'
                                }}
                            />
                        </div>

                        {/* 리비전 */}
                        <div>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: '#374151',
                                marginBottom: '8px'
                            }}>
                                리비전
                            </label>
                            <input
                                type="text"
                                value={revision}
                                onChange={(e) => setRevision(e.target.value)}
                                placeholder="예: Rev.0, Rev.1"
                                style={{
                                    width: '100%',
                                    padding: '12px 16px',
                                    border: '1px solid #d1d5db',
                                    borderRadius: '8px',
                                    fontSize: '16px'
                                }}
                            />
                        </div>

                        {/* BOM 이름 */}
                        <div>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: '#374151',
                                marginBottom: '8px'
                            }}>
                                BOM 이름 (선택사항)
                            </label>
                            <input
                                type="text"
                                value={bomName}
                                onChange={(e) => setBomName(e.target.value)}
                                placeholder="BOM 파일 설명"
                                style={{
                                    width: '100%',
                                    padding: '12px 16px',
                                    border: '1px solid #d1d5db',
                                    borderRadius: '8px',
                                    fontSize: '16px'
                                }}
                            />
                        </div>

                        {/* 파일 선택 */}
                        <div>
                            <label style={{
                                display: 'block',
                                fontSize: '14px',
                                fontWeight: '600',
                                color: '#374151',
                                marginBottom: '8px'
                            }}>
                                BOM 파일 *
                            </label>
                            <div style={{
                                border: '2px dashed #d1d5db',
                                borderRadius: '12px',
                                padding: '32px',
                                textAlign: 'center',
                                backgroundColor: selectedFile ? '#f0f9ff' : '#fafafa',
                                borderColor: selectedFile ? '#3b82f6' : '#d1d5db'
                            }}>
                                <input
                                    id="file-input"
                                    type="file"
                                    accept=".xlsx,.xls,.csv"
                                    onChange={handleFileSelect}
                                    style={{ display: 'none' }}
                                />
                                <label
                                    htmlFor="file-input"
                                    style={{
                                        cursor: 'pointer',
                                        display: 'block'
                                    }}
                                >
                                    {selectedFile ? (
                                        <div>
                                            <div style={{ fontSize: '48px', marginBottom: '16px' }}>📄</div>
                                            <div style={{
                                                fontSize: '18px',
                                                fontWeight: '600',
                                                color: '#1f2937',
                                                marginBottom: '8px'
                                            }}>
                                                {selectedFile.name}
                                            </div>
                                            <div style={{
                                                fontSize: '14px',
                                                color: '#6b7280'
                                            }}>
                                                크기: {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                                            </div>
                                            <div style={{
                                                fontSize: '14px',
                                                color: '#3b82f6',
                                                marginTop: '8px'
                                            }}>
                                                다른 파일을 선택하려면 클릭하세요
                                            </div>
                                        </div>
                                    ) : (
                                        <div>
                                            <div style={{ fontSize: '48px', marginBottom: '16px' }}>📁</div>
                                            <div style={{
                                                fontSize: '18px',
                                                fontWeight: '600',
                                                color: '#1f2937',
                                                marginBottom: '8px'
                                            }}>
                                                파일을 선택하거나 드래그하세요
                                            </div>
                                            <div style={{
                                                fontSize: '14px',
                                                color: '#6b7280'
                                            }}>
                                                Excel (.xlsx, .xls) 또는 CSV 파일만 지원됩니다
                                            </div>
                                        </div>
                                    )}
                                </label>
                            </div>
                        </div>

                        {/* 업로드 버튼 */}
                        <button
                            onClick={handleUpload}
                            disabled={!selectedFile || !jobNo.trim() || isUploading}
                            style={{
                                width: '100%',
                                padding: '16px',
                                backgroundColor: (!selectedFile || !jobNo.trim() || isUploading) ? '#9ca3af' : '#3b82f6',
                                color: 'white',
                                border: 'none',
                                borderRadius: '8px',
                                fontSize: '16px',
                                fontWeight: '600',
                                cursor: (!selectedFile || !jobNo.trim() || isUploading) ? 'not-allowed' : 'pointer',
                                transition: 'all 0.2s ease'
                            }}
                        >
                            {isUploading ? '업로드 중...' : '📤 업로드 시작'}
                        </button>
                    </div>
                </div>

                {/* 업로드 결과 */}
                {uploadResult && (
                    <div style={{
                        background: uploadResult.success ? '#f0f9ff' : '#fef2f2',
                        border: `1px solid ${uploadResult.success ? '#3b82f6' : '#ef4444'}`,
                        borderRadius: '12px',
                        padding: '24px'
                    }}>
                        <div style={{
                            display: 'flex',
                            alignItems: 'flex-start',
                            gap: '12px'
                        }}>
                            <div style={{ fontSize: '24px' }}>
                                {uploadResult.success ? '✅' : '❌'}
                            </div>
                            <div style={{ flex: 1 }}>
                                <h3 style={{
                                    margin: '0 0 8px 0',
                                    fontSize: '18px',
                                    fontWeight: '600',
                                    color: uploadResult.success ? '#1e40af' : '#dc2626'
                                }}>
                                    {uploadResult.success ? '업로드 성공!' : '업로드 실패'}
                                </h3>
                                <p style={{
                                    margin: '0 0 16px 0',
                                    fontSize: '14px',
                                    color: '#374151',
                                    lineHeight: 1.5
                                }}>
                                    {uploadResult.message}
                                </p>
                                
                                {uploadResult.success && (
                                    <div style={{
                                        display: 'flex',
                                        gap: '12px',
                                        marginTop: '16px'
                                    }}>
                                        <button
                                            onClick={handleViewMaterials}
                                            style={{
                                                padding: '8px 16px',
                                                backgroundColor: '#3b82f6',
                                                color: 'white',
                                                border: 'none',
                                                borderRadius: '6px',
                                                fontSize: '14px',
                                                fontWeight: '500',
                                                cursor: 'pointer'
                                            }}
                                        >
                                            자재 목록 보기
                                        </button>
                                        <div style={{
                                            fontSize: '14px',
                                            color: '#6b7280',
                                            display: 'flex',
                                            alignItems: 'center'
                                        }}>
                                            {uploadResult.materialsCount}개 자재 분류됨 • {uploadResult.uploadedBy}
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default BOMUploadPage;
