"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 DownloadIcon from '@mui/icons-material/Download';
import {
  fetchSemiFGItemCodes,
  fetchSemiFGItemCodesWithCategory,
  generateSemiFGProductionAnalysisReport,
  generateSemiFGProductionAnalysisReportExcel,
  ItemCodeWithCategory,
} from './semiFGProductionAnalysisApi';

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

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

  // 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 handleExportClick = async (format: 'pdf' | 'excel') => {
    setExportFormat(format);
    // Validate required fields
    if (requiredFieldLabels.length > 0) {
      alert(`缺少必填條件:\n- ${requiredFieldLabels.join('\n- ')}`);
      return;
    }

    // If no itemCode is selected, export directly without confirmation
    if (!criteria.itemCode) {
      await executeExport(format);
      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 executeExport = async (format: 'pdf' | 'excel' = exportFormat) => {
    setLoading(true);
    try {
      if (format === 'excel') {
        await generateSemiFGProductionAnalysisReportExcel(criteria, reportTitle);
      } else {
        await generateSemiFGProductionAnalysisReport(criteria, reportTitle);
      }
      onExportSuccess?.(format);
      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 (
    <>
      <div style={{ display: 'flex', gap: 16 }}>
        <Button
          variant="contained"
          size="large"
          startIcon={<DownloadIcon />}
          onClick={() => handleExportClick('pdf')}
          disabled={loading}
          sx={{ px: 4 }}
        >
          {loading ? '生成 PDF...' : '下載報告 (PDF)'}
        </Button>
        <Button
          variant="outlined"
          size="large"
          startIcon={<DownloadIcon />}
          onClick={() => handleExportClick('excel')}
          disabled={loading}
          sx={{ px: 4 }}
        >
          {loading ? '生成 Excel...' : '下載報告 (Excel)'}
        </Button>
      </div>

      {/* 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={() => executeExport()}
            disabled={loading}
            startIcon={<DownloadIcon />}
          >
            {loading
              ? exportFormat === 'excel'
                ? '生成 Excel...'
                : '生成 PDF...'
              : exportFormat === 'excel'
                ? '確認下載 Excel'
                : '確認下載 PDF'}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}
