// resources/assets/ts/ContactsPage/components/ContactsAddMultiple.tsx

/**
 * CSV Import Component - Main Orchestrator
 * 
 * Features:
 * - CSV template download
 * - File upload and parsing
 * - Validation and duplicate detection
 * - Preview before import
 * - Bulk import processing
 */

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,
} from '@mui/icons-material';
import ContactsImportPreview from './ContactsImportPreview';
import ContactsImportResults from './ContactsImportResults';
import {
  parseCSV,
  validateContact,
  checkDuplicate,
  importContact,
  generateCSVTemplate,
  ContactPreview,
  ParsedContact,
} from '../../utils/csvImportUtils';

interface ContactsAddMultipleProps {
  onNavigateToEinstellungen?: () => void;
  onSuccess?: () => void;
}

type ImportStep = 'upload' | 'preview' | 'importing' | 'results'; //use with MUI stepper

interface ImportResult {
  success: boolean;
  total: number;
  imported: number;
  duplicates: number;
  errors: number;
  details: {
    row: number;
    status: 'success' | 'duplicate' | 'error';
    message?: string;
    data?: any;
  }[];
}

import { DRAWER_WIDTH } from '../ContactsSidebar';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';


const ContactsAddMultiple: React.FC<ContactsAddMultipleProps> = ({
  onNavigateToEinstellungen, onSuccess
}) => {
  const { i18n } = useLingui();
  const [currentStep, setCurrentStep] = useState<ImportStep>('upload');
  const [file, setFile] = useState<File | null>(null);
  const [parsedContacts, setParsedContacts] = useState<ContactPreview[]>([]);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [validating, setValidating] = useState(false);
  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);
      setParsedContacts([]);
      setImportResult(null);
      setCurrentStep('upload');
    }
  };

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

    setValidating(true);

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

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

      // Validate and check duplicates for each contact
      const previews: ContactPreview[] = [];

      for (let i = 0; i < contacts.length; i++) {
        const contact = contacts[i] as ParsedContact;
        const validation = validateContact(contact);

        // Only check for duplicates if validation passed
        let isDuplicate = false;
        let duplicateReason = '';

        if (validation.valid) {
          const duplicateCheck = await checkDuplicate(
            contact.firmenname,
            contact.email
          );
          isDuplicate = duplicateCheck.isDuplicate;
          duplicateReason = duplicateCheck.reason || '';
        }

        previews.push({
          ...contact,
          rowNumber: i + 2, // +2 because row 1 is header
          validation,
          isDuplicate,
          duplicateReason,
        });
      }

      setParsedContacts(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 handleImportConfirm = async () => {
    setCurrentStep('importing');

    const result: ImportResult = {
      success: true,
      total: parsedContacts.length,
      imported: 0,
      duplicates: 0,
      errors: 0,
      details: [],
    };

    // Only import valid, non-duplicate contacts
    const validContacts = parsedContacts.filter(
      c => c.validation.valid && !c.isDuplicate
    );

    for (const contact of validContacts) {
      const imported = await importContact(contact);

      if (imported) {
        result.imported++;
        result.details.push({
          row: contact.rowNumber,
          status: 'success',
          message: i18n._(msg`Imported successfully`),
          data: contact,
        });
      } else {
        result.errors++;
        result.details.push({
          row: contact.rowNumber,
          status: 'error',
          message: i18n._(msg`Import failed`),
          data: contact,
        });
      }
    }

    // Add skipped duplicates to result
    parsedContacts.filter(c => c.isDuplicate).forEach(contact => {
      result.duplicates++;
      result.details.push({
        row: contact.rowNumber,
        status: 'duplicate',
        message: contact.duplicateReason || i18n._(msg`Contact already exists`),
        data: contact,
      });
    });

    // Add validation errors to result
    parsedContacts.filter(c => !c.validation.valid).forEach(contact => {
      result.errors++;
      result.details.push({
        row: contact.rowNumber,
        status: 'error',
        message: contact.validation.errors.join('; '),
        data: contact,
      });
    });

    result.success = result.imported > 0;
    setImportResult(result);
    setCurrentStep('results');

    // Call onSuccess if any contacts were imported, to trigger refresh on contactspage
    if (result.imported > 0 && onSuccess) {
      onSuccess();
    }
  };

  const handleReset = () => {
    setFile(null);
    setParsedContacts([]);
    setImportResult(null);
    setCurrentStep('upload');
  };

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

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        maxWidth: (theme) => `calc(${theme.breakpoints.values.xl}px - ${DRAWER_WIDTH}px)`,
      }}
    >
      <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 contact data.
                  Fields marked with * are required.
                </Trans>
              </Typography>
            </Alert>

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

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

            <Box sx={{ mb: 3 }}>
              <Typography variant="h5" 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);
                      setParsedContacts([]);
                    }}
                    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 contacts 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>Required fields:</Trans></strong> firmenname, kategorie_id, prioritaet_id, branche_id</li>
                    <li><Trans>The <strong>responsible person</strong> is automatically set to your username</Trans></li>


                    <li>
                      <strong>Kategorie_id, Prioritaet_id, Branche_id</strong>{' '}
                      <Trans>
                        are numeric IDs from your system (see{' '}
                        <a
                          href="#"
                          onClick={(e) => {
                            e.preventDefault();
                            onNavigateToEinstellungen?.();
                          }}
                          style={{
                            color: '#1976d2',
                            textDecoration: 'underline',
                            cursor: 'pointer'
                          }}
                        >
                          Settings
                        </a>
                        )
                      </Trans>
                    </li>

                    <li><Trans>Duplicates are detected automatically and shown in the preview</Trans></li>
                    <li><Trans>If no delivery address is given, the postal address is used</Trans></li>
                  </ul>
                </Typography>
              </Alert>
            </Box>
          </>
        )}

        {/* Step 2: Preview */}
        {currentStep === 'preview' && (
          <ContactsImportPreview
            contacts={parsedContacts}
            onConfirm={handleImportConfirm}
            onCancel={handleReset}
          />
        )}

        {/* Step 3: Importing */}
        {currentStep === 'importing' && (
          <Box sx={{ textAlign: 'center', py: 4 }}>
            <Typography variant="h6" gutterBottom>
              <Trans>Importing contacts...</Trans>
            </Typography>
            <LinearProgress sx={{ mt: 2 }} />
            <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
              <Trans>Please wait while the contacts are imported.</Trans>
            </Typography>
          </Box>
        )}

        {/* Step 4: Results */}
        {currentStep === 'results' && importResult && (
          <ContactsImportResults
            result={importResult}
            onReset={handleReset}
          />
        )}
      </Paper>
    </Box>
  );
};

export default ContactsAddMultiple;