import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/useAuth";
import { toast } from "sonner";

export type ActionNote = {
  id: string;
  action_key: string;
  note: string;
  hotel_id: string | null;
  updated_at: string;
};

const KEY = (uid?: string, hotelId?: string) => ["action_notes", uid, hotelId] as const;

export function useActionNotes(hotelId: string | null | undefined) {
  const { user } = useAuth();
  const qc = useQueryClient();

  const q = useQuery({
    queryKey: KEY(user?.id, hotelId ?? undefined),
    enabled: !!user,
    staleTime: 30_000,
    queryFn: async (): Promise<ActionNote[]> => {
      let query = supabase
        .from("action_notes")
        .select("id,action_key,note,hotel_id,updated_at")
        .order("updated_at", { ascending: false });
      if (hotelId) query = query.eq("hotel_id", hotelId);
      const { data, error } = await query;
      if (error) throw error;
      return (data ?? []) as ActionNote[];
    },
  });

  const upsert = useMutation({
    mutationFn: async (input: { action_key: string; note: string }) => {
      if (!user) throw new Error("Sign in required");
      // delete existing then insert (no unique key)
      await supabase
        .from("action_notes")
        .delete()
        .eq("user_id", user.id)
        .eq("action_key", input.action_key);
      const { error } = await supabase.from("action_notes").insert([
        {
          user_id: user.id,
          hotel_id: hotelId ?? null,
          action_key: input.action_key,
          note: input.note,
        },
      ]);
      if (error) throw error;
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY(user?.id, hotelId ?? undefined) }),
    onError: (e: Error) => toast.error("Couldn't save note", { description: e.message }),
  });

  const remove = useMutation({
    mutationFn: async (action_key: string) => {
      if (!user) return;
      const { error } = await supabase
        .from("action_notes")
        .delete()
        .eq("user_id", user.id)
        .eq("action_key", action_key);
      if (error) throw error;
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY(user?.id, hotelId ?? undefined) }),
  });

  const items = q.data ?? [];
  const byKey = new Map(items.map((r) => [r.action_key, r] as const));
  return {
    items,
    isLoading: q.isLoading,
    get: (k: string) => byKey.get(k) ?? null,
    save: (action_key: string, note: string) => upsert.mutate({ action_key, note }),
    remove: (action_key: string) => remove.mutate(action_key),
  };
}
