import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast, useSession } from "@xtablo/shared";
import { useAuthedApi } from "./auth";

type PendingClientInvite = {
  id: number;
  invited_email: string;
  expires_at: string;
  is_pending: boolean;
  created_at: string;
};

type CreateClientInviteResponse = {
  success: true;
  inviteMode: "notification" | "setup";
};

export const usePendingClientInvites = (tabloId: string) => {
  const api = useAuthedApi();
  const { session } = useSession();

  return useQuery({
    queryKey: ["client-invites", tabloId],
    queryFn: async () => {
      const { data } = await api.get<PendingClientInvite[]>(
        `/api/v1/client-invites/${tabloId}/pending`
      );
      return data;
    },
    enabled: !!tabloId && !!session,
  });
};

export const useCreateClientInvite = () => {
  const api = useAuthedApi();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ tabloId, email }: { tabloId: string; email: string }) => {
      const { data } = await api.post<CreateClientInviteResponse>(
        `/api/v1/client-invites/${tabloId}`,
        {
          email,
        }
      );
      return data;
    },
    onSuccess: (data, { tabloId }) => {
      queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] });
      toast.add(
        {
          title: data.inviteMode === "setup" ? "Invitation client envoyée" : "Accès client accordé",
          description:
            data.inviteMode === "setup"
              ? "Un email de configuration du mot de passe a été envoyé au client."
              : "Le client a été informé de son nouvel accès et pourra se connecter à son espace.",
          type: "success",
        },
        { timeout: 3000 }
      );
    },
    onError: (error) => {
      console.error("Error creating client invite:", error);
      toast.add(
        {
          title: "Erreur",
          description: "Impossible d'envoyer l'invitation client",
          type: "error",
        },
        { timeout: 5000 }
      );
    },
  });
};

export const useCancelClientInvite = () => {
  const api = useAuthedApi();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ tabloId, inviteId }: { tabloId: string; inviteId: number }) => {
      await api.delete(`/api/v1/client-invites/${tabloId}/${inviteId}`);
    },
    onSuccess: (_data, { tabloId }) => {
      queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] });
    },
    onError: (error) => {
      console.error("Error cancelling client invite:", error);
      toast.add(
        {
          title: "Erreur",
          description: "Impossible d'annuler l'invitation client",
          type: "error",
        },
        { timeout: 5000 }
      );
    },
  });
};
