import { supabase } from "@/lib/supabase";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Task, TaskInsert, TaskUpdate } from "@/types/tasks.types";
import { Alert } from "react-native";

export const useTasksByTablo = (tabloId: string | undefined) => {
  return useQuery({
    queryKey: ["tasks", "tablo", tabloId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("tasks_with_assignee")
        .select("*")
        .eq("tablo_id", tabloId!)
        .eq("is_parent", false)
        .order("position", { ascending: true });

      if (error) throw error;
      return data as Task[];
    },
    enabled: !!tabloId,
  });
};

export const useCreateTask = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (task: TaskInsert) => {
      const { data, error } = await supabase
        .from("tasks")
        .insert({
          tablo_id: task.tablo_id,
          title: task.title,
          description: task.description ?? null,
          status: task.status || "todo",
          assignee_id: task.assignee_id ?? null,
          position: task.position ?? 0,
          parent_task_id: task.parent_task_id ?? null,
          is_parent: false,
          due_date: task.due_date ?? null,
        })
        .select()
        .single();

      if (error) throw error;
      return data;
    },
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["tasks", "tablo", variables.tablo_id] });
    },
    onError: () => {
      Alert.alert("Erreur", "Impossible de créer la tâche.");
    },
  });
};

export const useUpdateTask = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, tabloId, ...updates }: TaskUpdate & { id: string; tabloId: string }) => {
      const { data, error } = await supabase
        .from("tasks")
        .update(updates)
        .eq("id", id)
        .select()
        .single();

      if (error) throw error;
      return data;
    },
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["tasks", "tablo", variables.tabloId] });
    },
    onError: () => {
      Alert.alert("Erreur", "Impossible de modifier la tâche.");
    },
  });
};

export const useDeleteTask = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, tabloId }: { id: string; tabloId: string }) => {
      const { error } = await supabase.from("tasks").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["tasks", "tablo", variables.tabloId] });
    },
    onError: () => {
      Alert.alert("Erreur", "Impossible de supprimer la tâche.");
    },
  });
};
