import { useEffect, useMemo } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/useAuth";
import type { Hotel } from "@/lib/hotel";

const HOTELS_KEY = (uid?: string) => ["hotels", uid] as const;
const PREFS_KEY = (uid?: string) => ["user_preferences", uid] as const;

export type UserPreferences = {
  user_id: string;
  theme: "light" | "dark";
  lang: "en" | "zh";
  selected_hotel_id: string | null;
  notifications_enabled: boolean;
};

/** All hotels owned by the user + the currently-selected hotel (or null = portfolio/all). */
export function useHotels() {
  const { user } = useAuth();
  const qc = useQueryClient();

  const hotelsQuery = useQuery({
    queryKey: HOTELS_KEY(user?.id),
    enabled: !!user,
    queryFn: async (): Promise<Hotel[]> => {
      const { data, error } = await supabase
        .from("hotels")
        .select("*")
        .eq("user_id", user!.id)
        .order("created_at", { ascending: true });
      if (error) throw error;
      return (data ?? []) as Hotel[];
    },
  });

  const prefsQuery = useQuery({
    queryKey: PREFS_KEY(user?.id),
    enabled: !!user,
    queryFn: async (): Promise<UserPreferences | null> => {
      const { data, error } = await supabase
        .from("user_preferences")
        .select("*")
        .eq("user_id", user!.id)
        .maybeSingle();
      if (error) throw error;
      return (data as UserPreferences | null) ?? null;
    },
  });

  // Auto-seed preference row + default selected hotel
  useEffect(() => {
    if (!user) return;
    if (prefsQuery.isLoading || hotelsQuery.isLoading) return;
    const prefs = prefsQuery.data;
    const hotels = hotelsQuery.data ?? [];
    if (!prefs) {
      const initial = {
        user_id: user.id,
        theme: "light",
        lang: "en",
        selected_hotel_id: hotels[0]?.id ?? null,
        notifications_enabled: true,
      };
      supabase
        .from("user_preferences")
        .insert(initial)
        .then(() => qc.invalidateQueries({ queryKey: PREFS_KEY(user.id) }));
    } else if (
      prefs.selected_hotel_id &&
      !hotels.some((h) => h.id === prefs.selected_hotel_id)
    ) {
      // Selected hotel was deleted — reset
      supabase
        .from("user_preferences")
        .update({ selected_hotel_id: hotels[0]?.id ?? null })
        .eq("user_id", user.id)
        .then(() => qc.invalidateQueries({ queryKey: PREFS_KEY(user.id) }));
    }
  }, [user, prefsQuery.data, prefsQuery.isLoading, hotelsQuery.data, hotelsQuery.isLoading, qc]);

  const selectMutation = useMutation({
    mutationFn: async (hotelId: string | null) => {
      if (!user) throw new Error("Not signed in");
      const { error } = await supabase
        .from("user_preferences")
        .upsert(
          { user_id: user.id, selected_hotel_id: hotelId },
          { onConflict: "user_id" },
        );
      if (error) throw error;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: PREFS_KEY(user?.id) });
    },
  });

  const hotels = hotelsQuery.data ?? [];
  const selectedId = prefsQuery.data?.selected_hotel_id ?? null;
  const selectedHotel = useMemo(
    () => hotels.find((h) => h.id === selectedId) ?? null,
    [hotels, selectedId],
  );

  return {
    hotels,
    selectedHotel,
    selectedHotelId: selectedId,
    isAllHotels: selectedId === null && hotels.length > 0,
    isLoading: hotelsQuery.isLoading || prefsQuery.isLoading,
    prefs: prefsQuery.data ?? null,
    selectHotel: (id: string | null) => selectMutation.mutate(id),
    refetch: () => {
      qc.invalidateQueries({ queryKey: HOTELS_KEY(user?.id) });
      qc.invalidateQueries({ queryKey: PREFS_KEY(user?.id) });
    },
  };
}
