/**
 * CSV Export utility functions for Detailed Reports
 */

import { dashboardService, type DateRange } from '@/services/dashboard.service';
import { getWorkflowDetails } from '@/services/workflowApi';
import { formatDateForCSV, mapActivityType } from './formatting';

/**
 * Export Lifecycle Report to CSV with End-to-End Workflow Details
 * Includes all approval levels, approvers, dates, and TAT compliance
 */
export async function exportLifecycleToCSV(
  dateRange: DateRange,
  customStartDate?: Date,
  customEndDate?: Date
): Promise<void> {
  // Fetch all data with a very large limit
  const result = await dashboardService.getLifecycleReport(1, 10000, dateRange, customStartDate, customEndDate);

  // CSV Headers for comprehensive end-to-end workflow status
  const csvRows = [
    [
      'Request Number',
      'Title',
      'Priority',
      'Overall Status',
      'Initiator',
      'Submission Date',
      'Closure Date',
      'Total Levels',
      'Current Level',
      'Overall TAT (Hours)',
      'Overall TAT (Days)',
      'Breach Count',
      'Level Number',
      'Level Name',
      'Approver Name',
      'Approver Email',
      'Level Status',
      'Level Start Date',
      'Level Completion Date',
      'Level TAT (Hours)',
      'Level TAT (Days)',
      'Level TAT Compliance',
      'Level Elapsed Hours',
      'Level Remaining Hours',
      'Level TAT % Used',
    ].join(','),
  ];

  // Process each request and fetch detailed approval level information
  for (const req of result.lifecycleData) {
    try {
      // Fetch detailed workflow information including all approval levels
      const workflowDetails = await getWorkflowDetails(req.requestId || req.requestNumber);
      
      const submissionDateCSV = req.submissionDate ? formatDateForCSV(req.submissionDate) : 'N/A';
      const closureDateCSV = req.closureDate ? formatDateForCSV(req.closureDate) : 'N/A';
      const overallTATHours = req.overallTATHours || 0;
      const overallTATDays = overallTATHours > 0 ? (overallTATHours / 8).toFixed(2) : '0';

      // Fix: Ensure currentLevel doesn't exceed totalLevels (data inconsistency from backend)
      const totalLevels = req.totalLevels || 1;
      const currentLevel = Math.min(Math.max(1, req.currentLevel || 1), totalLevels);

      // Get approval levels from workflow details
      const approvalLevels = workflowDetails?.approvals || [];
      
      if (approvalLevels.length === 0) {
        // If no approval levels found, still export request-level data
        const row = [
          req.requestNumber || '',
          `"${(req.title || '').replace(/"/g, '""')}"`,
          req.priority || 'medium',
          req.status || '',
          `"${(req.initiatorName || 'Unknown').replace(/"/g, '""')}"`,
          submissionDateCSV,
          closureDateCSV,
          totalLevels.toString(),
          currentLevel.toString(),
          overallTATHours.toString(),
          overallTATDays,
          (req.breachCount || 0).toString(),
          'N/A', // Level Number
          'N/A', // Level Name
          'N/A', // Approver Name
          'N/A', // Approver Email
          'N/A', // Level Status
          'N/A', // Level Start Date
          'N/A', // Level Completion Date
          'N/A', // Level TAT Hours
          'N/A', // Level TAT Days
          'N/A', // Level TAT Compliance
          'N/A', // Level Elapsed Hours
          'N/A', // Level Remaining Hours
          'N/A', // Level TAT % Used
        ];
        csvRows.push(row.join(','));
      } else {
        // Export one row per approval level for comprehensive end-to-end view
        approvalLevels.forEach((level: any) => {
          const levelStartDateCSV = level.levelStartTime ? formatDateForCSV(level.levelStartTime) : 'N/A';
          const levelCompletionDateCSV = level.levelEndTime || level.completedAt 
            ? formatDateForCSV(level.levelEndTime || level.completedAt) 
            : 'N/A';
          
          const levelTATHours = level.tatHours || 0;
          const levelTATDays = level.tatDays || (levelTATHours > 0 ? (levelTATHours / 8).toFixed(2) : '0');
          
          // Calculate TAT compliance status
          let tatCompliance = 'N/A';
          let elapsedHours = 'N/A';
          let remainingHours = 'N/A';
          let tatPercentageUsed = 'N/A';
          
          if (level.levelStartTime) {
            const startTime = new Date(level.levelStartTime);
            const endTime = level.levelEndTime || level.completedAt 
              ? new Date(level.levelEndTime || level.completedAt) 
              : new Date();
            const elapsedMs = endTime.getTime() - startTime.getTime();
            elapsedHours = (elapsedMs / (1000 * 60 * 60)).toFixed(2);
            
            if (levelTATHours > 0) {
              const elapsed = parseFloat(elapsedHours);
              remainingHours = Math.max(0, levelTATHours - elapsed).toFixed(2);
              tatPercentageUsed = ((elapsed / levelTATHours) * 100).toFixed(2);
              
              if (level.status === 'APPROVED' || level.status === 'REJECTED') {
                tatCompliance = elapsed <= levelTATHours ? 'Compliant' : 'Breached';
              } else if (level.status === 'IN_PROGRESS' || level.status === 'PENDING') {
                tatCompliance = elapsed <= levelTATHours ? 'On Track' : 'At Risk';
              } else {
                tatCompliance = 'N/A';
              }
            }
          }
          
          const row = [
            req.requestNumber || '',
            `"${(req.title || '').replace(/"/g, '""')}"`,
            req.priority || 'medium',
            req.status || '',
            `"${(req.initiatorName || 'Unknown').replace(/"/g, '""')}"`,
            submissionDateCSV,
            closureDateCSV,
            (req.totalLevels || 0).toString(),
            (req.currentLevel || 0).toString(),
            overallTATHours.toString(),
            overallTATDays,
            (req.breachCount || 0).toString(),
            (level.levelNumber || '').toString(),
            `"${(level.levelName || `Level ${level.levelNumber}`).replace(/"/g, '""')}"`,
            `"${(level.approverName || 'N/A').replace(/"/g, '""')}"`,
            `"${(level.approverEmail || 'N/A').replace(/"/g, '""')}"`,
            level.status || 'PENDING',
            levelStartDateCSV,
            levelCompletionDateCSV,
            levelTATHours.toString(),
            levelTATDays.toString(),
            tatCompliance,
            elapsedHours,
            remainingHours,
            tatPercentageUsed,
          ];
          csvRows.push(row.join(','));
        });
      }
    } catch (error) {
      console.error(`Failed to fetch details for request ${req.requestNumber}:`, error);
      // Still export basic request info even if details fetch fails
      const submissionDateCSV = req.submissionDate ? formatDateForCSV(req.submissionDate) : 'N/A';
      const overallTATHours = req.overallTATHours || 0;
      const overallTATDays = overallTATHours > 0 ? (overallTATHours / 8).toFixed(2) : '0';
      
      // Fix: Ensure currentLevel doesn't exceed totalLevels
      const totalLevels = req.totalLevels || 1;
      const currentLevel = Math.min(Math.max(1, req.currentLevel || 1), totalLevels);
      
      const row = [
        req.requestNumber || '',
        `"${(req.title || '').replace(/"/g, '""')}"`,
        req.priority || 'medium',
        req.status || '',
        `"${(req.initiatorName || 'Unknown').replace(/"/g, '""')}"`,
        submissionDateCSV,
        'N/A',
        totalLevels.toString(),
        currentLevel.toString(),
        overallTATHours.toString(),
        overallTATDays,
        (req.breachCount || 0).toString(),
        'Error', // Level Number
        'Error fetching details', // Level Name
        'N/A', // Approver Name
        'N/A', // Approver Email
        'N/A', // Level Status
        'N/A', // Level Start Date
        'N/A', // Level Completion Date
        'N/A', // Level TAT Hours
        'N/A', // Level TAT Days
        'N/A', // Level TAT Compliance
        'N/A', // Level Elapsed Hours
        'N/A', // Level Remaining Hours
        'N/A', // Level TAT % Used
      ];
      csvRows.push(row.join(','));
    }
  }

  downloadCSV(csvRows, `lifecycle-report-end-to-end-${new Date().toISOString().split('T')[0]}.csv`);
}

/**
 * Export Activity Log Report to CSV
 */
export async function exportActivityToCSV(
  dateRange: DateRange,
  customStartDate?: Date,
  customEndDate?: Date,
  filterCategory?: string,
  filterSeverity?: string
): Promise<void> {
  const result = await dashboardService.getActivityLogReport(
    1,
    10000,
    dateRange,
    undefined, // filterUserId
    undefined, // filterType
    filterCategory && filterCategory !== 'all' ? filterCategory : undefined,
    filterSeverity && filterSeverity !== 'all' ? filterSeverity : undefined,
    customStartDate,
    customEndDate
  );

  const csvRows = [
    ['Timestamp', 'User', 'Action', 'Details', 'IP Address', 'User Agent', 'Request ID'].join(','),
  ];

  result.activities.forEach((activity: any) => {
    const action = mapActivityType(activity.type || '', activity.details as string);
    const timestampCSV = activity.timestamp ? formatDateForCSV(activity.timestamp) : 'N/A';
    const row = [
      timestampCSV,
      `"${(activity.userName || 'Unknown').replace(/"/g, '""')}"`,
      `"${action.replace(/"/g, '""')}"`,
      `"${(activity.requestTitle || activity.requestNumber || activity.details || 'N/A').replace(/"/g, '""')}"`,
      activity.ipAddress || 'N/A',
      `"${(activity.userAgent || '').replace(/"/g, '""')}"`,
      activity.requestNumber || activity.requestId || '-',
    ];
    csvRows.push(row.join(','));
  });

  downloadCSV(csvRows, `activity-log-report-${new Date().toISOString().split('T')[0]}.csv`);
}

/**
 * Export Workflow Aging Report to CSV
 */
export async function exportAgingToCSV(
  threshold: number,
  dateRange: DateRange,
  customStartDate?: Date,
  customEndDate?: Date
): Promise<void> {
  const result = await dashboardService.getWorkflowAgingReport(
    threshold,
    1,
    10000,
    dateRange,
    customStartDate,
    customEndDate
  );

  const csvRows = [
    [
      'Request ID',
      'Title',
      'Initiator',
      'Start Date',
      'Days Open (Business)',
      'Current Stage',
      'Assigned To',
      'Priority',
      'Status',
    ].join(','),
  ];

  result.agingData.forEach((req: any) => {
    const startDateCSV = req.submissionDate ? formatDateForCSV(req.submissionDate) : 'N/A';
    const row = [
      req.requestNumber || req.requestId || '',
      `"${(req.title || '').replace(/"/g, '""')}"`,
      `"${(req.initiatorName || 'Unknown').replace(/"/g, '""')}"`,
      startDateCSV,
      (req.daysOpen || 0).toString(),
      `"${(req.currentStageName || `Level ${req.currentLevel}`).replace(/"/g, '""')}"`,
      `"${(req.currentApproverName || 'N/A').replace(/"/g, '""')}"`,
      req.priority || 'medium',
      req.status || 'pending',
    ];
    csvRows.push(row.join(','));
  });

  downloadCSV(csvRows, `workflow-aging-report-${new Date().toISOString().split('T')[0]}.csv`);
}

/**
 * Helper function to download CSV file
 */
function downloadCSV(csvRows: string[], filename: string): void {
  const csvContent = csvRows.join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', filename);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

