import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { 
  Typography, 
  Box, 
  Card, 
  CardContent, 
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TablePagination,
  CircularProgress,
  Chip,
  TextField,
  MenuItem,
  Select,
  InputLabel,
  FormControl,
  Grid,
  IconButton,
  Button,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Tabs,
  Tab,
  Alert
} from '@mui/material';
import { 
  Inventory, 
  Clear, 
  ExpandMore,
  CompareArrows,
  Add,
  Remove,
  Warning
} from '@mui/icons-material';
import SearchIcon from '@mui/icons-material/Search';
import { fetchMaterials as fetchMaterialsApi, fetchJobs } from '../api';
import { useSearchParams } from 'react-router-dom';
import Toast from './Toast';

function MaterialList({ selectedProject }) {
  const [searchParams, setSearchParams] = useSearchParams();
  const [materials, setMaterials] = useState([]);
  const [jobs, setJobs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [totalCount, setTotalCount] = useState(0);
  const [search, setSearch] = useState(searchParams.get('search') || '');
  const [searchValue, setSearchValue] = useState(searchParams.get('searchValue') || '');
  const [itemType, setItemType] = useState(searchParams.get('itemType') || '');
  const [materialGrade, setMaterialGrade] = useState(searchParams.get('materialGrade') || '');
  const [sizeSpec, setSizeSpec] = useState(searchParams.get('sizeSpec') || '');
  const [fileFilter, setFileFilter] = useState(searchParams.get('fileFilter') || '');
  const [selectedJob, setSelectedJob] = useState(searchParams.get('jobId') || '');
  const [selectedRevision, setSelectedRevision] = useState(searchParams.get('revision') || '');
  const [groupingType, setGroupingType] = useState(searchParams.get('grouping') || 'item');
  const [sortBy, setSortBy] = useState(searchParams.get('sortBy') || '');
  const [toast, setToast] = useState({ open: false, message: '', type: 'info' });
  const [revisionComparison, setRevisionComparison] = useState(null);
  const [files, setFiles] = useState([]);
  const [fileId, setFileId] = useState(searchParams.get('file_id') || '');
  const [selectedJobNo, setSelectedJobNo] = useState(searchParams.get('job_no') || '');
  const [selectedFilename, setSelectedFilename] = useState(searchParams.get('filename') || '');

  // URL 쿼리 파라미터 동기화
  useEffect(() => {
    const params = new URLSearchParams();
    if (search) params.set('search', search);
    if (searchValue) params.set('searchValue', searchValue);
    if (itemType) params.set('itemType', itemType);
    if (materialGrade) params.set('materialGrade', materialGrade);
    if (sizeSpec) params.set('sizeSpec', sizeSpec);
    if (fileFilter) params.set('fileFilter', fileFilter);
    if (selectedJob) params.set('jobId', selectedJob);
    if (selectedRevision) params.set('revision', selectedRevision);
    if (groupingType) params.set('grouping', groupingType);
    if (sortBy) params.set('sortBy', sortBy);
    if (page > 0) params.set('page', page.toString());
    if (rowsPerPage !== 25) params.set('rowsPerPage', rowsPerPage.toString());
    if (fileId) params.set('file_id', fileId);
    if (selectedJobNo) params.set('job_no', selectedJobNo);
    if (selectedFilename) params.set('filename', selectedFilename);
    if (selectedRevision) params.set('revision', selectedRevision);
    
    setSearchParams(params);
  }, [search, searchValue, itemType, materialGrade, sizeSpec, fileFilter, selectedJob, selectedRevision, groupingType, sortBy, page, rowsPerPage, fileId, setSearchParams, selectedJobNo, selectedFilename, selectedRevision]);

  // URL 파라미터로 진입 시 자동 필터 적용
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const urlJobNo = urlParams.get('job_no');
    const urlFilename = urlParams.get('filename');
    const urlRevision = urlParams.get('revision');
    if (urlJobNo) setSelectedJobNo(urlJobNo);
    if (urlFilename) setSelectedFilename(urlFilename);
    if (urlRevision) setSelectedRevision(urlRevision);
  }, []);

  useEffect(() => {
    if (selectedProject) {
      fetchJobsData();
      fetchMaterials();
    } else {
      setMaterials([]);
      setTotalCount(0);
      setJobs([]);
    }
  }, [selectedProject, page, rowsPerPage, search, searchValue, itemType, materialGrade, sizeSpec, fileFilter, selectedJob, selectedRevision, groupingType, sortBy, fileId, selectedJobNo, selectedFilename, selectedRevision]);

  // 파일 업로드 이벤트 리스너 추가
  useEffect(() => {
    const handleFileUploaded = (event) => {
      const { jobNo } = event.detail;
      if (selectedProject && selectedProject.job_no === jobNo) {
        console.log('파일 업로드 감지됨, 자재 목록 갱신 중...');
        fetchMaterials();
      }
    };

    window.addEventListener('fileUploaded', handleFileUploaded);
    
    return () => {
      window.removeEventListener('fileUploaded', handleFileUploaded);
    };
  }, [selectedProject]);

  // 파일 목록 불러오기 (선택된 프로젝트가 바뀔 때마다)
  useEffect(() => {
    async function fetchFilesForProject() {
      if (!selectedProject?.job_no) {
        setFiles([]);
        return;
      }
      try {
        const response = await fetch(`/files?job_no=${selectedProject.job_no}`);
        if (response.ok) {
          const data = await response.json();
          if (Array.isArray(data)) setFiles(data);
          else if (data && Array.isArray(data.files)) setFiles(data.files);
          else setFiles([]);
        } else {
          setFiles([]);
        }
      } catch {
        setFiles([]);
      }
    }
    fetchFilesForProject();
  }, [selectedProject]);

  const fetchJobsData = async () => {
    try {
      const response = await fetchJobs({ project_id: selectedProject.id });
      if (response.data && response.data.jobs) {
        setJobs(response.data.jobs);
      }
    } catch (error) {
      console.error('Job 조회 실패:', error);
    }
  };

  const fetchMaterials = async () => {
    setLoading(true);
    
    try {
      const skip = page * rowsPerPage;
      const params = {
        job_no: selectedJobNo || undefined,
        filename: selectedFilename || undefined,
        revision: selectedRevision || undefined,
        skip,
        limit: rowsPerPage,
        search: search || undefined,
        search_value: searchValue || undefined,
        item_type: itemType || undefined,
        material_grade: materialGrade || undefined,
        size_spec: sizeSpec || undefined,
        // file_id, fileFilter 등은 사용하지 않음
        grouping: groupingType || undefined,
        sort_by: sortBy || undefined
      };
      
      // selectedProject가 없으면 API 호출하지 않음
      if (!selectedProject?.job_no) {
        setMaterials([]);
        setTotalCount(0);
        setLoading(false);
        return;
      }
      
      console.log('API 요청 파라미터:', params); // 디버깅용
      
      const response = await fetchMaterialsApi(params);
      const data = response.data;
      
      console.log('API 응답:', data); // 디버깅용
      
      setMaterials(data.materials || []);
      setTotalCount(data.total_count || 0);
      
      // 리비전 비교 데이터가 있으면 설정
      if (data.revision_comparison) {
        setRevisionComparison(data.revision_comparison);
      }
    } catch (error) {
      console.error('자재 조회 실패:', error);
      console.error('에러 상세:', error.response?.data); // 디버깅용
      setToast({
        open: true,
        message: `자재 데이터를 불러오는데 실패했습니다: ${error.response?.data?.detail || error.message}`,
        type: 'error'
      });
      setMaterials([]);
      setTotalCount(0);
    } finally {
      setLoading(false);
    }
  };

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const clearFilters = () => {
    setSearch('');
    setSearchValue('');
    setItemType('');
    setMaterialGrade('');
    setSizeSpec('');
    setFileFilter('');
    setSelectedJob('');
    setSelectedRevision('');
    setGroupingType('item');
    setSortBy('');
    setPage(0);
  };

  const getItemTypeColor = (itemType) => {
    const colors = {
      'PIPE': 'primary',
      'FITTING': 'secondary', 
      'VALVE': 'success',
      'FLANGE': 'warning',
      'BOLT': 'info',
              'GASKET': 'error',
        'INSTRUMENT': 'purple',
        'OTHER': 'default'
    };
    return colors[itemType] || 'default';
  };

  const getRevisionChangeColor = (change) => {
    if (change > 0) return 'success';
    if (change < 0) return 'error';
    return 'default';
  };

  const getRevisionChangeIcon = (change) => {
    if (change > 0) return <Add />;
    if (change < 0) return <Remove />;
    return null;
  };

  if (!selectedProject) {
    return (
      <Box>
        <Typography variant="h4" gutterBottom>
          📋 자재 목록
        </Typography>
        <Card>
          <CardContent sx={{ textAlign: 'center', py: 4 }}>
            <Inventory sx={{ fontSize: 64, color: 'secondary.main', mb: 2 }} />
            <Typography variant="h6" gutterBottom>
              프로젝트를 선택해주세요
            </Typography>
            <Typography variant="body2" color="textSecondary">
              프로젝트 관리 탭에서 프로젝트를 선택하면 자재 목록을 확인할 수 있습니다.
            </Typography>
          </CardContent>
        </Card>
      </Box>
    );
  }

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        📋 자재 목록 (그룹핑)
      </Typography>
      
      <Typography variant="h6" color="primary" sx={{ mb: 2 }}>
        {selectedProject.project_name} ({selectedProject.official_project_code})
      </Typography>

      {/* 필터/검색/정렬 UI */}
      <Box sx={{ mb: 2, p: 2, bgcolor: 'grey.50', borderRadius: 2 }}>
        <Grid container spacing={2} alignItems="center">
          {/* 검색 유형 */}
          <Grid item xs={12} sm={3} md={2}>
            <FormControl size="small" fullWidth>
              <InputLabel>검색 유형</InputLabel>
              <Select
                value={search}
                label="검색 유형"
                onChange={e => setSearch(e.target.value)}
                displayEmpty
              >
                <MenuItem key="all-search" value="">전체</MenuItem>
                <MenuItem key="project-search" value="project">프로젝트명</MenuItem>
                <MenuItem key="job-search" value="job">Job No.</MenuItem>
                <MenuItem key="material-search" value="material">자재명</MenuItem>
                <MenuItem key="description-search" value="description">설명</MenuItem>
                <MenuItem key="grade-search" value="grade">재질</MenuItem>
                <MenuItem key="size-search" value="size">사이즈</MenuItem>
                <MenuItem key="filename-search" value="filename">파일명</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          {/* 검색어 입력/선택 */}
          <Grid item xs={12} sm={3} md={2}>
            {search === 'project' ? (
              <FormControl size="small" fullWidth>
                <InputLabel>프로젝트명 선택</InputLabel>
                <Select
                  value={searchValue}
                  label="프로젝트명 선택"
                  onChange={e => setSearchValue(e.target.value)}
                  displayEmpty
                >
                  <MenuItem key="all-projects" value="">전체 프로젝트</MenuItem>
                  <MenuItem key="mp7-rev2" value="MP7 PIPING PROJECT Rev.2">MP7 PIPING PROJECT Rev.2</MenuItem>
                  <MenuItem key="pp5-5701" value="PP5 5701">PP5 5701</MenuItem>
                  <MenuItem key="mp7" value="MP7">MP7</MenuItem>
                </Select>
              </FormControl>
            ) : search === 'job' ? (
              <FormControl size="small" fullWidth>
                <InputLabel>Job No. 선택</InputLabel>
                <Select
                  value={searchValue}
                  label="Job No. 선택"
                  onChange={e => setSearchValue(e.target.value)}
                  displayEmpty
                >
                  <MenuItem key="all-jobs-search" value="">전체 Job</MenuItem>
                  {jobs.map((job) => (
                    <MenuItem key={`job-search-${job.id}`} value={job.job_number}>
                      {job.job_number}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            ) : search === 'material' || search === 'description' ? (
              <TextField
                label="자재명/설명 검색"
                value={searchValue}
                onChange={e => setSearchValue(e.target.value)}
                size="small"
                fullWidth
                placeholder="자재명 또는 설명 입력"
                InputProps={{
                  endAdornment: (
                    <IconButton onClick={() => fetchMaterials()}>
                      <SearchIcon />
                    </IconButton>
                  )
                }}
              />
            ) : search === 'grade' ? (
              <TextField
                label="재질 검색"
                value={searchValue}
                onChange={e => setSearchValue(e.target.value)}
                size="small"
                fullWidth
                placeholder="재질 입력 (예: SS316)"
                InputProps={{
                  endAdornment: (
                    <IconButton onClick={() => fetchMaterials()}>
                      <SearchIcon />
                    </IconButton>
                  )
                }}
              />
            ) : search === 'size' ? (
              <TextField
                label="사이즈 검색"
                value={searchValue}
                onChange={e => setSearchValue(e.target.value)}
                size="small"
                fullWidth
                placeholder="사이즈 입력 (예: 6인치)"
                InputProps={{
                  endAdornment: (
                    <IconButton onClick={() => fetchMaterials()}>
                      <SearchIcon />
                    </IconButton>
                  )
                }}
              />
            ) : search === 'filename' ? (
              <TextField
                label="파일명 검색"
                value={searchValue}
                onChange={e => setSearchValue(e.target.value)}
                size="small"
                fullWidth
                placeholder="파일명 입력"
                InputProps={{
                  endAdornment: (
                    <IconButton onClick={() => fetchMaterials()}>
                      <SearchIcon />
                    </IconButton>
                  )
                }}
              />
            ) : (
              <TextField
                label="검색어"
                value={searchValue}
                onChange={e => setSearchValue(e.target.value)}
                size="small"
                fullWidth
                placeholder="검색어 입력"
                disabled={!search}
                InputProps={{
                  endAdornment: search && (
                    <IconButton onClick={() => fetchMaterials()}>
                      <SearchIcon />
                    </IconButton>
                  )
                }}
              />
            )}
          </Grid>

          {/* Job No. 선택 */}
          <Grid item xs={6} sm={2} md={2}>
            <FormControl size="small" fullWidth>
              <InputLabel>Job No.</InputLabel>
              <Select
                value={selectedJobNo}
                label="Job No."
                onChange={e => setSelectedJobNo(e.target.value)}
                displayEmpty
              >
                <MenuItem value="">전체</MenuItem>
                {jobs.map((job) => (
                  <MenuItem key={job.job_number} value={job.job_number}>
                    {job.job_number}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          {/* 도면명(파일명) 선택 */}
          <Grid item xs={6} sm={2} md={2}>
            <FormControl size="small" fullWidth>
              <InputLabel>도면명(파일명)</InputLabel>
              <Select
                value={selectedFilename}
                label="도면명(파일명)"
                onChange={e => setSelectedFilename(e.target.value)}
                displayEmpty
              >
                <MenuItem value="">전체</MenuItem>
                {files.map((file) => (
                  <MenuItem key={file.id} value={file.original_filename}>
                    {file.bom_name || file.original_filename || file.filename}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          {/* 리비전 선택 */}
          <Grid item xs={6} sm={2} md={2}>
            <FormControl size="small" fullWidth>
              <InputLabel>리비전</InputLabel>
              <Select
                value={selectedRevision}
                label="리비전"
                onChange={e => setSelectedRevision(e.target.value)}
                displayEmpty
              >
                <MenuItem value="">전체</MenuItem>
                {files
                  .filter(file => file.original_filename === selectedFilename)
                  .map((file) => (
                    <MenuItem key={file.id} value={file.revision}>
                      {file.revision}
                    </MenuItem>
                  ))}
              </Select>
            </FormControl>
          </Grid>

          {/* 그룹핑 타입 */}
          <Grid item xs={6} sm={2} md={2}>
            <FormControl size="small" fullWidth>
              <InputLabel>그룹핑</InputLabel>
              <Select
                value={groupingType}
                label="그룹핑"
                onChange={e => setGroupingType(e.target.value)}
              >
                <MenuItem key="item" value="item">품목별</MenuItem>
                <MenuItem key="material" value="material">재질별</MenuItem>
                <MenuItem key="size" value="size">사이즈별</MenuItem>
                <MenuItem key="job" value="job">Job별</MenuItem>
                <MenuItem key="revision" value="revision">리비전별</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          {/* 품목 필터 */}
          <Grid item xs={6} sm={2} md={2}>
            <FormControl size="small" fullWidth>
              <InputLabel>품목</InputLabel>
              <Select
                value={itemType}
                label="품목"
                onChange={e => setItemType(e.target.value)}
              >
                <MenuItem key="all" value="">전체</MenuItem>
                <MenuItem key="PIPE" value="PIPE">PIPE</MenuItem>
                <MenuItem key="FITTING" value="FITTING">FITTING</MenuItem>
                <MenuItem key="VALVE" value="VALVE">VALVE</MenuItem>
                <MenuItem key="FLANGE" value="FLANGE">FLANGE</MenuItem>
                <MenuItem key="BOLT" value="BOLT">BOLT</MenuItem>
                <MenuItem key="GASKET" value="GASKET">GASKET</MenuItem>
                <MenuItem key="INSTRUMENT" value="INSTRUMENT">INSTRUMENT</MenuItem>
                <MenuItem key="OTHER" value="OTHER">기타</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          {/* 재질 필터 */}
          <Grid item xs={6} sm={2} md={2}>
            <TextField
              label="재질"
              value={materialGrade}
              onChange={e => setMaterialGrade(e.target.value)}
              size="small"
              fullWidth
              placeholder="예: SS316"
            />
          </Grid>

          {/* 사이즈 필터 */}
          <Grid item xs={6} sm={2} md={2}>
            <TextField
              label="사이즈"
              value={sizeSpec}
              onChange={e => setSizeSpec(e.target.value)}
              size="small"
              fullWidth
              placeholder={'예: 6"'}
            />
          </Grid>

          {/* 파일명 필터 */}
          <Grid item xs={6} sm={2} md={2}>
            <TextField
              label="파일명"
              value={fileFilter}
              onChange={e => setFileFilter(e.target.value)}
              size="small"
              fullWidth
              placeholder="파일명 검색"
            />
          </Grid>

          {/* 파일(도면) 선택 드롭다운 */}
          <Grid item xs={6} sm={2} md={2}>
            <FormControl size="small" fullWidth>
              <InputLabel>도면(파일)</InputLabel>
              <Select
                value={fileId}
                label="도면(파일)"
                onChange={e => setFileId(e.target.value)}
                displayEmpty
              >
                <MenuItem value="">전체</MenuItem>
                {files.map((file) => (
                  <MenuItem key={file.id} value={file.id}>
                    {file.bom_name || file.original_filename || file.filename}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          {/* 정렬 */}
          <Grid item xs={6} sm={2} md={2}>
            <FormControl size="small" fullWidth>
              <InputLabel>정렬</InputLabel>
              <Select
                value={sortBy}
                label="정렬"
                onChange={e => setSortBy(e.target.value)}
              >
                <MenuItem key="default" value="">기본</MenuItem>
                <MenuItem key="quantity_desc" value="quantity_desc">수량 내림차순</MenuItem>
                <MenuItem key="quantity_asc" value="quantity_asc">수량 오름차순</MenuItem>
                <MenuItem key="name_asc" value="name_asc">이름 오름차순</MenuItem>
                <MenuItem key="name_desc" value="name_desc">이름 내림차순</MenuItem>
                <MenuItem key="created_desc" value="created_desc">최신 업로드</MenuItem>
                <MenuItem key="created_asc" value="created_asc">오래된 업로드</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          {/* 필터 초기화 */}
          <Grid item xs={12}>
            <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
              <Button
                variant="outlined"
                size="small"
                startIcon={<Clear />}
                onClick={clearFilters}
              >
                필터 초기화
              </Button>
            </Box>
          </Grid>
        </Grid>
      </Box>

      {/* 전역 Toast */}
      <Toast
        open={toast.open}
        message={toast.message}
        type={toast.type}
        onClose={() => setToast({ open: false, message: '', type: 'info' })}
      />

      {/* 리비전 비교 알림 */}
      {revisionComparison && (
        <Alert severity="info" sx={{ mb: 2 }}>
          <Typography variant="body2">
            <strong>리비전 비교:</strong> {revisionComparison.summary}
          </Typography>
        </Alert>
      )}

      {/* 필터 상태 표시 */}
      {(search || searchValue || itemType || materialGrade || sizeSpec || fileFilter || selectedJobNo || selectedFilename || selectedRevision || groupingType !== 'item' || sortBy) && (
        <Box sx={{ mb: 2, p: 1, bgcolor: 'info.50', borderRadius: 1, border: '1px solid', borderColor: 'info.200' }}>
          <Typography variant="body2" color="info.main">
            필터 적용 중: 
            {search && ` 검색 유형: ${search}`}
            {searchValue && ` 검색어: "${searchValue}"`}
            {selectedJobNo && ` Job No: ${selectedJobNo}`}
            {selectedFilename && ` 파일: ${selectedFilename}`}
            {selectedRevision && ` 리비전: ${selectedRevision}`}
            {groupingType !== 'item' && ` 그룹핑: ${groupingType}`}
            {itemType && ` 품목: ${itemType}`}
            {materialGrade && ` 재질: ${materialGrade}`}
            {sizeSpec && ` 사이즈: ${sizeSpec}`}
            {fileFilter && ` 파일: ${fileFilter}`}
            {sortBy && ` 정렬: ${sortBy}`}
          </Typography>
        </Box>
      )}

      {loading ? (
        <Card>
          <CardContent sx={{ textAlign: 'center', py: 4 }}>
            <CircularProgress size={60} />
            <Typography variant="h6" sx={{ mt: 2 }}>
              자재 데이터 로딩 중...
            </Typography>
          </CardContent>
        </Card>
      ) : materials.length === 0 ? (
        <Card>
          <CardContent sx={{ textAlign: 'center', py: 4 }}>
            <Inventory sx={{ fontSize: 64, color: 'secondary.main', mb: 2 }} />
            <Typography variant="h6" gutterBottom>
              {search || searchValue || itemType || materialGrade || sizeSpec || fileFilter || selectedJobNo || selectedFilename || selectedRevision ? '검색 결과가 없습니다' : '자재 데이터가 없습니다'}
            </Typography>
            <Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
              {search || searchValue || itemType || materialGrade || sizeSpec || fileFilter || selectedJobNo || selectedFilename || selectedRevision 
                ? '다른 검색 조건을 시도해보세요.' 
                : '파일 업로드 탭에서 BOM 파일을 업로드해주세요.'
              }
            </Typography>
            {(search || searchValue || itemType || materialGrade || sizeSpec || fileFilter || selectedJobNo || selectedFilename || selectedRevision) && (
              <Button variant="outlined" onClick={clearFilters}>
                필터 초기화
              </Button>
            )}
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent>
            <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
              <Typography variant="h6">
                총 {totalCount.toLocaleString()}개 자재 그룹
              </Typography>
              <Chip 
                label={`${materials.length}개 표시 중`} 
                color="primary" 
                variant="outlined" 
              />
            </Box>
            
            <TableContainer component={Paper} variant="outlined">
              <Table>
                <TableHead>
                  <TableRow sx={{ bgcolor: 'grey.50' }}>
                    <TableCell><strong>번호</strong></TableCell>
                    <TableCell><strong>유형</strong></TableCell>
                    <TableCell><strong>자재명</strong></TableCell>
                    <TableCell align="center"><strong>총 수량</strong></TableCell>
                    <TableCell align="center"><strong>단위</strong></TableCell>
                    <TableCell align="center"><strong>사이즈</strong></TableCell>
                    <TableCell><strong>재질</strong></TableCell>
                    <TableCell align="center"><strong>Job No.</strong></TableCell>
                    <TableCell align="center"><strong>리비전</strong></TableCell>
                    <TableCell align="center"><strong>변경</strong></TableCell>
                    <TableCell align="center"><strong>라인 수</strong></TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {materials.map((material, index) => (
                    <TableRow 
                      key={`${material.id}-${index}`}
                      sx={{ '&:hover': { bgcolor: 'grey.50' } }}
                    >
                      <TableCell>
                        {page * rowsPerPage + index + 1}
                      </TableCell>
                      <TableCell>
                        <Chip 
                          label={material.item_type || 'OTHER'} 
                          size="small"
                          color={getItemTypeColor(material.item_type)}
                        />
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2" sx={{ maxWidth: 300 }}>
                          {material.original_description}
                        </Typography>
                      </TableCell>
                      <TableCell align="center">
                        <Typography variant="h6" color="primary">
                          {material.classified_category === 'PIPE' ? (() => {
                            const bomLength = material.pipe_details?.total_length_mm || 0;
                            const pipeCount = material.pipe_details?.pipe_count || 0;
                            const cuttingLoss = pipeCount * 2;
                            const requiredLength = bomLength + cuttingLoss;
                            const pipesNeeded = Math.ceil(requiredLength / 6000);
                            return pipesNeeded.toLocaleString();
                          })() : material.quantity.toLocaleString()}
                        </Typography>
                      </TableCell>
                      <TableCell align="center">
                        <Chip label={material.classified_category === 'PIPE' ? '본' : material.unit} size="small" />
                      </TableCell>
                      <TableCell align="center">
                        <Chip 
                          label={material.size_spec || '-'} 
                          size="small" 
                          color="secondary"
                        />
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2" color="primary">
                          {material.material_grade || '-'}
                        </Typography>
                      </TableCell>
                      <TableCell align="center">
                        <Chip 
                          label={material.job_number || '-'} 
                          size="small" 
                          color="info"
                        />
                      </TableCell>
                      <TableCell align="center">
                        <Chip 
                          label={material.revision || 'Rev.0'} 
                          size="small" 
                          color="warning"
                        />
                      </TableCell>
                      <TableCell align="center">
                        {material.quantity_change && (
                          <Chip 
                            label={`${material.quantity_change > 0 ? '+' : ''}${material.quantity_change}`}
                            size="small"
                            color={getRevisionChangeColor(material.quantity_change)}
                            icon={getRevisionChangeIcon(material.quantity_change)}
                          />
                        )}
                      </TableCell>
                      <TableCell align="center">
                        <Chip 
                          label={`${material.line_count || 1}개 라인`}
                          size="small"
                          variant="outlined"
                          title={material.line_numbers_str}
                        />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>

            <TablePagination
              component="div"
              count={totalCount}
              page={page}
              onPageChange={handleChangePage}
              rowsPerPage={rowsPerPage}
              onRowsPerPageChange={handleChangeRowsPerPage}
              rowsPerPageOptions={[10, 25, 50, 100]}
              labelRowsPerPage="페이지당 행 수:"
              labelDisplayedRows={({ from, to, count }) => 
                `${from}-${to} / 총 ${count !== -1 ? count : to} 개`
              }
            />
          </CardContent>
        </Card>
      )}
    </Box>
  );
}

MaterialList.propTypes = {
  selectedProject: PropTypes.shape({
    id: PropTypes.string.isRequired,
    project_name: PropTypes.string.isRequired,
    official_project_code: PropTypes.string.isRequired,
  }),
};

export default MaterialList;
