"use client";

import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  Typography,
} from '@mui/material';
import PrintIcon from '@mui/icons-material/Print';
import {
  fetchSemiFGItemCodes,
  fetchSemiFGItemCodesWithCategory,
  generateSemiFGProductionAnalysisReport,
  ItemCodeWithCategory,
} from './semiFGProductionAnalysisApi';

interface SemiFGProductionAnalysisReportProps {
  criteria: Record<string, string>;
  requiredFieldLabels: string[];
  loading: boolean;
  setLoading: (loading: boolean) => void;
  reportTitle?: string;
}

export default function SemiFGProductionAnalysisReport({
  criteria,
  requiredFieldLabels,
  loading,
  setLoading,
  reportTitle = '成品/半成品生產分析報告',
}: SemiFGProductionAnalysisReportProps) {
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [selectedItemCodesInfo, setSelectedItemCodesInfo] = useState<ItemCodeWithCategory[]>([]);
  const [itemCodesWithCategory, setItemCodesWithCategory] = useState<Record<string, ItemCodeWithCategory>>({});

  // Fetch item codes with category when stockCategory changes
  useEffect(() => {
    const stockCategory = criteria.stockCategory || '';
    if (stockCategory) {
      fetchSemiFGItemCodesWithCategory(stockCategory)
        .then((items) => {
          const categoryMap: Record<string, ItemCodeWithCategory> = {};
          items.forEach((item) => {
            categoryMap[item.code] = item;
          });
          setItemCodesWithCategory((prev) => ({ ...prev, ...categoryMap }));
        })
        .catch((error) => {
          console.error('Failed to fetch item codes with category:', error);
        });
    }
  }, [criteria.stockCategory]);

  const handlePrintClick = async () => {
    // Validate required fields
    if (requiredFieldLabels.length > 0) {
      alert(`缺少必填條件:\n- ${requiredFieldLabels.join('\n- ')}`);
      return;
    }

    // If no itemCode is selected, print directly without confirmation
    if (!criteria.itemCode) {
      await executePrint();
      return;
    }

    // If itemCode is selected, show confirmation dialog
    const selectedCodes = criteria.itemCode.split(',').filter((code) => code.trim());
    const itemCodesInfo: ItemCodeWithCategory[] = selectedCodes.map((code) => {
      const codeTrimmed = code.trim();
      const categoryInfo = itemCodesWithCategory[codeTrimmed];
      return {
        code: codeTrimmed,
        category: categoryInfo?.category || 'Unknown',
        name: categoryInfo?.name || '',
      };
    });
    setSelectedItemCodesInfo(itemCodesInfo);
    setShowConfirmDialog(true);
  };

  const executePrint = async () => {
    setLoading(true);
    try {
      await generateSemiFGProductionAnalysisReport(criteria, reportTitle);
      setShowConfirmDialog(false);
    } catch (error) {
      console.error('Failed to generate report:', error);
      alert('An error occurred while generating the report. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Button
        variant="contained"
        size="large"
        startIcon={<PrintIcon />}
        onClick={handlePrintClick}
        disabled={loading}
        sx={{ px: 4 }}
      >
        {loading ? '生成報告...' : '列印報告'}
      </Button>

      {/* Confirmation Dialog for 成品/半成品生產分析報告 */}
      <Dialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          <Typography variant="h6" fontWeight="bold">
            已選擇的物料編號以及列印成品/半成品生產分析報告
          </Typography>
        </DialogTitle>
        <DialogContent>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            請確認以下已選擇的物料編號及其類別：
          </Typography>
          <TableContainer component={Paper} variant="outlined">
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>
                    <strong>物料編號及名稱</strong>
                  </TableCell>
                  <TableCell>
                    <strong>類別</strong>
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {selectedItemCodesInfo.map((item, index) => {
                  const displayName = item.name ? `${item.code} ${item.name}` : item.code;
                  return (
                    <TableRow key={index}>
                      <TableCell>{displayName}</TableCell>
                      <TableCell>
                        <Chip
                          label={item.category || 'Unknown'}
                          color={item.category === 'FG' ? 'primary' : item.category === 'WIP' ? 'secondary' : 'default'}
                          size="small"
                        />
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setShowConfirmDialog(false)}>取消</Button>
          <Button
            variant="contained"
            onClick={executePrint}
            disabled={loading}
            startIcon={<PrintIcon />}
          >
            {loading ? '生成報告...' : '確認列印報告'}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}
