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

const PurchaseBatchPage = ({ onNavigate, fileId, jobNo }) => {
    const [batches, setBatches] = useState([]);
    const [selectedBatch, setSelectedBatch] = useState(null);
    const [batchMaterials, setBatchMaterials] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('all'); // all, pending, requested, ordered, received
    const [message, setMessage] = useState({ type: '', text: '' });

    useEffect(() => {
        loadBatches();
    }, [fileId, jobNo]);

    const loadBatches = async () => {
        setIsLoading(true);
        try {
            const params = {};
            if (fileId) params.file_id = fileId;
            if (jobNo) params.job_no = jobNo;
            
            const response = await api.get('/export/batches', { params });
            setBatches(response.data.batches || []);
        } catch (error) {
            console.error('Failed to load batches:', error);
            setMessage({ type: 'error', text: '배치 목록 로드 실패' });
        } finally {
            setIsLoading(false);
        }
    };

    const loadBatchMaterials = async (exportId) => {
        setIsLoading(true);
        try {
            const response = await api.get(`/export/batch/${exportId}/materials`);
            setBatchMaterials(response.data.materials || []);
        } catch (error) {
            console.error('Failed to load batch materials:', error);
            setMessage({ type: 'error', text: '자재 목록 로드 실패' });
        } finally {
            setIsLoading(false);
        }
    };

    const handleBatchSelect = (batch) => {
        setSelectedBatch(batch);
        loadBatchMaterials(batch.export_id);
    };

    const handleDownloadExcel = async (exportId, batchNo) => {
        try {
            const response = await api.get(`/export/batch/${exportId}/download`, {
                responseType: 'blob'
            });
            
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `batch_${batchNo}.xlsx`);
            document.body.appendChild(link);
            link.click();
            link.remove();
            window.URL.revokeObjectURL(url);
            
            setMessage({ type: 'success', text: '엑셀 다운로드 완료' });
        } catch (error) {
            console.error('Failed to download excel:', error);
            setMessage({ type: 'error', text: '엑셀 다운로드 실패' });
        }
    };

    const handleBatchStatusUpdate = async (exportId, newStatus) => {
        try {
            const prNo = prompt('구매요청 번호 (PR)를 입력하세요:');
            const response = await api.patch(`/export/batch/${exportId}/status`, {
                status: newStatus,
                purchase_request_no: prNo
            });
            
            if (response.data.success) {
                setMessage({ type: 'success', text: response.data.message });
                loadBatches();
                if (selectedBatch?.export_id === exportId) {
                    loadBatchMaterials(exportId);
                }
            }
        } catch (error) {
            console.error('Failed to update batch status:', error);
            setMessage({ type: 'error', text: '상태 업데이트 실패' });
        }
    };

    const getStatusBadge = (status) => {
        const styles = {
            pending: { bg: '#FFFFE0', color: '#856404', text: '구매 전' },
            requested: { bg: '#FFE4B5', color: '#8B4513', text: '구매신청' },
            in_progress: { bg: '#ADD8E6', color: '#00008B', text: '진행중' },
            ordered: { bg: '#87CEEB', color: '#4682B4', text: '발주완료' },
            received: { bg: '#90EE90', color: '#228B22', text: '입고완료' },
            completed: { bg: '#98FB98', color: '#006400', text: '완료' }
        };
        
        const style = styles[status] || styles.pending;
        
        return (
            <span style={{
                background: style.bg,
                color: style.color,
                padding: '4px 8px',
                borderRadius: '12px',
                fontSize: '12px',
                fontWeight: '600'
            }}>
                {style.text}
            </span>
        );
    };

    const filteredBatches = activeTab === 'all' 
        ? batches 
        : batches.filter(b => b.batch_status === activeTab);

    return (
        <div style={{ padding: '24px', maxWidth: '1400px', margin: '0 auto' }}>
            {/* 헤더 */}
            <div style={{ marginBottom: '24px' }}>
                <h1 style={{ fontSize: '24px', fontWeight: '600', marginBottom: '8px' }}>
                    구매 배치 관리
                </h1>
                <p style={{ color: '#6c757d' }}>
                    엑셀로 내보낸 자재들을 배치 단위로 관리합니다
                </p>
            </div>

            {/* 메시지 */}
            {message.text && (
                <div style={{
                    padding: '12px',
                    marginBottom: '16px',
                    borderRadius: '8px',
                    background: message.type === 'error' ? '#fee' : '#e6ffe6',
                    color: message.type === 'error' ? '#dc3545' : '#28a745',
                    border: `1px solid ${message.type === 'error' ? '#fcc' : '#cfc'}`
                }}>
                    {message.text}
                </div>
            )}

            {/* 탭 네비게이션 */}
            <div style={{ display: 'flex', gap: '12px', marginBottom: '20px' }}>
                {[
                    { key: 'all', label: '전체' },
                    { key: 'pending', label: '구매 전' },
                    { key: 'requested', label: '구매신청' },
                    { key: 'in_progress', label: '진행중' },
                    { key: 'completed', label: '완료' }
                ].map(tab => (
                    <button
                        key={tab.key}
                        onClick={() => setActiveTab(tab.key)}
                        style={{
                            padding: '8px 16px',
                            borderRadius: '20px',
                            border: activeTab === tab.key ? '2px solid #007bff' : '1px solid #dee2e6',
                            background: activeTab === tab.key ? '#007bff' : 'white',
                            color: activeTab === tab.key ? 'white' : '#495057',
                            fontSize: '14px',
                            fontWeight: '500',
                            cursor: 'pointer',
                            transition: 'all 0.2s'
                        }}
                    >
                        {tab.label}
                    </button>
                ))}
            </div>

            {/* 메인 컨텐츠 */}
            <div style={{ display: 'grid', gridTemplateColumns: '400px 1fr', gap: '24px' }}>
                {/* 배치 목록 */}
                <div style={{
                    background: 'white',
                    borderRadius: '12px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                    overflow: 'hidden'
                }}>
                    <div style={{
                        padding: '16px',
                        borderBottom: '1px solid #e9ecef',
                        background: '#f8f9fa'
                    }}>
                        <h2 style={{ fontSize: '16px', fontWeight: '600', margin: 0 }}>
                            배치 목록 ({filteredBatches.length})
                        </h2>
                    </div>
                    
                    <div style={{ maxHeight: '600px', overflow: 'auto' }}>
                        {isLoading ? (
                            <div style={{ padding: '40px', textAlign: 'center' }}>
                                로딩중...
                            </div>
                        ) : filteredBatches.length === 0 ? (
                            <div style={{ padding: '40px', textAlign: 'center', color: '#6c757d' }}>
                                배치가 없습니다
                            </div>
                        ) : (
                            filteredBatches.map(batch => (
                                <div
                                    key={batch.export_id}
                                    onClick={() => handleBatchSelect(batch)}
                                    style={{
                                        padding: '16px',
                                        borderBottom: '1px solid #f1f3f4',
                                        cursor: 'pointer',
                                        background: selectedBatch?.export_id === batch.export_id ? '#f0f8ff' : 'white',
                                        transition: 'background 0.2s'
                                    }}
                                    onMouseEnter={(e) => {
                                        if (selectedBatch?.export_id !== batch.export_id) {
                                            e.currentTarget.style.background = '#f8f9fa';
                                        }
                                    }}
                                    onMouseLeave={(e) => {
                                        if (selectedBatch?.export_id !== batch.export_id) {
                                            e.currentTarget.style.background = 'white';
                                        }
                                    }}
                                >
                                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                                        <span style={{ fontWeight: '600', fontSize: '14px' }}>
                                            {batch.batch_no}
                                        </span>
                                        {getStatusBadge(batch.batch_status)}
                                    </div>
                                    
                                    <div style={{ fontSize: '12px', color: '#6c757d', marginBottom: '4px' }}>
                                        {batch.job_no} - {batch.job_name}
                                    </div>
                                    
                                    <div style={{ fontSize: '12px', color: '#6c757d', marginBottom: '8px' }}>
                                        {batch.category || '전체'} | {batch.material_count}개 자재
                                    </div>
                                    
                                    <div style={{ display: 'flex', gap: '8px', fontSize: '11px' }}>
                                        <span style={{ background: '#e9ecef', padding: '2px 6px', borderRadius: '4px' }}>
                                            대기: {batch.status_detail.pending}
                                        </span>
                                        <span style={{ background: '#fff3cd', padding: '2px 6px', borderRadius: '4px' }}>
                                            신청: {batch.status_detail.requested}
                                        </span>
                                        <span style={{ background: '#cce5ff', padding: '2px 6px', borderRadius: '4px' }}>
                                            발주: {batch.status_detail.ordered}
                                        </span>
                                        <span style={{ background: '#d4edda', padding: '2px 6px', borderRadius: '4px' }}>
                                            입고: {batch.status_detail.received}
                                        </span>
                                    </div>
                                    
                                    <div style={{ marginTop: '8px', fontSize: '11px', color: '#6c757d' }}>
                                        {new Date(batch.export_date).toLocaleDateString()} | {batch.exported_by}
                                    </div>
                                </div>
                            ))
                        )}
                    </div>
                </div>

                {/* 선택된 배치 상세 */}
                {selectedBatch ? (
                    <div style={{
                        background: 'white',
                        borderRadius: '12px',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                        overflow: 'hidden'
                    }}>
                        <div style={{
                            padding: '16px',
                            borderBottom: '1px solid #e9ecef',
                            background: '#f8f9fa'
                        }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <h2 style={{ fontSize: '16px', fontWeight: '600', margin: 0 }}>
                                    배치 {selectedBatch.batch_no}
                                </h2>
                                <div style={{ display: 'flex', gap: '8px' }}>
                                    <button
                                        onClick={() => handleDownloadExcel(selectedBatch.export_id, selectedBatch.batch_no)}
                                        style={{
                                            padding: '6px 12px',
                                            background: '#28a745',
                                            color: 'white',
                                            border: 'none',
                                            borderRadius: '6px',
                                            fontSize: '12px',
                                            cursor: 'pointer'
                                        }}
                                    >
                                        📥 엑셀 다운로드
                                    </button>
                                    <button
                                        onClick={() => handleBatchStatusUpdate(selectedBatch.export_id, 'requested')}
                                        style={{
                                            padding: '6px 12px',
                                            background: '#ffc107',
                                            color: 'white',
                                            border: 'none',
                                            borderRadius: '6px',
                                            fontSize: '12px',
                                            cursor: 'pointer'
                                        }}
                                    >
                                        구매신청
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div style={{ padding: '16px' }}>
                            <div style={{ overflow: 'auto', maxHeight: '500px' }}>
                                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                    <thead>
                                        <tr style={{ background: '#f8f9fa' }}>
                                            <th style={{ padding: '8px', textAlign: 'left', fontSize: '12px', borderBottom: '2px solid #dee2e6' }}>No</th>
                                            <th style={{ padding: '8px', textAlign: 'left', fontSize: '12px', borderBottom: '2px solid #dee2e6' }}>카테고리</th>
                                            <th style={{ padding: '8px', textAlign: 'left', fontSize: '12px', borderBottom: '2px solid #dee2e6' }}>자재 설명</th>
                                            <th style={{ padding: '8px', textAlign: 'center', fontSize: '12px', borderBottom: '2px solid #dee2e6' }}>수량</th>
                                            <th style={{ padding: '8px', textAlign: 'center', fontSize: '12px', borderBottom: '2px solid #dee2e6' }}>상태</th>
                                            <th style={{ padding: '8px', textAlign: 'left', fontSize: '12px', borderBottom: '2px solid #dee2e6' }}>PR번호</th>
                                            <th style={{ padding: '8px', textAlign: 'left', fontSize: '12px', borderBottom: '2px solid #dee2e6' }}>PO번호</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {batchMaterials.map((material, idx) => (
                                            <tr key={material.exported_material_id} style={{ borderBottom: '1px solid #f1f3f4' }}>
                                                <td style={{ padding: '8px', fontSize: '12px' }}>{idx + 1}</td>
                                                <td style={{ padding: '8px', fontSize: '12px' }}>
                                                    <span style={{
                                                        background: '#e9ecef',
                                                        padding: '2px 6px',
                                                        borderRadius: '4px',
                                                        fontSize: '11px'
                                                    }}>
                                                        {material.category}
                                                    </span>
                                                </td>
                                                <td style={{ padding: '8px', fontSize: '12px' }}>{material.description}</td>
                                                <td style={{ padding: '8px', fontSize: '12px', textAlign: 'center' }}>
                                                    {material.quantity} {material.unit}
                                                </td>
                                                <td style={{ padding: '8px', textAlign: 'center' }}>
                                                    {getStatusBadge(material.purchase_status)}
                                                </td>
                                                <td style={{ padding: '8px', fontSize: '12px' }}>
                                                    {material.purchase_request_no || '-'}
                                                </td>
                                                <td style={{ padding: '8px', fontSize: '12px' }}>
                                                    {material.purchase_order_no || '-'}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                ) : (
                    <div style={{
                        background: 'white',
                        borderRadius: '12px',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        minHeight: '400px'
                    }}>
                        <div style={{ textAlign: 'center', color: '#6c757d' }}>
                            <div style={{ fontSize: '48px', marginBottom: '16px' }}>📦</div>
                            <div style={{ fontSize: '16px' }}>배치를 선택하세요</div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default PurchaseBatchPage;
