import React, { useState, useEffect } from 'react';
import MaterialList from '../components/MaterialList';
import { fetchMaterials, fetchJobs } from '../api';

const MaterialsManagementPage = ({ user }) => {
    const [materials, setMaterials] = useState([]);
    const [filteredMaterials, setFilteredMaterials] = useState([]);
    const [projects, setProjects] = useState([]);
    const [loading, setLoading] = useState(false);
    const [filters, setFilters] = useState({
        project: '',
        category: '',
        status: '',
        search: ''
    });
    const [stats, setStats] = useState({
        totalMaterials: 0,
        categorizedMaterials: 0,
        uncategorizedMaterials: 0,
        categories: {}
    });

    useEffect(() => {
        loadProjects();
        loadAllMaterials();
    }, []);

    useEffect(() => {
        applyFilters();
    }, [materials, filters]);

    const loadProjects = async () => {
        try {
            // ✅ API 함수 사용 (권장)
            const response = await fetchJobs();
            if (response.data.success) {
                setProjects(response.data.jobs);
            }
        } catch (error) {
            console.error('프로젝트 로딩 실패:', error);
        }
    };

    const loadAllMaterials = async () => {
        setLoading(true);
        try {
            // 기존 API 함수 사용 - 모든 자재 데이터 로딩
            const response = await fetchMaterials({ limit: 10000 }); // 충분히 큰 limit
            const materialsData = response.data?.materials || [];
            
            setMaterials(materialsData);
            calculateStats(materialsData);
        } catch (error) {
            console.error('자재 데이터 로딩 실패:', error);
        } finally {
            setLoading(false);
        }
    };

    const calculateStats = (materialsData) => {
        const totalMaterials = materialsData.length;
        const categorizedMaterials = materialsData.filter(m => m.classified_category && m.classified_category !== 'Unknown').length;
        const uncategorizedMaterials = totalMaterials - categorizedMaterials;
        
        // 카테고리별 통계
        const categories = {};
        materialsData.forEach(material => {
            const category = material.classified_category || 'Unknown';
            categories[category] = (categories[category] || 0) + 1;
        });

        setStats({
            totalMaterials,
            categorizedMaterials,
            uncategorizedMaterials,
            categories
        });
    };

    const applyFilters = () => {
        let filtered = [...materials];

        // 프로젝트 필터
        if (filters.project) {
            filtered = filtered.filter(m => m.job_no === filters.project);
        }

        // 카테고리 필터
        if (filters.category) {
            filtered = filtered.filter(m => m.classified_category === filters.category);
        }

        // 상태 필터
        if (filters.status) {
            if (filters.status === 'categorized') {
                filtered = filtered.filter(m => m.classified_category && m.classified_category !== 'Unknown');
            } else if (filters.status === 'uncategorized') {
                filtered = filtered.filter(m => !m.classified_category || m.classified_category === 'Unknown');
            }
        }

        // 검색 필터
        if (filters.search) {
            const searchTerm = filters.search.toLowerCase();
            filtered = filtered.filter(m => 
                (m.original_description && m.original_description.toLowerCase().includes(searchTerm)) ||
                (m.size_spec && m.size_spec.toLowerCase().includes(searchTerm)) ||
                (m.classified_category && m.classified_category.toLowerCase().includes(searchTerm))
            );
        }

        setFilteredMaterials(filtered);
    };

    const handleFilterChange = (filterType, value) => {
        setFilters(prev => ({
            ...prev,
            [filterType]: value
        }));
    };

    const clearFilters = () => {
        setFilters({
            project: '',
            category: '',
            status: '',
            search: ''
        });
    };

    const StatCard = ({ title, value, icon, color = '#667eea', subtitle }) => (
        <div style={{
            background: 'white',
            borderRadius: '12px',
            padding: '20px',
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
            border: '1px solid #e2e8f0'
        }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
                <div style={{
                    width: '40px',
                    height: '40px',
                    borderRadius: '10px',
                    background: color + '20',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '20px'
                }}>
                    {icon}
                </div>
                <div>
                    <div style={{ 
                        fontSize: '24px', 
                        fontWeight: '700', 
                        color: '#2d3748'
                    }}>
                        {value.toLocaleString()}
                    </div>
                    <div style={{ 
                        fontSize: '14px', 
                        color: '#718096'
                    }}>
                        {title}
                    </div>
                </div>
            </div>
            {subtitle && (
                <div style={{ 
                    fontSize: '12px', 
                    color: '#718096',
                    marginTop: '4px'
                }}>
                    {subtitle}
                </div>
            )}
        </div>
    );

    return (
        <div style={{ 
            padding: '32px',
            background: '#f7fafc',
            minHeight: '100vh'
        }}>
            <div style={{ maxWidth: '1400px', margin: '0 auto' }}>
                {/* 헤더 */}
                <div style={{ marginBottom: '32px' }}>
                    <h1 style={{ 
                        fontSize: '28px', 
                        fontWeight: '700', 
                        color: '#2d3748',
                        margin: '0 0 8px 0'
                    }}>
                        📦 자재 관리
                    </h1>
                    <p style={{ 
                        color: '#718096', 
                        fontSize: '16px',
                        margin: '0'
                    }}>
                        전체 프로젝트의 자재 정보를 통합 관리하고 분석하세요.
                    </p>
                </div>

                {/* 통계 카드들 */}
                <div style={{ 
                    display: 'grid', 
                    gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', 
                    gap: '20px',
                    marginBottom: '32px'
                }}>
                    <StatCard 
                        title="전체 자재" 
                        value={stats.totalMaterials} 
                        icon="📦"
                        color="#667eea"
                        subtitle={`${projects.length}개 프로젝트`}
                    />
                    <StatCard 
                        title="분류 완료" 
                        value={stats.categorizedMaterials} 
                        icon="✅"
                        color="#48bb78"
                        subtitle={`${Math.round((stats.categorizedMaterials / stats.totalMaterials) * 100) || 0}% 완료`}
                    />
                    <StatCard 
                        title="미분류" 
                        value={stats.uncategorizedMaterials} 
                        icon="⚠️"
                        color="#ed8936"
                        subtitle="분류 작업 필요"
                    />
                    <StatCard 
                        title="카테고리" 
                        value={Object.keys(stats.categories).length} 
                        icon="🏷️"
                        color="#9f7aea"
                        subtitle="자재 분류 유형"
                    />
                </div>

                {/* 필터 섹션 */}
                <div style={{
                    background: 'white',
                    borderRadius: '12px',
                    border: '1px solid #e2e8f0',
                    padding: '24px',
                    marginBottom: '24px'
                }}>
                    <div style={{ 
                        display: 'flex', 
                        justifyContent: 'space-between', 
                        alignItems: 'center',
                        marginBottom: '20px'
                    }}>
                        <h3 style={{ 
                            fontSize: '18px', 
                            fontWeight: '600', 
                            color: '#2d3748',
                            margin: '0'
                        }}>
                            🔍 필터 및 검색
                        </h3>
                        <button
                            onClick={clearFilters}
                            style={{
                                padding: '8px 16px',
                                background: '#e2e8f0',
                                border: 'none',
                                borderRadius: '6px',
                                cursor: 'pointer',
                                fontSize: '14px',
                                color: '#4a5568'
                            }}
                        >
                            필터 초기화
                        </button>
                    </div>

                    <div style={{ 
                        display: 'grid', 
                        gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', 
                        gap: '16px'
                    }}>
                        {/* 프로젝트 필터 */}
                        <div>
                            <label style={{ 
                                display: 'block', 
                                fontSize: '14px', 
                                fontWeight: '600', 
                                color: '#4a5568',
                                marginBottom: '6px'
                            }}>
                                프로젝트
                            </label>
                            <select
                                value={filters.project}
                                onChange={(e) => handleFilterChange('project', e.target.value)}
                                style={{
                                    width: '100%',
                                    padding: '10px',
                                    border: '1px solid #e2e8f0',
                                    borderRadius: '6px',
                                    fontSize: '14px'
                                }}
                            >
                                <option value="">전체 프로젝트</option>
                                {projects.map(project => (
                                    <option key={project.job_no} value={project.job_no}>
                                        {project.job_no} - {project.job_name}
                                    </option>
                                ))}
                            </select>
                        </div>

                        {/* 카테고리 필터 */}
                        <div>
                            <label style={{ 
                                display: 'block', 
                                fontSize: '14px', 
                                fontWeight: '600', 
                                color: '#4a5568',
                                marginBottom: '6px'
                            }}>
                                카테고리
                            </label>
                            <select
                                value={filters.category}
                                onChange={(e) => handleFilterChange('category', e.target.value)}
                                style={{
                                    width: '100%',
                                    padding: '10px',
                                    border: '1px solid #e2e8f0',
                                    borderRadius: '6px',
                                    fontSize: '14px'
                                }}
                            >
                                <option value="">전체 카테고리</option>
                                {Object.keys(stats.categories).map(category => (
                                    <option key={category} value={category}>
                                        {category} ({stats.categories[category]})
                                    </option>
                                ))}
                            </select>
                        </div>

                        {/* 상태 필터 */}
                        <div>
                            <label style={{ 
                                display: 'block', 
                                fontSize: '14px', 
                                fontWeight: '600', 
                                color: '#4a5568',
                                marginBottom: '6px'
                            }}>
                                분류 상태
                            </label>
                            <select
                                value={filters.status}
                                onChange={(e) => handleFilterChange('status', e.target.value)}
                                style={{
                                    width: '100%',
                                    padding: '10px',
                                    border: '1px solid #e2e8f0',
                                    borderRadius: '6px',
                                    fontSize: '14px'
                                }}
                            >
                                <option value="">전체</option>
                                <option value="categorized">분류 완료</option>
                                <option value="uncategorized">미분류</option>
                            </select>
                        </div>

                        {/* 검색 */}
                        <div>
                            <label style={{ 
                                display: 'block', 
                                fontSize: '14px', 
                                fontWeight: '600', 
                                color: '#4a5568',
                                marginBottom: '6px'
                            }}>
                                검색
                            </label>
                            <input
                                type="text"
                                placeholder="자재명, 코드, 카테고리 검색..."
                                value={filters.search}
                                onChange={(e) => handleFilterChange('search', e.target.value)}
                                style={{
                                    width: '100%',
                                    padding: '10px',
                                    border: '1px solid #e2e8f0',
                                    borderRadius: '6px',
                                    fontSize: '14px'
                                }}
                            />
                        </div>
                    </div>

                    {/* 필터 결과 요약 */}
                    <div style={{ 
                        marginTop: '16px', 
                        padding: '12px', 
                        background: '#f7fafc', 
                        borderRadius: '6px',
                        fontSize: '14px',
                        color: '#4a5568'
                    }}>
                        <strong>{filteredMaterials.length.toLocaleString()}</strong>개의 자재가 검색되었습니다.
                        {filters.project && ` (프로젝트: ${filters.project})`}
                        {filters.category && ` (카테고리: ${filters.category})`}
                        {filters.status && ` (상태: ${filters.status === 'categorized' ? '분류완료' : '미분류'})`}
                        {filters.search && ` (검색: "${filters.search}")`}
                    </div>
                </div>

                {/* 자재 목록 */}
                <div style={{
                    background: 'white',
                    borderRadius: '12px',
                    border: '1px solid #e2e8f0',
                    overflow: 'hidden'
                }}>
                    <div style={{
                        padding: '20px 24px',
                        borderBottom: '1px solid #e2e8f0',
                        background: '#f7fafc',
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}>
                        <h3 style={{ 
                            margin: '0',
                            fontSize: '16px',
                            fontWeight: '600',
                            color: '#2d3748'
                        }}>
                            자재 목록 ({filteredMaterials.length.toLocaleString()}개)
                        </h3>
                        
                        <div style={{ display: 'flex', gap: '8px' }}>
                            <button
                                style={{
                                    padding: '8px 16px',
                                    background: '#667eea',
                                    color: 'white',
                                    border: 'none',
                                    borderRadius: '6px',
                                    cursor: 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                📊 분석 리포트
                            </button>
                            <button
                                style={{
                                    padding: '8px 16px',
                                    background: '#48bb78',
                                    color: 'white',
                                    border: 'none',
                                    borderRadius: '6px',
                                    cursor: 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                📤 Excel 내보내기
                            </button>
                        </div>
                    </div>

                    <MaterialList 
                        selectedProject={null} // 전체 자재 보기
                        showProjectInfo={true}
                        enableSelection={true}
                        key="all-materials" // 전체 자재 모드
                    />
                </div>
            </div>
        </div>
    );
};

export default MaterialsManagementPage;
