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 FocusedRow = {
  id: string;
  competitor_key: string;
  competitor_name: string;
  notes: string | null;
  snapshot: Record<string, unknown>;
  updated_at: string;
};

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

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

  const q = useQuery({
    queryKey: KEY(user?.id, hotelId ?? undefined),
    enabled: !!user && !!hotelId,
    staleTime: 30_000,
    queryFn: async (): Promise<FocusedRow[]> => {
      const { data, error } = await supabase
        .from("focused_competitors")
        .select("id,competitor_key,competitor_name,notes,snapshot,updated_at")
        .eq("hotel_id", hotelId!)
        .order("updated_at", { ascending: false });
      if (error) throw error;
      return (data ?? []) as FocusedRow[];
    },
  });

  const add = useMutation({
    mutationFn: async (input: {
      competitor_key: string;
      competitor_name: string;
      snapshot?: Record<string, unknown>;
      notes?: string;
    }) => {
      if (!user || !hotelId) throw new Error("Sign in to track competitors");
      const { error } = await supabase.from("focused_competitors").insert([
        {
          user_id: user.id,
          hotel_id: hotelId,
          competitor_key: input.competitor_key,
          competitor_name: input.competitor_name,
          snapshot: (input.snapshot ?? {}) as never,
          notes: input.notes ?? null,
        },
      ]);
      if (error) throw error;
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY(user?.id, hotelId ?? undefined) }),
    onError: (e: Error) => toast.error("Couldn't track competitor", { description: e.message }),
  });

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

  const items = q.data ?? [];
  const keys = new Set(items.map((r) => r.competitor_key));
  return {
    items,
    keys,
    isLoading: q.isLoading,
    isTracked: (k: string) => keys.has(k),
    track: (input: Parameters<typeof add.mutate>[0]) => add.mutate(input),
    untrack: (k: string) => remove.mutate(k),
  };
}
