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

/**
 * Employee CSV Import Component - Main Orchestrator
 * 
 * Features:
 * - CSV template download (with adressid column for multi-company)
 * - File upload and parsing
 * - Validation and duplicate detection (with override option!)
 * - Preview before import
 * - Bulk import processing across MULTIPLE companies
 * 
 * Key difference from Contact import:
 * - Duplicates show WARNING, not block
 * - Users can check "Import anyway" for duplicates
 * - Supports importing to multiple companies in one CSV
 */

import React, { useState, useRef } 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 LinearProgress from '@mui/material/LinearProgress';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepLabel from '@mui/material/StepLabel';
import {
  CloudUpload as CloudUploadIcon,
  Download as DownloadIcon,
  ArrowBack as ArrowBackIcon,
} from '@mui/icons-material';
import EmployeesImportPreview from './EmployeesImportPreview';
import EmployeesImportResults from './EmployeesImportResults';
import {
  parseCSV,
  validateEmployee,
  checkDuplicate,
  bulkImportEmployees,
  generateCSVTemplate,
  EmployeePreview,
  ParsedEmployee,
} from '../../utils/employeeCsvImportUtils';
import { DRAWER_WIDTH } from '../ContactsSidebar';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';

interface EmployeesAddMultipleProps {
  onSuccess?: () => void;
  onBack?: () => void;
}

type ImportStep = 'upload' | 'preview' | 'importing' | 'results';

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;
  }[];
}

const EmployeesAddMultiple: React.FC<EmployeesAddMultipleProps> = ({
  onSuccess,
  onBack,
}) => {
  const { i18n } = useLingui();
  const [currentStep, setCurrentStep] = useState<ImportStep>('upload');
  const [file, setFile] = useState<File | null>(null);
  const [parsedEmployees, setParsedEmployees] = useState<EmployeePreview[]>([]);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [validating, setValidating] = useState(false);
  const [importProgress, setImportProgress] = useState({ current: 0, total: 0 });
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = event.target.files?.[0];
    if (selectedFile) {
      if (!selectedFile.name.endsWith('.csv')) {
        alert(i18n._(msg`Please select a CSV file.`));
        return;
      }
      setFile(selectedFile);
      setParsedEmployees([]);
      setImportResult(null);
      setCurrentStep('upload');
    }
  };

  const handleFileValidation = async () => {
    if (!file) return;

    setValidating(true);

    try {
      const text = await file.text();
      const employees = parseCSV(text);

      if (employees.length === 0) {
        alert(i18n._(msg`The CSV file is empty or has an invalid format.`));
        setValidating(false);
        return;
      }

      // Validate and check duplicates for each employee
      const previews: EmployeePreview[] = [];

      for (let i = 0; i < employees.length; i++) {
        const employee = employees[i] as ParsedEmployee;

        // Validate with requireAdressid = true (multi-company mode)
        const validation = validateEmployee(employee, true);

        // Check for duplicates (only if validation passed and has adressid)
        let duplicateCheck = { isDuplicate: false, reason: '', matchType: null as any };

        if (validation.valid && employee.adressid) {
          duplicateCheck = await checkDuplicate(employee, employee.adressid);
        }

        previews.push({
          ...employee,
          rowNumber: i + 2, // +2 because row 1 is header
          validation,
          duplicateCheck,
          importAnyway: false, // Default: don't import duplicates
        });
      }

      setParsedEmployees(previews);
      setCurrentStep('preview');
    } catch (error) {
      console.error('CSV validation error:', error);
      alert(i18n._(msg`Error validating the CSV file. Please check the format.`));
    } finally {
      setValidating(false);
    }
  };

  const handleToggleImportAnyway = (rowNumber: number) => {
    setParsedEmployees(prev =>
      prev.map(emp =>
        emp.rowNumber === rowNumber
          ? { ...emp, importAnyway: !emp.importAnyway }
          : emp
      )
    );
  };

  const handleToggleAllDuplicates = (importAll: boolean) => {
    setParsedEmployees(prev =>
      prev.map(emp =>
        emp.duplicateCheck.isDuplicate
          ? { ...emp, importAnyway: importAll }
          : emp
      )
    );
  };

  const handleImportConfirm = async () => {
    setCurrentStep('importing');
    setImportProgress({ current: 0, total: 0 });

    // No contactId passed - each employee uses its own adressid from CSV
    const result = await bulkImportEmployees(
      parsedEmployees,
      undefined, // No fallback contactId
      (current, total) => setImportProgress({ current, total })
    );

    setImportResult({
      success: result.success,
      total: parsedEmployees.length,
      imported: result.imported,
      skipped: result.skipped,
      errors: result.errors,
      details: result.details,
    });

    setCurrentStep('results');

    // Call onSuccess if any employees were imported
    if (result.imported > 0 && onSuccess) {
      onSuccess();
    }
  };

  const handleReset = () => {
    setFile(null);
    setParsedEmployees([]);
    setImportResult(null);
    setCurrentStep('upload');
    setImportProgress({ current: 0, total: 0 });
  };

  const getActiveStep = (): number => {
    switch (currentStep) {
      case 'upload': return 0;
      case 'preview': return 1;
      case 'importing': return 2;
      case 'results': return 2;
      default: return 0;
    }
  };

  // Count unique companies in parsed data
  const uniqueCompanyCount = new Set(
    parsedEmployees
      .filter(e => e.adressid)
      .map(e => e.adressid)
  ).size;

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        maxWidth: (theme) => `calc(${theme.breakpoints.values.xl}px - ${DRAWER_WIDTH}px)`,
      }}
    >
      {/* Header */}

      <Paper elevation={0} sx={{ p: {xs: 4, md: 5}, border: '1px solid', borderColor: 'divider' }}>
        {/* Stepper */}
        <Stepper activeStep={getActiveStep()} sx={{ mb: 4 }}>
          <Step>
            <StepLabel><Trans>Upload file</Trans></StepLabel>
          </Step>
          <Step>
            <StepLabel><Trans>Preview & check</Trans></StepLabel>
          </Step>
          <Step>
            <StepLabel><Trans>Finish import</Trans></StepLabel>
          </Step>
        </Stepper>

        {/* Step 1: Upload */}
        {currentStep === 'upload' && (
          <>
            <Alert severity="info" sx={{ mb: 3 }}>
              <Typography variant="body2" gutterBottom>
                <Trans>First download the CSV template and fill it with your employee data.</Trans>
              </Typography>
              <Typography variant="body2">
                <strong><Trans>Required fields:</Trans></strong> <Trans>adressid (company ID) and Name (last name)</Trans>
              </Typography>
            </Alert>

            <Box sx={{ mb: 4 }}>
              <Button
                variant="outlined"
                startIcon={<DownloadIcon />}
                onClick={() => generateCSVTemplate(true)} // true = include adressid
                sx={{ textTransform: 'none' }}
              >
                <Trans>Download CSV template</Trans>
              </Button>
            </Box>

            <Divider sx={{ my: 3 }} />

            <Box sx={{ mb: 3 }}>
              <Typography variant="h3" gutterBottom>
                <Trans>Upload CSV file</Trans>
              </Typography>

              <input
                ref={fileInputRef}
                type="file"
                accept=".csv"
                onChange={handleFileSelect}
                style={{ display: 'none' }}
              />

              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                <Button
                  variant="contained"
                  startIcon={<CloudUploadIcon />}
                  onClick={() => fileInputRef.current?.click()}
                  disabled={validating}
                  sx={{ textTransform: 'none' }}
                >
                  <Trans>Select CSV file</Trans>
                </Button>

                {file && (
                  <Chip
                    label={file.name}
                    onDelete={() => {
                      setFile(null);
                      setParsedEmployees([]);
                    }}
                    color="primary"
                    variant="outlined"
                  />
                )}
              </Box>

              {file && (
                <Button
                  variant="contained"
                  color="primary"
                  onClick={handleFileValidation}
                  disabled={validating}
                  sx={{ textTransform: 'none' }}
                >
                  <Trans>Validate file and show preview</Trans>
                </Button>
              )}
            </Box>

            {validating && (
              <Box sx={{ mb: 3 }}>
                <Typography variant="body2" color="text.secondary" gutterBottom>
                  <Trans>Validating employees and checking for duplicates...</Trans>
                </Typography>
                <LinearProgress />
              </Box>
            )}

            <Box sx={{ mt: 4 }}>
              <Alert severity="info">
                <Typography variant="subtitle2" gutterBottom fontWeight={600}>
                  <Trans>Notes on the CSV template:</Trans>
                </Typography>
                <Typography variant="body2" component="div">
                  <ul style={{ margin: 0, paddingLeft: '20px' }}>
                    <li>
                      <strong><Trans>adressid* (required field):</Trans></strong>{' '}
                      <Trans>The ID of the company the employee belongs to. You can find the ID in the URL when you open a company (e.g. /contact/getadr/123)</Trans>
                    </li>
                    <li><strong><Trans>Name* (required field):</Trans></strong> <Trans>Employee's last name</Trans></li>
                    <li><strong><Trans>MW (salutation):</Trans></strong> <Trans>Herr or Frau</Trans></li>
                    <li><strong><Trans>dw1–dw4:</Trans></strong> <Trans>Phone extensions</Trans></li>
                    <li>
                      <strong><Trans>Multiple companies:</Trans></strong>{' '}
                      <Trans>You can import employees for different companies in one CSV file – just use different adressid values</Trans>
                    </li>
                    <li>
                      <strong><Trans>Duplicates:</Trans></strong>{' '}
                      <Trans>If an employee with the same name or email already exists, a warning is shown. You can still import (e.g. for common names).</Trans>
                    </li>
                  </ul>
                </Typography>
              </Alert>
            </Box>
          </>
        )}

        {/* Step 2: Preview */}
        {currentStep === 'preview' && (
          <>
            {/* Show company count info */}
            {uniqueCompanyCount > 1 && (
              <Alert severity="info" sx={{ mb: 2 }}>
                <Trans>Employees will be imported to <strong>{uniqueCompanyCount} different companies</strong>.</Trans>
              </Alert>
            )}
            <EmployeesImportPreview
              employees={parsedEmployees}
              onConfirm={handleImportConfirm}
              onCancel={handleReset}
              onToggleImportAnyway={handleToggleImportAnyway}
              onToggleAllDuplicates={handleToggleAllDuplicates}
              showCompanyColumn={true}
            />
          </>
        )}

        {/* Step 3: Importing */}
        {currentStep === 'importing' && (
          <Box sx={{ textAlign: 'center', py: 4 }}>
            <Typography variant="h6" gutterBottom>
              <Trans>Importing employees...</Trans>
            </Typography>
            <LinearProgress
              variant={importProgress.total > 0 ? 'determinate' : 'indeterminate'}
              value={importProgress.total > 0 ? (importProgress.current / importProgress.total) * 100 : 0}
              sx={{ mt: 2 }}
            />
            {importProgress.total > 0 && (
              <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
                <Trans>{importProgress.current} of {importProgress.total} processed</Trans>
              </Typography>
            )}
            <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
              <Trans>Please wait while the employees are imported.</Trans>
            </Typography>
          </Box>
        )}

        {/* Step 4: Results */}
        {currentStep === 'results' && importResult && (
          <EmployeesImportResults
            result={importResult}
            onReset={handleReset}
            onBack={onBack}
            showCompanyColumn={true}
          />
        )}
      </Paper>
      {/* {onBack && (
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={onBack}
          sx={{ textTransform: 'none' }}
        >
          Zurück
        </Button> */}
      {/* )} */}
    </Box>
  );
};

export default EmployeesAddMultiple;
