import { useMutation } from "@tanstack/react-query";
import type { AxiosInstance } from "axios";
import { useNavigate } from "react-router-dom";
import { queryClient } from "../lib/api";
import { toast } from "../lib/toast";
import { invalidatePublicSlots } from "./public";

type BookSlotPayload = {
  event_type_standard_name: string;
  owner_short_id: string;
  event_details: {
    start_date: string;
    start_time: string;
    end_time: string;
  };
  user_details: {
    name: string;
    email: string;
  };
};

type BookSlotResponse = {
  tablo_id: string;
  hasCreatedAccount: boolean;
  email: string;
};

// Book a slot with an event type owner
export const useBookSlot = (
  api: AxiosInstance,
  accessToken?: string,
  onSuccess?: (data: BookSlotResponse) => void
) => {
  const navigate = useNavigate();

  return useMutation<BookSlotResponse, unknown, BookSlotPayload>({
    mutationFn: async (payload: BookSlotPayload) => {
      const headers: Record<string, string> = {};
      if (accessToken) {
        headers.Authorization = `Bearer ${accessToken}`;
      }

      const { data } = await api.post("/api/v1/book/slot", payload, {
        headers,
        timeout: 10000,
      });
      return data;
    },
    onSuccess: (data) => {
      const { tablo_id, hasCreatedAccount, email } = data;

      toast.add({
        title: "Réservation confirmée avec succès",
        description: hasCreatedAccount
          ? "Vous avez reçu un email de confirmation et votre compte a été créé automatiquement. Un mot de passe vous a été envoyé par email."
          : "Vous recevrez un email de confirmation dans quelques instants",
        type: "success",
      });

      queryClient.invalidateQueries({ queryKey: ["tablos"] });
      invalidatePublicSlots();

      // Call custom onSuccess callback if provided
      if (onSuccess) {
        onSuccess(data);
      } else {
        // Default navigation behavior
        if (hasCreatedAccount) {
          navigate(`/login?email=${email}`, { replace: true });
        } else {
          navigate(`/tablos/${tablo_id}`, { replace: true });
        }
      }
    },
    onError: (error) => {
      console.error(error);
      toast.add(
        {
          title: "Échec de la réservation",
          description: "Veuillez réessayer",
          type: "error",
        },
        {
          timeout: 5000,
        }
      );
    },
  });
};
