import axiosInstance from '@/utils/axios';

interface ExportFilters {
  [key: string]: {
    value: string;
    condition: string;
    secondValue?: string;
  };
}

interface ExportRequest {
  filters?: ExportFilters;
  selectedColumns?: string[];
  format: 'csv';
}

// Map frontend filter format to backend API format
const mapFiltersToBackendFormat = (filters: Record<string, { value: string; condition: string }>): ExportFilters => {
  const backendFilters: ExportFilters = {};

  Object.entries(filters).forEach(([key, filter]) => {
    if (filter.value && filter.value.trim() !== '') {
      // Map frontend column IDs to backend column IDs
      const backendColumnMap: Record<string, string> = {
        'id': 'id',
        'dateApplication': 'createdAt',
        'etat': 'controlled',
        'codeAvenant': 'amendmentCode',
        'intitule': 'subject',
        'clientDO': 'client',
        'chauffeur': 'driver',
        'departement': 'company',
        'objetAvenant': 'amendmentObject',
        'objet': 'object',
        'type': 'type',
        'dateFin': 'endDate',
        'isActive': 'active'
      };

      const backendKey = backendColumnMap[key] || key;

      // Handle special cases for boolean fields
      if (key === 'etat') {
        backendFilters[backendKey] = {
          value: filter.value === 'controle' ? 'true' : 'false',
          condition: 'equals'
        };
      } else if (key === 'isActive') {
        backendFilters[backendKey] = {
          value: filter.value === 'true' ? 'true' : 'false',
          condition: 'equals'
        };
      } else {
        backendFilters[backendKey] = {
          value: filter.value,
          condition: filter.condition
        };
      }
    }
  });

  return backendFilters;
};

// Map frontend column IDs to backend column IDs
const mapColumnsToBackendFormat = (columns: string[]): string[] => {
  const columnMap: Record<string, string> = {
    'id': 'id',
    'dateApplication': 'createdAt',
    'etat': 'controlled',
    'codeAvenant': 'amendmentCode',
    'intitule': 'subject',
    'clientDO': 'client',
    'chauffeur': 'driver',
    'departement': 'company',
    'objetAvenant': 'amendmentObject',
    'objet': 'object',
    'type': 'type',
    'dateFin': 'endDate',
    'isActive': 'active'
  };

  return columns.map(col => columnMap[col] || col);
};

export const exportAmendments = async (
  filters: Record<string, { value: string; condition: string }>,
  selectedColumns?: string[]
): Promise<void> => {
  try {
    const backendFilters = mapFiltersToBackendFormat(filters);
    const backendColumns = selectedColumns ? mapColumnsToBackendFormat(selectedColumns) : undefined;

    const requestBody: ExportRequest = {
      format: 'csv'
    };

    // Only add filters if there are any
    if (Object.keys(backendFilters).length > 0) {
      requestBody.filters = backendFilters;
    }

    // Only add selectedColumns if provided
    if (backendColumns && backendColumns.length > 0) {
      requestBody.selectedColumns = backendColumns;
    }

    const response = await axiosInstance.post('/api/circuit/v1/amendments/export', requestBody, {
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json',
      }
    });

    // Handle file download
    const blob = response.data;
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;

    // Extract filename from Content-Disposition header or use default
    const contentDisposition = response.headers['content-disposition'];
    let filename = 'avenants_export.csv';
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, '');
      }
    }

    a.download = filename;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('Export error:', error);
    throw error;
  }
};

export const exportComprehensiveAvenant = async (amendmentId: string): Promise<void> => {
  try {
    const response = await axiosInstance.get(`/api/circuit/v1/amendments/${amendmentId}/export-complete`, {
      responseType: 'blob',
      headers: {
        'Accept': 'text/csv',
      }
    });

    // Handle file download
    const blob = response.data;
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;

    // Extract filename from Content-Disposition header or use default
    const contentDisposition = response.headers['content-disposition'];
    let filename = `avenant_complet_${amendmentId}.csv`;
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, '');
      }
    }

    a.download = filename;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('Comprehensive export error:', error);
    throw error;
  }
};
