import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { validateCallLogImport } from '@/lib/callLogImportSecurity';
import { logCallLogAudit } from '@/lib/callLogAuditLogger';

export function useCallLogImport() {
  const [analyzing, setAnalyzing] = useState(false);
  const [validationResult, setValidationResult] = useState(null);

  const parseAndValidateFile = async (file) => {
    setAnalyzing(true);
    setValidationResult(null);

    try {
      const { data: userData } = await supabase.auth.getUser();
      const user = userData?.user;

      const data = await readFile(file);
      let jsonData = [];

      if (file.name.endsWith('.csv') || file.name.endsWith('.xlsx') || file.name.endsWith('.xls')) {
        const XLSX = await import('xlsx');
        const workbook = XLSX.read(data, { type: 'binary' });
        jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
      } else if (file.name.endsWith('.json')) {
        jsonData = JSON.parse(data);
      } else {
        throw new Error("Unsupported file format. Please use CSV, Excel, or JSON.");
      }

      const normalizedData = jsonData.map(row => {
        const newRow = {};
        Object.keys(row).forEach(key => {
          newRow[key.toLowerCase().trim().replace(/\s+/g, '_')] = row[key];
        });
        return newRow;
      });

      const { data: associations } = await supabase.from('associations').select('id');
      const validAssociationIds = new Set(associations?.map(a => a.id) || []);

      const result = validateCallLogImport(normalizedData, validAssociationIds);
      setValidationResult(result);

      if (!result.valid && user) {
        await logCallLogAudit({
          userId: user.id,
          action: 'IMPORT_VALIDATION_FAILURE',
          status: 'FAILURE',
          details: { fileName: file.name, errorCount: result.errors?.length || 0 }
        });
      }

      return result;
    } catch (err) {
      console.error(err);
      throw err;
    } finally {
      setAnalyzing(false);
    }
  };

  const readFile = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => resolve(e.target.result);
      reader.onerror = (e) => reject(e);
      if (file.name.endsWith('.json')) {
        reader.readAsText(file);
      } else {
        reader.readAsBinaryString(file);
      }
    });
  };

  return {
    parseAndValidateFile,
    analyzing,
    validationResult,
    resetValidation: () => setValidationResult(null)
  };
}
