// resources/assets/ts/ContactsPage/components/ContactsAddMultipleEmployees/EmployeesImportResults.tsx

/**
 * Employee Import Results Component
 * 
 * Displays the results of the import operation with:
 * - Summary statistics
 * - Detailed breakdown per row (with company info)
 * - Options to start new import or go back
 */

import React, { useState } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import Alert from '@mui/material/Alert';
import Chip from '@mui/material/Chip';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Collapse from '@mui/material/Collapse';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import {
  CheckCircle as CheckCircleIcon,
  Error as ErrorIcon,
  Warning as WarningIcon,
  KeyboardArrowDown as KeyboardArrowDownIcon,
  KeyboardArrowUp as KeyboardArrowUpIcon,
  Refresh as RefreshIcon,
  ArrowBack as ArrowBackIcon,
  Business as BusinessIcon,
} from '@mui/icons-material';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';

interface ImportResult {
  success: boolean;
  total: number;
  imported: number;
  skipped: number;
  errors: number;
  details: {
    rowNumber: number;
    status: 'success' | 'skipped' | 'error';
    message: string;
    employeeId?: number;
    firmenname?: string;
    adressid?: number;
  }[];
}

interface EmployeesImportResultsProps {
  result: ImportResult;
  onReset: () => void;
  onBack?: () => void;
  showCompanyColumn?: boolean;
}

const EmployeesImportResults: React.FC<EmployeesImportResultsProps> = ({
  result,
  onReset,
  onBack,
  showCompanyColumn = false,
}) => {
  const { i18n } = useLingui();
  const [showDetails, setShowDetails] = useState(false);

  // Count unique companies in successful imports
  const successfulCompanyIds = new Set(
    result.details
      .filter(d => d.status === 'success' && d.adressid)
      .map(d => d.adressid)
  );

  const getAlertSeverity = () => {
    if (result.imported === 0 && result.errors > 0) return 'error';
    if (result.imported > 0 && result.errors > 0) return 'warning';
    if (result.imported > 0) return 'success';
    return 'info';
  };

  const getAlertMessage = () => {
    if (result.imported === 0 && result.errors > 0) {
      return i18n._(msg`No employees could be imported.`);
    }
    if (result.imported > 0 && result.errors > 0) {
      return i18n._(msg`Import completed with ${result.errors} errors.`);
    }
    if (result.imported > 0) {
      if (showCompanyColumn && successfulCompanyIds.size > 1) {
        return i18n._(msg`Import completed successfully! ${result.imported} employees imported to ${successfulCompanyIds.size} companies.`);
      }
      return i18n._(msg`Import completed successfully! ${result.imported} employees imported.`);
    }
    return i18n._(msg`Import complete`);
  };

  return (
    <Box>
      <Alert
        severity={getAlertSeverity()}
        sx={{ mb: 3 }}
        icon={result.success ? <CheckCircleIcon /> : <ErrorIcon />}
      >
        <Typography variant="subtitle1" fontWeight={600}>
          {getAlertMessage()}
        </Typography>
      </Alert>

      {/* Summary Statistics */}
      <Paper variant="outlined" sx={{ p: 3, mb: 3 }}>
        <Typography variant="h6" gutterBottom>
          <Trans>Summary</Trans>
        </Typography>
        <List dense>
          <ListItem>
            <ListItemText
              primary={i18n._(msg`Total rows`)}
              secondary={result.total}
              primaryTypographyProps={{ fontWeight: 500 }}
            />
          </ListItem>
          <ListItem>
            <ListItemText
              primary={
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <CheckCircleIcon color="success" fontSize="small" />
                  <span><Trans>Imported successfully</Trans></span>
                </Box>
              }
              secondary={result.imported}
              primaryTypographyProps={{ fontWeight: 500 }}
            />
          </ListItem>
          {showCompanyColumn && successfulCompanyIds.size > 0 && (
            <ListItem>
              <ListItemText
                primary={
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <BusinessIcon color="info" fontSize="small" />
                    <span><Trans>Affected companies</Trans></span>
                  </Box>
                }
                secondary={successfulCompanyIds.size}
                primaryTypographyProps={{ fontWeight: 500 }}
              />
            </ListItem>
          )}
          {result.skipped > 0 && (
            <ListItem>
              <ListItemText
                primary={
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <WarningIcon color="warning" fontSize="small" />
                    <span><Trans>Duplicates skipped</Trans></span>
                  </Box>
                }
                secondary={result.skipped}
                primaryTypographyProps={{ fontWeight: 500 }}
              />
            </ListItem>
          )}
          {result.errors > 0 && (
            <ListItem>
              <ListItemText
                primary={
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <ErrorIcon color="error" fontSize="small" />
                    <span><Trans>Errors</Trans></span>
                  </Box>
                }
                secondary={result.errors}
                primaryTypographyProps={{ fontWeight: 500 }}
              />
            </ListItem>
          )}
        </List>

        {/* Success message for imported with override */}
        {result.details.some(d => d.status === 'success' && d.message.includes('überschrieben')) && (
          <Alert severity="info" sx={{ mt: 2 }}>
            <Typography variant="body2">
              <Trans>Some employees were imported despite the duplicate warning (manual confirmation).</Trans>
            </Typography>
          </Alert>
        )}
      </Paper>

      {/* Detailed Results Table */}
      <Box>
        <Button
          onClick={() => setShowDetails(!showDetails)}
          endIcon={showDetails ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
          sx={{ mb: 2, textTransform: 'none' }}
        >
          {showDetails ? i18n._(msg`Hide details`) : i18n._(msg`Show details`)}
        </Button>

        <Collapse in={showDetails}>
          <TableContainer component={Paper} variant="outlined">
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell><Trans>Row</Trans></TableCell>
                  <TableCell><Trans>Status</Trans></TableCell>
                  {showCompanyColumn && <TableCell><Trans>Company ID</Trans></TableCell>}
                  <TableCell><Trans>Message</Trans></TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {result.details.map((detail, index) => (
                  <TableRow
                    key={index}
                    sx={{
                      backgroundColor:
                        detail.status === 'success'
                          ? 'rgba(76, 175, 80, 0.08)'
                          : detail.status === 'skipped'
                            ? 'rgba(255, 152, 0, 0.08)'
                            : 'rgba(244, 67, 54, 0.08)',
                    }}
                  >
                    <TableCell>{detail.rowNumber}</TableCell>
                    <TableCell>
                      {detail.status === 'success' && (
                        <Chip
                          icon={<CheckCircleIcon />}
                          label={i18n._(msg`Success`)}
                          size="small"
                          color="success"
                        />
                      )}
                      {detail.status === 'skipped' && (
                        <Chip
                          icon={<WarningIcon />}
                          label={i18n._(msg`Skipped`)}
                          size="small"
                          color="warning"
                        />
                      )}
                      {detail.status === 'error' && (
                        <Chip
                          icon={<ErrorIcon />}
                          label={i18n._(msg`Error`)}
                          size="small"
                          color="error"
                        />
                      )}
                    </TableCell>
                    {showCompanyColumn && (
                      <TableCell>
                        {detail.adressid || '-'}
                      </TableCell>
                    )}
                    <TableCell>
                      <Typography variant="body2" color="text.secondary">
                        {detail.message}
                      </Typography>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Collapse>
      </Box>

      {/* Action Buttons */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 3, gap: 2 }}>
        {/* Left side - Back button */}
        {onBack && (
          <Button
            variant="contained"
            color="primary"
            startIcon={<ArrowBackIcon />}
            onClick={onBack}
            sx={{ textTransform: 'none' }}
          >
            <Trans>Back to overview</Trans>
          </Button>
        )}

        {/* Right side - New import */}
        <Button
          variant="outlined"
          startIcon={<RefreshIcon />}
          onClick={onReset}
          sx={{ textTransform: 'none', ml: 'auto' }}
        >
          <Trans>Start new import</Trans>
        </Button>
      </Box>
    </Box>
  );
};

export default EmployeesImportResults;
