import { Injectable } from '@angular/core';
import {
  Firestore,
  collection,
  deleteDoc,
  doc,
  getDoc,
  getDocs,
  query,
  setDoc,
  updateDoc,
  where,
} from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root',
})
export class PendingActionsService {
  private tempQRId: string | null = null;

  constructor(private firestore: Firestore) {}

  setTempQRId(id: string) {
    this.tempQRId = id;
  }

  getTempQRId(): string | null {
    return this.tempQRId;
  }

  clearTempQRId() {
    this.tempQRId = null;
  }

  saveTempQRCodeData(qrData: any) {
    const docRef = doc(collection(this.firestore, 'tempQRData'), qrData.uid);
    setDoc(docRef, qrData).catch((error) => {
      console.error('Error saving qr data', error);
      throw error;
    });
    return docRef.id;
  }

  getTempQRCodeData(uid: string | null) {
    if (uid === null) return null;
    const docRef = doc(this.firestore, `tempQRData/${uid}`);
    return getDoc(docRef)
      .then((docSnap) => {
        if (docSnap.exists()) {
          return docSnap.data();
        } else {
          return null;
        }
      })
      .catch((error) => {
        console.error('Error getting qr data', error);
        throw error;
      });
  }

  deleteTempQRCodeData(uid: string | null) {
    if (uid === null) return null;
    const docRef = doc(this.firestore, `tempQRData/${uid}`);
    return deleteDoc(docRef).catch((error) => {
      console.error('Error deleting qr data', error);
      throw error;
    });
  }

  addUserRefToQRCodeData(userId: string | null, uid: string | null) {
    if (userId === null || uid === null) return null;
    const docRef = doc(this.firestore, `tempQRData/${uid}`);
    const userRef = doc(this.firestore, 'users', userId);

    return updateDoc(docRef, { userRef: userRef });
  }

  checkForPendingQRData(userId: string | null) {
    if (userId === null) return null;
    const userRef = doc(this.firestore, 'users', userId);

    const tempQRDataRef = collection(this.firestore, 'tempQRData');
    const q = query(tempQRDataRef, where('userRef', '==', userRef));

    return getDocs(q)
      .then((querySnapshot) => {
        if (querySnapshot.empty) {
          return null;
        }
        const firstDoc = querySnapshot.docs[0];
        return firstDoc;
      })
      .catch((error) => {
        console.error('Fehler beim Abrufen der Dokumente:', error);
        return null;
      });
  }

  setScoreLocalStorage(score: string, uid: string) {
    localStorage.setItem('score', score);
    localStorage.setItem('uid', uid);
  }

  getScoreLocalStorage() {
    return {
      score: localStorage.getItem('score'),
      uid: localStorage.getItem('uid'),
    };
  }

  resetLocalStorage() {
    localStorage.removeItem('score');
    localStorage.removeItem('uid');
  }
}
