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

/**
 * Employee Import Preview Component
 * 
 * KEY FEATURE: Duplicates show checkboxes to "Import anyway"
 * This allows users to import employees with common names
 * 
 * Now also shows company ID (adressid) column for multi-company imports
 */

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 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 Chip from '@mui/material/Chip';
import Collapse from '@mui/material/Collapse';
import IconButton from '@mui/material/IconButton';
import Alert from '@mui/material/Alert';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Tooltip from '@mui/material/Tooltip';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import {
  CheckCircle as CheckCircleIcon,
  Error as ErrorIcon,
  Warning as WarningIcon,
  KeyboardArrowDown as KeyboardArrowDownIcon,
  KeyboardArrowUp as KeyboardArrowUpIcon,
  Info as InfoIcon,
  HelpOutline as HelpOutlineIcon,
  Business as BusinessIcon,
} from '@mui/icons-material';
import { EmployeePreview } from '../../utils/employeeCsvImportUtils';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

const TabPanel: React.FC<TabPanelProps> = ({ children, value, index }) => {
  return (
    <div hidden={value !== index} style={{ paddingTop: '16px' }}>
      {value === index && children}
    </div>
  );
};

interface EmployeesImportPreviewProps {
  employees: EmployeePreview[];
  onConfirm: () => void;
  onCancel: () => void;
  onToggleImportAnyway: (rowNumber: number) => void;
  onToggleAllDuplicates: (importAll: boolean) => void;
  showCompanyColumn?: boolean;
}

const EmployeesImportPreview: React.FC<EmployeesImportPreviewProps> = ({
  employees,
  onConfirm,
  onCancel,
  onToggleImportAnyway,
  onToggleAllDuplicates,
  showCompanyColumn = false,
}) => {
  const { i18n } = useLingui();
  const [tabValue, setTabValue] = useState(0);
  const [expandedRows, setExpandedRows] = useState<Set<number>>(new Set());

  // Categorize employees
  const validEmployees = employees.filter(e => e.validation.valid && !e.duplicateCheck.isDuplicate);
  const duplicateEmployees = employees.filter(e => e.validation.valid && e.duplicateCheck.isDuplicate);
  const errorEmployees = employees.filter(e => !e.validation.valid);

  // Count how many duplicates will be imported
  const duplicatesToImport = duplicateEmployees.filter(e => e.importAnyway).length;
  const totalToImport = validEmployees.length + duplicatesToImport;

  // Count unique companies
  const uniqueCompanies = new Set(employees.filter(e => e.adressid).map(e => e.adressid)).size;

  // Check if all duplicates are selected
  const allDuplicatesSelected = duplicateEmployees.length > 0 && 
    duplicateEmployees.every(e => e.importAnyway);
  const someDuplicatesSelected = duplicateEmployees.some(e => e.importAnyway);

  const toggleRowExpansion = (rowNumber: number) => {
    const newExpanded = new Set(expandedRows);
    if (newExpanded.has(rowNumber)) {
      newExpanded.delete(rowNumber);
    } else {
      newExpanded.add(rowNumber);
    }
    setExpandedRows(newExpanded);
  };

  const getStatusChip = (employee: EmployeePreview) => {
    if (!employee.validation.valid) {
      return (
        <Chip
          icon={<ErrorIcon />}
          label={i18n._(msg`Error`)}
          size="small"
          color="error"
        />
      );
    }
    if (employee.duplicateCheck.isDuplicate) {
      if (employee.importAnyway) {
        return (
          <Chip
            icon={<CheckCircleIcon />}
            label={i18n._(msg`Will be imported`)}
            size="small"
            color="success"
            variant="outlined"
          />
        );
      }
      return (
        <Chip
          icon={<WarningIcon />}
          label={i18n._(msg`Possible duplicate`)}
          size="small"
          color="warning"
        />
      );
    }
    return (
      <Chip
        icon={<CheckCircleIcon />}
        label={i18n._(msg`Ready`)}
        size="small"
        color="success"
      />
    );
  };

  const renderEmployeeRow = (employee: EmployeePreview, showDuplicateCheckbox: boolean = false) => {
    const isExpanded = expandedRows.has(employee.rowNumber);
    const fullName = [employee.vorname, employee.Name].filter(Boolean).join(' ') || '-';
    const colSpan = showCompanyColumn ? 8 : 7;

    return (
      <React.Fragment key={employee.rowNumber}>
        <TableRow
          sx={{
            backgroundColor: 
              !employee.validation.valid ? 'rgba(244, 67, 54, 0.08)' :
              employee.duplicateCheck.isDuplicate && !employee.importAnyway ? 'rgba(255, 152, 0, 0.08)' :
              'rgba(76, 175, 80, 0.08)',
          }}
        >
          <TableCell>
            <IconButton
              size="small"
              onClick={() => toggleRowExpansion(employee.rowNumber)}
            >
              {isExpanded ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
            </IconButton>
          </TableCell>
          <TableCell>{employee.rowNumber}</TableCell>
          <TableCell>{getStatusChip(employee)}</TableCell>
          {showCompanyColumn && (
            <TableCell>
              <Tooltip title={i18n._(msg`Company ID (adressid)`)}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  <BusinessIcon fontSize="small" color="action" />
                  {employee.adressid || <ErrorIcon fontSize="small" color="error" />}
                </Box>
              </Tooltip>
            </TableCell>
          )}
          <TableCell>{fullName}</TableCell>
          <TableCell>{employee.email || '-'}</TableCell>
          <TableCell>{employee.dw1 || '-'}</TableCell>
          <TableCell>
            {/* Show checkbox for duplicates */}
            {showDuplicateCheckbox && employee.duplicateCheck.isDuplicate && (
              <Checkbox
                checked={employee.importAnyway}
                onChange={() => onToggleImportAnyway(employee.rowNumber)}
                size="small"
                color="primary"
              />
            )}
            {/* Show warning/error icons */}
            {employee.validation.errors.length > 0 && (
              <Tooltip title={employee.validation.errors.join(', ')}>
                <ErrorIcon color="error" fontSize="small" sx={{ ml: 1 }} />
              </Tooltip>
            )}
            {employee.duplicateCheck.isDuplicate && (
              <Tooltip title={employee.duplicateCheck.reason}>
                <WarningIcon color="warning" fontSize="small" sx={{ ml: 1 }} />
              </Tooltip>
            )}
          </TableCell>
        </TableRow>
        
        {/* Expanded Details */}
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={colSpan}>
            <Collapse in={isExpanded} timeout="auto" unmountOnExit>
              <Box sx={{ margin: 2 }}>
                <Typography variant="subtitle2" gutterBottom>
                  <Trans>Details</Trans>
                </Typography>
                <Paper variant="outlined" sx={{ p: 2 }}>
                  <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 2 }}>
                    {showCompanyColumn && (
                      <Box>
                        <Typography variant="caption" color="text.secondary"><Trans>Company ID (adressid):</Trans></Typography>
                        <Typography variant="body2" color={employee.adressid ? 'text.primary' : 'error'}>
                          {employee.adressid || i18n._(msg`MISSING!`)}
                        </Typography>
                      </Box>
                    )}
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>Salutation:</Trans></Typography>
                      <Typography variant="body2">{employee.MW || '-'}</Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>Last name:</Trans></Typography>
                      <Typography variant="body2">{employee.Name || '-'}</Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>First name:</Trans></Typography>
                      <Typography variant="body2">{employee.vorname || '-'}</Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>Email:</Trans></Typography>
                      <Typography variant="body2">{employee.email || '-'}</Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>Phone 1:</Trans></Typography>
                      <Typography variant="body2">{employee.dw1 || '-'}</Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>Phone 2:</Trans></Typography>
                      <Typography variant="body2">{employee.dw2 || '-'}</Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>Phone 3:</Trans></Typography>
                      <Typography variant="body2">{employee.dw3 || '-'}</Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>Phone 4:</Trans></Typography>
                      <Typography variant="body2">{employee.dw4 || '-'}</Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary"><Trans>Fax:</Trans></Typography>
                      <Typography variant="body2">{employee.fax || '-'}</Typography>
                    </Box>
                    <Box sx={{ gridColumn: 'span 3' }}>
                      <Typography variant="caption" color="text.secondary"><Trans>Note:</Trans></Typography>
                      <Typography variant="body2">{employee.bemerkung || '-'}</Typography>
                    </Box>
                  </Box>
                  
                  {/* Show validation errors */}
                  {employee.validation.errors.length > 0 && (
                    <Alert severity="error" sx={{ mt: 2 }}>
                      <Typography variant="subtitle2"><Trans>Errors:</Trans></Typography>
                      <ul style={{ margin: 0, paddingLeft: '20px' }}>
                        {employee.validation.errors.map((error, i) => (
                          <li key={i}>{error}</li>
                        ))}
                      </ul>
                    </Alert>
                  )}

                  {/* Show validation warnings */}
                  {employee.validation.warnings.length > 0 && (
                    <Alert severity="info" sx={{ mt: 2 }}>
                      <Typography variant="subtitle2"><Trans>Notes:</Trans></Typography>
                      <ul style={{ margin: 0, paddingLeft: '20px' }}>
                        {employee.validation.warnings.map((warning, i) => (
                          <li key={i}>{warning}</li>
                        ))}
                      </ul>
                    </Alert>
                  )}
                  
                  {/* Show duplicate warning with option */}
                  {employee.duplicateCheck.isDuplicate && (
                    <Alert 
                      severity="warning" 
                      sx={{ mt: 2 }}
                      action={
                        <FormControlLabel
                          control={
                            <Checkbox
                              checked={employee.importAnyway}
                              onChange={() => onToggleImportAnyway(employee.rowNumber)}
                              size="small"
                            />
                          }
                          label={i18n._(msg`Import anyway`)}
                        />
                      }
                    >
                      <Typography variant="body2">
                        <strong><Trans>Possible duplicate:</Trans></strong> {employee.duplicateCheck.reason}
                      </Typography>
                    </Alert>
                  )}
                </Paper>
              </Box>
            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  };

  const renderTable = (employeeList: EmployeePreview[], showDuplicateCheckbox: boolean = false) => (
    <TableContainer component={Paper}>
      <Table size="small">
        <TableHead>
          <TableRow>
            <TableCell width="50px"></TableCell>
            <TableCell><Trans>Row</Trans></TableCell>
            <TableCell><Trans>Status</Trans></TableCell>
            {showCompanyColumn && <TableCell><Trans>Company ID</Trans></TableCell>}
            <TableCell><Trans>Name</Trans></TableCell>
            <TableCell><Trans>Email</Trans></TableCell>
            <TableCell><Trans>Phone</Trans></TableCell>
            <TableCell width="100px">
              {showDuplicateCheckbox ? i18n._(msg`Import`) : ''}
            </TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {employeeList.map(employee => renderEmployeeRow(employee, showDuplicateCheckbox))}
        </TableBody>
      </Table>
    </TableContainer>
  );

  return (
    <Box>
      {/* Summary Statistics */}
      <Paper variant="outlined" sx={{ p: 3, mb: 3 }}>
        <Typography variant="h6" gutterBottom>
          <Trans>Import preview</Trans>
        </Typography>
        <Box sx={{ display: 'flex', gap: 3, mt: 2, flexWrap: 'wrap' }}>
          <Box>
            <Typography variant="h4" color="success.main">
              {validEmployees.length}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              <Trans>Ready to import</Trans>
            </Typography>
          </Box>
          <Box>
            <Typography variant="h4" color="warning.main">
              {duplicateEmployees.length}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              <Trans>Possible duplicates</Trans>
            </Typography>
          </Box>
          <Box>
            <Typography variant="h4" color="error.main">
              {errorEmployees.length}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              <Trans>Errors (will be skipped)</Trans>
            </Typography>
          </Box>
          {showCompanyColumn && uniqueCompanies > 0 && (
            <Box>
              <Typography variant="h4" color="info.main">
                {uniqueCompanies}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {uniqueCompanies === 1 ? i18n._(msg`Company`) : i18n._(msg`Companies`)}
              </Typography>
            </Box>
          )}
        </Box>

        {/* Duplicate import info */}
        {duplicateEmployees.length > 0 && (
          <Alert 
            severity="info" 
            sx={{ mt: 2 }}
            icon={<HelpOutlineIcon />}
          >
            <Typography variant="body2">
              <Trans>
                <strong>{duplicatesToImport} of {duplicateEmployees.length}</strong> possible duplicates will be imported. In the "Possible duplicates" tab you can individually choose which ones to import anyway.
              </Trans>
            </Typography>
          </Alert>
        )}

        {totalToImport === 0 && (
          <Alert severity="warning" sx={{ mt: 2 }}>
            <Trans>No employees selected to import.</Trans>
          </Alert>
        )}
      </Paper>

      {/* Tabs */}
      <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}>
        <Tabs value={tabValue} onChange={(e, newValue) => setTabValue(newValue)}>
          <Tab
            label={i18n._(msg`All (${employees.length})`)}
            icon={<InfoIcon />}
            iconPosition="start"
          />
          <Tab
            label={i18n._(msg`Ready (${validEmployees.length})`)}
            icon={<CheckCircleIcon />}
            iconPosition="start"
          />
          <Tab
            label={i18n._(msg`Possible duplicates (${duplicateEmployees.length})`)}
            icon={<WarningIcon />}
            iconPosition="start"
          />
          <Tab
            label={i18n._(msg`Errors (${errorEmployees.length})`)}
            icon={<ErrorIcon />}
            iconPosition="start"
          />
        </Tabs>
      </Box>

      {/* Tab Panels */}
      <TabPanel value={tabValue} index={0}>
        {renderTable(employees, true)}
      </TabPanel>

      <TabPanel value={tabValue} index={1}>
        {renderTable(validEmployees)}
      </TabPanel>

      <TabPanel value={tabValue} index={2}>
        {duplicateEmployees.length > 0 ? (
          <>
            {/* Bulk select for duplicates */}
            <Box sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 2 }}>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={allDuplicatesSelected}
                    indeterminate={someDuplicatesSelected && !allDuplicatesSelected}
                    onChange={(e) => onToggleAllDuplicates(e.target.checked)}
                  />
                }
                label={i18n._(msg`Import all duplicates anyway`)}
              />
              <Tooltip title={i18n._(msg`Common names like 'Müller' or 'Schmidt' may belong to different people`)}>
                <HelpOutlineIcon fontSize="small" color="action" />
              </Tooltip>
            </Box>
            {renderTable(duplicateEmployees, true)}
          </>
        ) : (
          <Typography color="text.secondary"><Trans>No duplicates found.</Trans></Typography>
        )}
      </TabPanel>

      <TabPanel value={tabValue} index={3}>
        {errorEmployees.length > 0 ? (
          renderTable(errorEmployees)
        ) : (
          <Typography color="text.secondary"><Trans>No errors found.</Trans></Typography>
        )}
      </TabPanel>

      {/* Action Buttons */}
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2, mt: 3 }}>
        <Button
          variant="outlined"
          color="error"
          onClick={onCancel}
          sx={{ textTransform: 'none' }}
        >
          <Trans>Cancel</Trans>
        </Button>
        <Button
          variant="contained"
          color="success"
          onClick={onConfirm}
          disabled={totalToImport === 0}
          sx={{ textTransform: 'none' }}
        >
          {i18n._(msg`Import ${totalToImport} employees`)}
        </Button>
      </Box>
    </Box>
  );
};

export default EmployeesImportPreview;
