"use client";

import { useState, useEffect, useCallback } from "react";
import { useStorage } from "@/core/storage";
import { v4 as uuid } from "uuid";
import type { DeskId, DeskReservation } from "../types";

const PREFIX = "res:";

export function useReservations() {
  const storage = useStorage("hot-desk");
  const [reservations, setReservations] = useState<DeskReservation[]>([]);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    setLoading(true);
    const all = await storage.exportAll();
    const results: DeskReservation[] = [];
    for (const [key, value] of Object.entries(all)) {
      if (key.startsWith(PREFIX) && value) {
        results.push(value as DeskReservation);
      }
    }
    results.sort((a, b) => a.date.localeCompare(b.date));
    setReservations(results);
    setLoading(false);
  }, [storage]);

  useEffect(() => {
    refresh();
  }, [refresh]);

  const addReservation = useCallback(
    async (deskId: DeskId, date: string, userName: string, notes: string) => {
      // Check for conflict
      const existing = reservations.find(
        (r) => r.deskId === deskId && r.date === date,
      );
      if (existing) {
        throw new Error(`Biroul este deja rezervat pe ${date}`);
      }

      const now = new Date().toISOString();
      const reservation: DeskReservation = {
        id: uuid(),
        deskId,
        date,
        userName,
        notes,
        visibility: "all",
        createdAt: now,
        updatedAt: now,
      };
      await storage.set(`${PREFIX}${reservation.id}`, reservation);
      await refresh();
      return reservation;
    },
    [storage, refresh, reservations],
  );

  const cancelReservation = useCallback(
    async (id: string) => {
      await storage.delete(`${PREFIX}${id}`);
      await refresh();
    },
    [storage, refresh],
  );

  return {
    reservations,
    loading,
    addReservation,
    cancelReservation,
    refresh,
  };
}
