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

export type Debt = {
  id: string;
  householdId: string;
  userId: string;
  creditorUserId: string | null;
  creditorUserName: string | null;
  label: string;
  creditor: string | null;
  totalAmount: number;
  paidAmount: number;
  remainingAmount: number;
  progressPercent: number;
  notes: string | null;
  createdAt: string;
  closedAt: string | null;
};

export type DebtPayment = {
  id: string;
  debtId: string;
  amount: number;
  date: string;
  note: string | null;
  linkedTransactionId: string | null;
  createdAt: string;
};

export type CreateDebtInput = {
  label: string;
  creditorUserId?: string;
  creditor?: string;
  totalAmount: number;
  notes?: string;
};

export type CreateDebtPaymentInput = {
  debtId: string;
  amount: number;
  date: string;
  note?: string;
};

export function useDebts() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["debts", activeHouseholdId],
    queryFn: () => apiRequest<{ debts: Debt[] }>("/api/debts"),
    select: (data) => data.debts,
    enabled: !!activeHouseholdId,
  });
}

export function useClaims() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["debts-claims", activeHouseholdId],
    queryFn: () => apiRequest<{ debts: Debt[] }>("/api/debts/claims"),
    select: (data) => data.debts,
    enabled: !!activeHouseholdId,
  });
}

export function useCreateDebt() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateDebtInput) =>
      apiRequest<{ debt: Debt }>("/api/debts", {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["debts"] });
    },
  });
}

export function useDeleteDebt() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiRequest<{ success: boolean }>(`/api/debts/${id}`, {
        method: "DELETE",
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["debts"] });
      void queryClient.invalidateQueries({ queryKey: ["transactions"] });
    },
  });
}

export function useCreateDebtPayment() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateDebtPaymentInput) =>
      apiRequest<{ payment: DebtPayment; debt: Debt }>("/api/debts/payments", {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["debts"] });
      void queryClient.invalidateQueries({ queryKey: ["debts-claims"] });
      void queryClient.invalidateQueries({ queryKey: ["transactions"] });
    },
  });
}
