import { supabase } from "@/lib/supabase";
import { useUser } from "@/providers/UserProvider";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { TabloInsert, UserTablo } from "@/types/tablos.types";
import { api } from "@/lib/api";
import { useAuthStore } from "@/stores/auth";
import { Alert } from "react-native";

// type TabloInsert = Tablo["Insert"];
// type TabloUpdate = Tablo["Update"];

// Fetch all tablos
export const useTablosList = () => {
  const user = useUser();
  return useQuery({
    queryKey: ["tablos"],
    queryFn: async () => {
      const { data, error } = await supabase.from("user_tablos").select("*").eq("user_id", user.id);
      if (error) throw error;
      const tablos = data as UserTablo[];
      return tablos;
    },
    refetchInterval: 1000 * 60 * 5, // 5 minutes
  });
};

export const useCreateTablo = () => {
  const session = useAuthStore((state) => state.session);
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (tablo: Pick<TabloInsert, "name" | "color" | "image" | "status">) => {
      const { data } = await api.post("/api/v1/tablos/create", tablo, {
        headers: {
          Authorization: `Bearer ${session?.access_token}`,
        },
      });
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tablos"] });
    },
    onError: (error) => {
      Alert.alert("Erreur", "Impossible de créer le tablo.");
    },
  });
};

// Delete tablo (soft delete)
export const useDeleteTablo = () => {
  const session = useAuthStore((state) => state.session);
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      await api.delete("/api/v1/tablos/delete", {
        data: { id },
        headers: {
          Authorization: `Bearer ${session?.access_token}`,
        },
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tablos"] });
    },
    onError: (error) => {
      console.error(error);
      Alert.alert("Erreur", "Impossible de supprimer le tablo. Veuillez réessayer.");
    },
  });
};
