import { 
  collection, 
  addDoc, 
  query, 
  where, 
  getDocs,
  orderBy,
  Timestamp,
  doc,
  deleteDoc
} from 'firebase/firestore';
import { db, auth } from '../config/firebase';

export interface VarroaTest {
  // User and Reference Information
  userId: string;
  id?: string;  
  reference: string;
  evaluationDate: Timestamp | Date;
  reportGeneratedDate: Timestamp | Date;

  // Basic Test Information
  method: string;
  miteCount: number;
  sampleSize: number;
  infestationRate: number;
  status: string;

  // Colony Information
  beekeepingType: string;
  timePerHive: string;
  hiveType: string;
  colonyStrength: string;
  geneticResistance: string;
  hiveModel: string;
  frames: number;
  bottomBoard: string;

  // Treatment Information
  treatmentApplied: string;
  selectedTreatments: Array<{
    name: string;
    duration: string | number;
    effectiveness: number;
    applicationTime: number;
    temperature: { min: number; max: number };
    activeIngredient?: string;
    availability?: string;
    beekeepingTypes?: string[];
    colonyStrengthRequirement?: string;
    cost?: string;
    difficulty?: string;
    efficacy?: string;
    id?: string;
    organicCompatible?: boolean;
    precautions?: string[];
    seasonCompatibility?: {
      autumn: boolean;
      spring: boolean;
      summer: boolean;
      winter: boolean;
    };
    timeRequired?: string;
    type?: string;
  }>;
  selectedBiotechnicalMethods: string[];
  previousTreatment: string;
  treatmentAvailability: string;
  veterinaryProduct: string;
  actionTime: string;

  // Population Data
  beePopulation: {
    current: number;
    projected: number[];
    dates: string[];
  };

  mitePopulation: {
    current: number;
    projected: number[];
    withTreatment: number[];
    dates: string[];
  };

  // Risk Analysis
  riskLevels: {
    warning: number;
    critical: number;
    monthlyProjections: number[];
  };

  // Treatment Effectiveness
  temperatureImpact: {
    temperatures: number[];
    effectiveness: number[];
    currentTemp: number;
  };

  // Monitoring History
  monitoringHistory: Array<{
    date: string;
    method: string;
    miteCount: number;
    sampleSize: number;
    infestationRate: number;
    infestationLevel: string;
    treatmentApplied?: string;
  }>;
  nextMonitoringDate: Date | Timestamp;

  // Seasonal Information
  seasonalAdvice: string[];
  currentSeason: string;
  seasonalTips: string[];

  // Additional Resources
  documentation: {
    treatmentGuide: string;
    monitoringMethods: string;
  };
  contacts: {
    veterinarian: string;
    association: string;
  };

  // Treatment Prediction
  treatmentPrediction: {
    treatmentDate: Date | Timestamp;
    effectiveness: number;
    projectedInfestationRates: number[];
    projectedDates: string[];
  };

  // Personalized Recommendations
  recommendations: Array<{
    title: string;
    description: string;
    category: string;
    priority: 'high' | 'medium' | 'low';
  }>;

  // Environmental Conditions
  environment: {
    temperature: number;
    humidity?: number;
    season: string;
    location?: string;
  };
}

const convertDatesToTimestamp = (obj: any): any => {
  if (obj === null || obj === undefined) {
    return obj;
  }

  if (obj instanceof Date) {
    return Timestamp.fromDate(obj);
  }

  if (Array.isArray(obj)) {
    return obj.map(item => convertDatesToTimestamp(item));
  }

  if (typeof obj === 'object') {
    const result: any = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        const value = obj[key];
        
        // Convertir todas las fechas a Timestamp
        if (value instanceof Date) {
          result[key] = Timestamp.fromDate(value);
        } else if (typeof value === 'object') {
          result[key] = convertDatesToTimestamp(value);
        } else {
          result[key] = value;
        }
      }
    }
    return result;
  }

  return obj;
};

const cleanDataForFirebase = (data: any): any => {
  if (data === null || data === undefined) {
    return null;
  }

  if (Array.isArray(data)) {
    return data.map(item => cleanDataForFirebase(item));
  }

  if (typeof data === 'object') {
    const cleanedObj: any = {};
    for (const [key, value] of Object.entries(data)) {
      const cleanedValue = cleanDataForFirebase(value);
      if (cleanedValue !== undefined) {
        cleanedObj[key] = cleanedValue;
      }
    }
    return cleanedObj;
  }

  return data;
};

export const saveVarroaTest = async (testData: VarroaTest, userId: string): Promise<void> => {
  try {
    // Asegurarse de que el usuario esté autenticado
    const currentUser = auth.currentUser;
    if (!currentUser) {
      throw new Error('Usuario no autenticado');
    }

    const testsRef = collection(db, 'varroaTests');
    
    // Limpiar datos y convertir undefined a null
    const cleanedData = cleanDataForFirebase(testData);
    
    // Convertir todas las fechas a Timestamp
    const processedData = convertDatesToTimestamp(cleanedData);
    
    console.log('Procesando datos para Firebase:', processedData);
    console.log('Estructura final del documento:', {
      collection: 'varroaTests',
      data: processedData
    });
    
    // Asegurarse de que el userId está presente
    processedData.userId = userId;
    
    await addDoc(testsRef, processedData);
    console.log('Test saved successfully');
  } catch (error) {
    console.error('Error saving test:', error);
    throw new Error('Error al guardar el test en la base de datos');
  }
};

export const getUserTests = async (userId: string): Promise<(VarroaTest & { id: string })[]> => {
  try {
    const currentUser = auth.currentUser;
    if (!currentUser) {
      throw new Error('Usuario no autenticado');
    }

    const collectionRef = collection(db, 'varroaTests');
    const q = query(collectionRef, where('userId', '==', userId));
    const querySnapshot = await getDocs(q);
    console.log('Query executed, number of docs:', querySnapshot.size);

    const tests = querySnapshot.docs.map(doc => {
      const data = doc.data();
      console.log('Raw test data from Firebase:', data);

      // Convertir las fechas a objetos Date
      const convertToDate = (value: any): Date => {
        if (!value) return new Date();
        if (value instanceof Timestamp) {
          return value.toDate();
        }
        if (value instanceof Date) {
          return value;
        }
        if (typeof value === 'string') {
          const date = new Date(value);
          return isNaN(date.getTime()) ? new Date() : date;
        }
        return new Date();
      };

      const evaluationDate = convertToDate(data.evaluationDate);
      const reportGeneratedDate = convertToDate(data.reportGeneratedDate);

      console.log('Converted dates:', {
        evaluationDate,
        reportGeneratedDate,
        evaluationTimestamp: evaluationDate.getTime(),
        reportTimestamp: reportGeneratedDate.getTime()
      });

      const test = {
        ...data,
        id: doc.id,
        evaluationDate,
        reportGeneratedDate,
        monitoringHistory: Array.isArray(data.monitoringHistory) ? data.monitoringHistory.map((item: any) => ({
          ...item,
          date: convertToDate(item.date).toISOString().split('T')[0]
        })) : [],
        userId: data.userId,
        reference: data.reference,
        method: data.method,
        miteCount: data.miteCount,
        sampleSize: data.sampleSize,
        infestationRate: data.infestationRate,
        status: data.status
      } as VarroaTest & { id: string };

      console.log('Processed test:', {
        id: test.id,
        evaluationDate: test.evaluationDate,
        timestamp: test.evaluationDate instanceof Date ? test.evaluationDate.getTime() : test.evaluationDate
      });

      return test;
    });

    // Ordenar por fecha de evaluación (más reciente primero)
    const sortedTests = tests.sort((a, b) => {
      const getTime = (date: Date | Timestamp): number => {
        if (date instanceof Date) return date.getTime();
        if (date instanceof Timestamp) return date.toDate().getTime();
        const converted = new Date(date);
        return isNaN(converted.getTime()) ? 0 : converted.getTime();
      };

      const timeA = getTime(a.evaluationDate);
      const timeB = getTime(b.evaluationDate);

      console.log('Sorting:', {
        a: { date: a.evaluationDate, time: timeA },
        b: { date: b.evaluationDate, time: timeB }
      });

      return timeB - timeA;
    });

    console.log('Final sorted tests:', sortedTests.map(test => ({
      id: test.id,
      date: test.evaluationDate,
      timestamp: test.evaluationDate instanceof Date ? test.evaluationDate.getTime() : test.evaluationDate
    })));

    return sortedTests;

  } catch (error) {
    console.error('Error detallado al obtener tests:', error);
    throw new Error('Error al obtener los tests de la base de datos');
  }
};

export const deleteTest = async (userId: string, testId: string): Promise<void> => {
  try {
    // Asegurarse de que el usuario esté autenticado
    const currentUser = auth.currentUser;
    if (!currentUser) {
      throw new Error('Usuario no autenticado');
    }

    const testRef = doc(db, 'varroaTests', testId);
    await deleteDoc(testRef);
    console.log('Test deleted successfully');
  } catch (error) {
    console.error('Error deleting test:', error);
    throw new Error('Error al eliminar el test');
  }
};
