import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  Alert,
  CircularProgress,
  Chip,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Tabs,
  Tab,
  Divider
} from '@mui/material';
import {
  ArrowBack,
  ShoppingCart,
  Compare,
  Add as AddIcon,
  Remove as RemoveIcon,
  TrendingUp,
  Assessment
} from '@mui/icons-material';
import { compareMaterialRevisions, fetchFiles } from '../api';

const RevisionPurchasePage = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [comparisonResult, setComparisonResult] = useState(null);
  const [availableRevisions, setAvailableRevisions] = useState([]);
  const [selectedTab, setSelectedTab] = useState(0);
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  
  // URL 파라미터에서 정보 추출
  const jobNo = searchParams.get('job_no');
  const currentRevision = searchParams.get('current_revision') || searchParams.get('revision');
  const previousRevision = searchParams.get('previous_revision');
  const bomName = searchParams.get('bom_name');

  useEffect(() => {
    if (jobNo && currentRevision) {
      loadAvailableRevisions();
      loadComparisonData();
    } else {
      setError('필수 파라미터가 누락되었습니다. (job_no, current_revision)');
      setLoading(false);
    }
  }, [jobNo, currentRevision, previousRevision]);

  const loadAvailableRevisions = async () => {
    try {
      const response = await fetchFiles({ job_no: jobNo });
      if (Array.isArray(response.data)) {
        // BOM별로 그룹화
        const bomGroups = response.data.reduce((acc, file) => {
          const key = file.bom_name || file.original_filename;
          if (!acc[key]) acc[key] = [];
          acc[key].push(file);
          return acc;
        }, {});
        
        // 현재 BOM과 관련된 리비전들만 필터링
        let relevantFiles = [];
        if (bomName) {
          relevantFiles = bomGroups[bomName] || [];
        } else {
          // bomName이 없으면 현재 리비전과 같은 원본파일명을 가진 것들
          const currentFile = response.data.find(file => file.revision === currentRevision);
          if (currentFile) {
            const key = currentFile.bom_name || currentFile.original_filename;
            relevantFiles = bomGroups[key] || [];
          }
        }
        
        // 리비전 순으로 정렬
        relevantFiles.sort((a, b) => {
          const revA = parseInt(a.revision?.replace('Rev.', '') || '0');
          const revB = parseInt(b.revision?.replace('Rev.', '') || '0');
          return revB - revA;
        });
        
        setAvailableRevisions(relevantFiles);
      }
    } catch (err) {
      console.error('리비전 목록 로드 실패:', err);
    }
  };

  const loadComparisonData = async () => {
    try {
      setLoading(true);
      const result = await compareMaterialRevisions(
        jobNo,
        currentRevision,
        previousRevision,
        true
      );
      setComparisonResult(result);
    } catch (err) {
      setError(`리비전 비교 실패: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleRevisionChange = (type, newRevision) => {
    const params = new URLSearchParams(searchParams);
    if (type === 'current') {
      params.set('current_revision', newRevision);
    } else {
      params.set('previous_revision', newRevision);
    }
    navigate(`?${params.toString()}`, { replace: true });
  };

  const calculatePurchaseNeeds = () => {
    if (!comparisonResult) return { newItems: [], increasedItems: [] };
    
    const newItems = comparisonResult.new_items || [];
    const modifiedItems = comparisonResult.modified_items || [];
    
    // 수량이 증가한 항목들만 필터링
    const increasedItems = modifiedItems.filter(item => 
      item.quantity_change > 0
    );
    
    return { newItems, increasedItems };
  };

  const formatCurrency = (amount) => {
    return new Intl.NumberFormat('ko-KR', {
      style: 'currency',
      currency: 'KRW'
    }).format(amount);
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <CircularProgress />
        <Typography variant="h6" sx={{ ml: 2 }}>
          리비전 비교 분석 중...
        </Typography>
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ maxWidth: 1200, mx: 'auto', mt: 4, px: 2 }}>
        <Button
          variant="outlined"
          startIcon={<ArrowBack />}
          onClick={() => navigate(`/bom-status?job_no=${jobNo}`)}
          sx={{ mb: 2 }}
        >
          BOM 목록으로
        </Button>
        <Alert severity="error">{error}</Alert>
      </Box>
    );
  }

  const { newItems, increasedItems } = calculatePurchaseNeeds();
  const totalNewItems = newItems.length;
  const totalIncreasedItems = increasedItems.length;
  const totalPurchaseItems = totalNewItems + totalIncreasedItems;

  return (
    <Box sx={{ maxWidth: 1400, mx: 'auto', mt: 4, px: 2 }}>
      {/* 헤더 */}
      <Box sx={{ mb: 3 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
          <Button
            variant="outlined"
            startIcon={<ArrowBack />}
            onClick={() => navigate(`/bom-status?job_no=${jobNo}`)}
          >
            BOM 목록으로
          </Button>
          
          <Box sx={{ display: 'flex', gap: 2 }}>
            <Button
              variant="outlined"
              startIcon={<Assessment />}
              onClick={() => navigate(`/material-comparison?job_no=${jobNo}&revision=${currentRevision}&prev_revision=${previousRevision}`)}
            >
              상세 비교 보기
            </Button>
            
            <Button
              variant="contained"
              color="success"
              startIcon={<ShoppingCart />}
              disabled={totalPurchaseItems === 0}
            >
              구매 목록 생성
            </Button>
          </Box>
        </Box>

        <Typography variant="h4" gutterBottom>
          🛒 리비전간 추가 구매 필요 자재
        </Typography>
        
        <Typography variant="h6" color="textSecondary">
          Job No: {jobNo} | {currentRevision} vs {previousRevision || '이전 리비전'}
        </Typography>
      </Box>

      {/* 리비전 선택 카드 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            리비전 비교 설정
          </Typography>
          <Grid container spacing={3}>
            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>현재 리비전</InputLabel>
                <Select
                  value={currentRevision}
                  label="현재 리비전"
                  onChange={(e) => handleRevisionChange('current', e.target.value)}
                >
                  {availableRevisions.map((file) => (
                    <MenuItem key={file.id} value={file.revision}>
                      {file.revision} ({file.parsed_count || 0}개 자재)
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>이전 리비전</InputLabel>
                <Select
                  value={previousRevision || ''}
                  label="이전 리비전"
                  onChange={(e) => handleRevisionChange('previous', e.target.value)}
                >
                  <MenuItem value="">자동 선택 (직전 리비전)</MenuItem>
                  {availableRevisions
                    .filter(file => file.revision !== currentRevision)
                    .map((file) => (
                      <MenuItem key={file.id} value={file.revision}>
                        {file.revision} ({file.parsed_count || 0}개 자재)
                      </MenuItem>
                    ))}
                </Select>
              </FormControl>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 구매 요약 */}
      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={12} md={4}>
          <Card>
            <CardContent sx={{ textAlign: 'center' }}>
              <AddIcon color="primary" sx={{ fontSize: 48, mb: 1 }} />
              <Typography variant="h4" color="primary">
                {totalNewItems}
              </Typography>
              <Typography variant="h6">
                신규 자재
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={4}>
          <Card>
            <CardContent sx={{ textAlign: 'center' }}>
              <TrendingUp color="warning" sx={{ fontSize: 48, mb: 1 }} />
              <Typography variant="h4" color="warning.main">
                {totalIncreasedItems}
              </Typography>
              <Typography variant="h6">
                수량 증가
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={4}>
          <Card>
            <CardContent sx={{ textAlign: 'center' }}>
              <ShoppingCart color="success" sx={{ fontSize: 48, mb: 1 }} />
              <Typography variant="h4" color="success.main">
                {totalPurchaseItems}
              </Typography>
              <Typography variant="h6">
                총 구매 항목
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 탭으로 구분된 자재 목록 */}
      <Card>
        <Tabs
          value={selectedTab}
          onChange={(e, newValue) => setSelectedTab(newValue)}
          variant="fullWidth"
        >
          <Tab label={`신규 자재 (${totalNewItems})`} />
          <Tab label={`수량 증가 (${totalIncreasedItems})`} />
        </Tabs>

        <CardContent>
          {selectedTab === 0 && (
            <Box>
              <Typography variant="h6" gutterBottom color="primary">
                🆕 신규 추가 자재
              </Typography>
              {newItems.length === 0 ? (
                <Alert severity="info">새로 추가된 자재가 없습니다.</Alert>
              ) : (
                <TableContainer component={Paper} variant="outlined">
                  <Table size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell>카테고리</TableCell>
                        <TableCell>자재 설명</TableCell>
                        <TableCell>사이즈</TableCell>
                        <TableCell>재질</TableCell>
                        <TableCell>수량</TableCell>
                        <TableCell>단위</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {newItems.map((item, index) => (
                        <TableRow key={index}>
                          <TableCell>
                            <Chip 
                              label={item.category} 
                              size="small" 
                              color="primary"
                            />
                          </TableCell>
                          <TableCell>{item.description}</TableCell>
                          <TableCell>{item.size_spec || '-'}</TableCell>
                          <TableCell>{item.material_grade || '-'}</TableCell>
                          <TableCell>
                            <Typography variant="body2" fontWeight="bold" color="primary">
                              +{item.quantity}
                            </Typography>
                          </TableCell>
                          <TableCell>{item.unit || 'EA'}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              )}
            </Box>
          )}

          {selectedTab === 1 && (
            <Box>
              <Typography variant="h6" gutterBottom color="warning.main">
                📈 수량 증가 자재
              </Typography>
              {increasedItems.length === 0 ? (
                <Alert severity="info">수량이 증가한 자재가 없습니다.</Alert>
              ) : (
                <TableContainer component={Paper} variant="outlined">
                  <Table size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell>카테고리</TableCell>
                        <TableCell>자재 설명</TableCell>
                        <TableCell>사이즈</TableCell>
                        <TableCell>재질</TableCell>
                        <TableCell>이전 수량</TableCell>
                        <TableCell>현재 수량</TableCell>
                        <TableCell>증가량</TableCell>
                        <TableCell>단위</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {increasedItems.map((item, index) => (
                        <TableRow key={index}>
                          <TableCell>
                            <Chip 
                              label={item.category} 
                              size="small" 
                              color="warning"
                            />
                          </TableCell>
                          <TableCell>{item.description}</TableCell>
                          <TableCell>{item.size_spec || '-'}</TableCell>
                          <TableCell>{item.material_grade || '-'}</TableCell>
                          <TableCell>{item.previous_quantity}</TableCell>
                          <TableCell>{item.current_quantity}</TableCell>
                          <TableCell>
                            <Typography variant="body2" fontWeight="bold" color="warning.main">
                              +{item.quantity_change}
                            </Typography>
                          </TableCell>
                          <TableCell>{item.unit || 'EA'}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              )}
            </Box>
          )}
        </CardContent>
      </Card>

      {totalPurchaseItems === 0 && (
        <Alert severity="success" sx={{ mt: 3 }}>
          🎉 추가로 구매가 필요한 자재가 없습니다!
        </Alert>
      )}
    </Box>
  );
};

export default RevisionPurchasePage; 