import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "../lib/api-client";
import { useAuthStore } from "../stores/auth.store";
import { authClient } from "../lib/auth-client";

export type HouseholdMember = {
  userId: string;
  name: string;
  email: string;
  role: string;
};

export type PendingInvitation = {
  id: string;
  email: string;
  role: string | null;
  status: string;
  expiresAt: string;
  createdAt: string;
};

type MembersResponse = {
  members: HouseholdMember[];
  pendingInvitations: PendingInvitation[];
};

export function useHouseholdMembers() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["household-members", activeHouseholdId],
    queryFn: () => apiRequest<MembersResponse>("/api/households/members"),
    enabled: !!activeHouseholdId,
  });
}

export function useInviteMember() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (email: string) => {
      const result = await authClient.organization.inviteMember({
        email,
        role: "member",
        organizationId: activeHouseholdId!,
      });
      if (result.error) throw new Error(result.error.message ?? "Einladung fehlgeschlagen");
      return result.data;
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["household-members", activeHouseholdId] });
    },
  });
}

export function useRevokeInvitation() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (invitationId: string) =>
      apiRequest(`/api/households/invitations/${invitationId}`, { method: "DELETE" }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["household-members", activeHouseholdId] });
    },
  });
}

export function useAcceptInvitation() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (invitationId: string) => {
      const result = await authClient.organization.acceptInvitation({ invitationId });
      if (result.error) throw new Error(result.error.message ?? "Annahme fehlgeschlagen");
      return result.data;
    },
    onSuccess: () => {
      void queryClient.invalidateQueries();
    },
  });
}
