import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "@xtablo/shared";
import { Database } from "@xtablo/shared/types/database.types";
import { supabase } from "../lib/supabase";
import { useUser } from "../providers/UserStoreProvider";
import { useAuthedApi } from "./auth";

type TabloInvite = Database["public"]["Tables"]["tablo_invites"]["Row"];
type PendingReceivedInvite = {
  id: number;
  tablo_id: string;
  tablo_name: string;
  created_at: string;
};

// Fetch all pending invites created by the current user
// export const usePendingTabloInvites = () => {
//   const user = useUser();

//   return useQuery({
//     queryKey: ["tablo-invites", "pending", user.id],
//     queryFn: async () => {
//       const { data, error } = await supabase
//         .from("tablo_invites")
//         .select("*")
//         .eq("invited_by", user.id)
//         .eq("is_pending", true)
//         .order("created_at", { ascending: false });

//       if (error) throw error;

//       return data as TabloInvite[];
//     },
//     enabled: !!user.id,
//   });
// };

// Fetch pending invites for a specific tablo
export const usePendingTabloInvitesByTablo = (tabloId: string) => {
  const user = useUser();

  return useQuery({
    queryKey: ["tablo-invites", tabloId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("tablo_invites")
        .select("*")
        .eq("invited_by", user.id)
        .eq("tablo_id", tabloId)
        .eq("is_pending", true)
        .order("created_at", { ascending: false });

      if (error) throw error;

      return data as TabloInvite[];
    },
    enabled: !!user.id && !!tabloId,
  });
};

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

  return useMutation({
    mutationFn: async ({ tabloId, inviteId }: { tabloId: string; inviteId: number }) => {
      await api.delete(`/api/v1/tablos/invite/${tabloId}/${inviteId}`);
    },
    onSuccess: (_data, { tabloId }) => {
      queryClient.invalidateQueries({ queryKey: ["tablo-invites", tabloId] });
      queryClient.invalidateQueries({ queryKey: ["tablo-invites", "received"] });
      queryClient.invalidateQueries({ queryKey: ["tablo-members", tabloId] });
      queryClient.invalidateQueries({ queryKey: ["notifications"] });
      toast.add(
        {
          title: "Invitation retirée",
          description: "L'invitation en attente a été supprimée",
          type: "success",
        },
        { timeout: 3000 }
      );
    },
    onError: (error) => {
      console.error("Error cancelling invite:", error);
      toast.add(
        {
          title: "Erreur",
          description: "Impossible de retirer l'invitation",
          type: "error",
        },
        { timeout: 5000 }
      );
    },
  });
};

export const useReceivedTabloInvites = () => {
  const api = useAuthedApi();

  return useQuery({
    queryKey: ["tablo-invites", "received"],
    queryFn: async () => {
      const { data } = await api.get<{ invites: PendingReceivedInvite[] }>(
        "/api/v1/tablos/invites/pending"
      );
      return data.invites;
    },
    refetchInterval: 30000,
  });
};

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

  return useMutation({
    mutationFn: async ({ inviteId }: { inviteId: number }) => {
      const { data } = await api.post<{ tablo_id: string }>(
        `/api/v1/tablos/invites/${inviteId}/accept`
      );
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tablo-invites", "received"] });
      queryClient.invalidateQueries({ queryKey: ["tablos"] });
      queryClient.invalidateQueries({ queryKey: ["notifications"] });
      toast.add(
        {
          title: "Invitation acceptée",
          description: "Vous avez rejoint le tablo",
          type: "success",
        },
        { timeout: 3000 }
      );
    },
    onError: (error) => {
      console.error("Error accepting invite:", error);
      toast.add(
        {
          title: "Erreur",
          description: "Impossible d'accepter l'invitation",
          type: "error",
        },
        { timeout: 5000 }
      );
    },
  });
};
