import Papa from 'papaparse';
import { supabase } from '@/integrations/supabase/client';

const LOG_PREFIX = '[ChecklistImportService]';

/**
 * Validates parsed items to ensure they match the required format
 */
export const validateItemsAndHeaders = (rawItems, explicitHeaders = null) => {
  console.log(`${LOG_PREFIX} Validating ${rawItems?.length} items`, { explicitHeaders });

  if (!Array.isArray(rawItems) || rawItems.length === 0) {
    return { items: [], headers: [] };
  }

  let headers = [];
  if (explicitHeaders && Array.isArray(explicitHeaders) && explicitHeaders.length > 0) {
    headers = explicitHeaders;
  } else {
    const firstItem = rawItems[0];
    if (typeof firstItem === 'object' && firstItem !== null) {
      headers = Object.keys(firstItem).filter(k => k !== 'completed' && k !== 'checked');
    }
  }

  if (headers.length === 0) {
    headers = ['Task'];
  }

  const validatedItems = rawItems.map(item => {
    if (typeof item === 'string') {
      return { 
        [headers[0]]: item.trim(), 
        completed: false,
        created_at: new Date().toISOString()
      };
    }
    
    if (typeof item === 'object' && item !== null) {
      const newItem = { 
        completed: !!(item.completed || item.checked || item.done),
        created_at: item.created_at || new Date().toISOString()
      };
      
      headers.forEach(h => {
        newItem[h] = item[h] !== undefined ? String(item[h]).trim() : '';
      });
      
      return newItem;
    }
    return null;
  }).filter(item => item !== null);

  console.log(`${LOG_PREFIX} Validation complete`, { headers, itemCount: validatedItems.length });
  return { items: validatedItems, headers };
};

export const parseJSON = (file) => {
  console.log(`${LOG_PREFIX} Parsing JSON file: ${file.name}`);
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const json = JSON.parse(e.target.result);
        let rawItems = [];
        let headers = [];

        if (Array.isArray(json)) {
          rawItems = json;
        } else if (json.items && Array.isArray(json.items)) {
          rawItems = json.items;
          if (json.headers && Array.isArray(json.headers)) {
            headers = json.headers;
          }
        }
        
        resolve(validateItemsAndHeaders(rawItems, headers));
      } catch (err) {
        console.error(`${LOG_PREFIX} JSON Parse Error`, err);
        reject(new Error("Invalid JSON format"));
      }
    };
    reader.onerror = () => reject(new Error("Failed to read file"));
    reader.readAsText(file);
  });
};

export const parseCSV = (file) => {
  console.log(`${LOG_PREFIX} Parsing CSV file: ${file.name}`);
  return new Promise((resolve, reject) => {
    Papa.parse(file, {
      header: true,
      skipEmptyLines: true,
      complete: (results) => {
        console.log(`${LOG_PREFIX} CSV Parse Complete`, results);
        if (results.errors.length > 0) {
          console.warn(`${LOG_PREFIX} CSV Warnings`, results.errors);
        }
        
        const headers = results.meta.fields || [];
        resolve(validateItemsAndHeaders(results.data, headers));
      },
      error: (err) => {
        console.error(`${LOG_PREFIX} CSV Error`, err);
        reject(new Error("Failed to parse CSV: " + err.message));
      }
    });
  });
};

export const parseText = (file) => {
  console.log(`${LOG_PREFIX} Parsing Text file: ${file.name}`);
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const text = e.target.result;
      const lines = text.split(/\r?\n/).filter(line => line.trim().length > 0);
      
      if (lines.length === 0) {
        resolve({ items: [], headers: [] });
        return;
      }

      const firstLine = lines[0];
      let delimiter = null;
      if (firstLine.includes('\t')) delimiter = '\t';
      else if (firstLine.includes(',')) delimiter = ',';

      if (delimiter) {
        const headers = firstLine.split(delimiter).map(h => h.trim());
        const rawItems = lines.slice(1).map(line => {
          const values = line.split(delimiter);
          const item = {};
          headers.forEach((h, i) => {
            item[h] = values[i]?.trim() || '';
          });
          return item;
        });
        resolve(validateItemsAndHeaders(rawItems, headers));
      } else {
        resolve(validateItemsAndHeaders(lines, ['Task']));
      }
    };
    reader.onerror = () => reject(new Error("Failed to read file"));
    reader.readAsText(file);
  });
};

export const createChecklistFromImport = async ({ 
  title, 
  clientId, 
  items, 
  headers,
  customHeader, 
  user 
}) => {
  console.log(`${LOG_PREFIX} Creating checklist in DB`, { title, headers, itemCount: items?.length });
  
  if (!user) throw new Error("User not authenticated");

  const { data, error } = await supabase
    .from('checklists')
    .insert({
      title,
      association_id: clientId === 'none' ? null : clientId,
      items,
      status: 'in_progress',
      created_by: user.id,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    })
    .select()
    .single();

  if (error) {
    console.error(`${LOG_PREFIX} DB Insert Error`, error);
    throw error;
  }
  
  console.log(`${LOG_PREFIX} Checklist created successfully`, data.id);
  return data;
};
