import {
  collection,
  query,
  orderBy,
  onSnapshot,
  addDoc,
  serverTimestamp,
} from 'firebase/firestore';
import { db } from './firebase.js';

const donorsRef = collection(db, 'donors');
let unsubscribe = null;

export function subscribeToDonors(callback) {
  const q = query(donorsRef, orderBy('date', 'desc'));
  unsubscribe = onSnapshot(
    q,
    (snapshot) => {
      const donors = [];
      snapshot.forEach((doc) => {
        donors.push({ id: doc.id, ...doc.data() });
      });
      callback(donors);
    },
    (error) => {
      console.error('Error fetching donors:', error);
      callback([]);
    }
  );
  return unsubscribe;
}

export async function addDonor({ name, amount, classYear, message, anonymous }) {
  return addDoc(donorsRef, {
    name: anonymous ? 'Anonymous' : name,
    amount: Number(amount),
    classYear: classYear || '',
    message: message || '',
    anonymous: !!anonymous,
    date: serverTimestamp(),
  });
}

export function calculateTotal(donors) {
  return donors.reduce((sum, d) => sum + (d.amount || 0), 0);
}

export function sortDonors(donors, sortBy) {
  const sorted = [...donors];
  if (sortBy === 'amount') {
    sorted.sort((a, b) => (b.amount || 0) - (a.amount || 0));
  } else {
    sorted.sort((a, b) => {
      const dateA = a.date?.toMillis?.() || 0;
      const dateB = b.date?.toMillis?.() || 0;
      return dateB - dateA;
    });
  }
  return sorted;
}
