import { defineStore } from 'pinia';
import type { Reservation } from './schedule.types';
import { computed, ref } from 'vue';
import { AppwriteIds, databases } from 'src/boot/appwrite';
import { ID, Query } from 'appwrite';
import { date } from 'quasar';
import { Timestamp, parseDate, today } from '@quasar/quasar-ui-qcalendar';
import { LoadingTypes } from 'src/utils/misc';

export const useReservationStore = defineStore('reservation', () => {
  const reservations = ref<Map<string, Reservation>>(new Map());
  const datesLoaded = ref<Record<string, LoadingTypes>>({});

  // Fetch reservations for a specific date range
  const fetchReservationsForDateRange = async (
    start: string = today(),
    end: string = start
  ) => {
    const startDate = new Date(start < end ? start : end + 'T00:00');
    const endDate = new Date(start < end ? end : start + 'T23:59');

    if (getUnloadedDates(startDate, endDate).length === 0) return;

    setDateLoaded(startDate, endDate, 'pending');

    try {
      const response = await databases.listDocuments(
        AppwriteIds.databaseId,
        AppwriteIds.collection.reservation,
        [
          Query.greaterThanEqual('end', startDate.toISOString()),
          Query.lessThanEqual('start', endDate.toISOString()),
        ]
      );

      response.documents.forEach((d) =>
        reservations.value.set(d.$id, d as Reservation)
      );
      setDateLoaded(startDate, endDate, 'loaded');
    } catch (error) {
      console.error('Failed to fetch reservations', error);
      setDateLoaded(startDate, endDate, 'error');
    }
  };
  const createReservation = async (reservation: Reservation) => {
    try {
      const response = await databases.createDocument(
        AppwriteIds.databaseId,
        AppwriteIds.collection.reservation,
        ID.unique(),
        reservation
      );
      reservations.value.set(response.$id, response as Reservation);
      console.info('Reservation booked: ', response);
    } catch (e) {
      console.error('Error creating Reservation: ' + e);
    }
  };

  // Set the loading state for dates
  const setDateLoaded = (start: Date, end: Date, state: LoadingTypes) => {
    if (start > end) return [];
    let curDate = start;
    while (curDate < end) {
      datesLoaded.value[(parseDate(curDate) as Timestamp).date] = state;
      curDate = date.addToDate(curDate, { days: 1 });
    }
  };

  const getUnloadedDates = (start: Date, end: Date): string[] => {
    if (start > end) return [];
    let curDate = start;
    const unloaded = [];
    while (curDate < end) {
      const parsedDate = (parseDate(curDate) as Timestamp).date;
      if (datesLoaded.value[parsedDate] === undefined)
        unloaded.push(parsedDate);
      curDate = date.addToDate(curDate, { days: 1 });
    }
    return unloaded;
  };

  // Get reservations by date and optionally filter by boat
  const getReservationsByDate = (
    searchDate: string,
    boat?: string
  ): Reservation[] => {
    if (!datesLoaded.value[searchDate]) {
      fetchReservationsForDateRange(searchDate);
    }
    const dayStart = new Date(searchDate + 'T00:00');
    const dayEnd = new Date(searchDate + 'T23:59');

    return computed(() => {
      return Array.from(reservations.value.values()).filter((reservation) => {
        const reservationStart = new Date(reservation.start);
        const reservationEnd = new Date(reservation.end);

        const isWithinDay =
          reservationStart < dayEnd && reservationEnd > dayStart;
        const matchesBoat = boat ? boat === reservation.resource : true;
        return isWithinDay && matchesBoat;
      });
    }).value;
  };

  // Get conflicting reservations for a resource within a time range
  const getConflictingReservations = (
    resource: string,
    start: Date,
    end: Date
  ): Reservation[] => {
    return Array.from(reservations.value.values()).filter(
      (entry) =>
        entry.resource === resource &&
        new Date(entry.start) < end &&
        new Date(entry.end) > start
    );
  };

  // Check if a resource has time overlap
  const isResourceTimeOverlapped = (
    resource: string,
    start: Date,
    end: Date
  ): boolean => {
    return getConflictingReservations(resource, start, end).length > 0;
  };

  // Check if a reservation overlaps with existing reservations
  const isReservationOverlapped = (res: Reservation): boolean => {
    return isResourceTimeOverlapped(
      res.resource,
      new Date(res.start),
      new Date(res.end)
    );
  };

  return {
    getReservationsByDate,
    createReservation,
    fetchReservationsForDateRange,
    isReservationOverlapped,
    isResourceTimeOverlapped,
    getConflictingReservations,
  };
});
