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

export type FixedCost = {
  id: string;
  householdId: string;
  scope: "household" | "private" | "child";
  childId: string | null;
  categoryId: string | null;
  label: string;
  amount: number;
  type: "income" | "expense";
  isActive: boolean;
  createdAt: string;
};

export type TransferLineItem = {
  id: string;
  householdId: string;
  label: string;
  amount: number;
  isActive: boolean;
  createdAt: string;
};

export type MonthlyTransfer = {
  id: string;
  householdId: string;
  month: string;
  fromUserId: string;
  toUserId: string;
  amount: number;
  note: string | null;
  createdAt: string;
};

export type NettoMonth = {
  month: string;
  totalIncome: number;
  incomeByScope: Array<{ scope: string; label: string; amount: number }>;
  totalExpenses: number;
  netto: number;
};

export type SettlementV2 = {
  month: string;
  householdExpenses: number;
  householdIncome: number;
  householdNet: number;
  memberCount: number;
  perMemberShare: number;
  userSharePercent: number;
  lineItems: Array<{ id: string; label: string; amount: number }>;
  lineItemsTotal: number;
  myOwnExpenses: number;
  transfers: MonthlyTransfer[];
  alreadyTransferred: number;
  totalOwed: number;
  remaining: number;
  members: Array<{ userId: string; name: string; paid: number; owes: number }>;
};

export type CreateFixedCostInput = {
  scope: "household" | "private" | "child";
  childId?: string;
  categoryId?: string;
  label: string;
  amount: number;
  type?: "income" | "expense";
};

export type UpdateFixedCostInput = {
  label?: string;
  amount?: number;
  categoryId?: string | null;
  isActive?: boolean;
};

// ── Fixed Costs ───────────────────────────────────────────────────────────────

export function useFixedCosts() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["fixed-costs", activeHouseholdId],
    queryFn: () => apiRequest<{ fixedCosts: FixedCost[] }>("/api/fixed-costs"),
    select: (data) => data.fixedCosts,
    enabled: !!activeHouseholdId,
  });
}

export function useCreateFixedCost() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateFixedCostInput) =>
      apiRequest<{ fixedCost: FixedCost }>("/api/fixed-costs", {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["fixed-costs"] });
    },
  });
}

export function useUpdateFixedCost() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, input }: { id: string; input: UpdateFixedCostInput }) =>
      apiRequest<{ fixedCost: FixedCost }>(`/api/fixed-costs/${id}`, {
        method: "PATCH",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["fixed-costs"] });
    },
  });
}

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

// ── Transfer Line Items ───────────────────────────────────────────────────────

export function useTransferLineItems() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["transfer-line-items", activeHouseholdId],
    queryFn: () => apiRequest<{ lineItems: TransferLineItem[] }>("/api/fixed-costs/line-items"),
    select: (data) => data.lineItems,
    enabled: !!activeHouseholdId,
  });
}

export function useCreateTransferLineItem() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: { label: string; amount: number }) =>
      apiRequest<{ lineItem: TransferLineItem }>("/api/fixed-costs/line-items", {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["transfer-line-items"] });
      void queryClient.invalidateQueries({ queryKey: ["settlement-v2"] });
    },
  });
}

export function useDeleteTransferLineItem() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiRequest<{ success: boolean }>(`/api/fixed-costs/line-items/${id}`, { method: "DELETE" }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["transfer-line-items"] });
      void queryClient.invalidateQueries({ queryKey: ["settlement-v2"] });
    },
  });
}

// ── Monthly Transfers ─────────────────────────────────────────────────────────

export function useCreateMonthlyTransfer() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: { month: string; toUserId: string; amount: number; note?: string }) =>
      apiRequest<{ transfer: MonthlyTransfer }>("/api/fixed-costs/monthly-transfers", {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["settlement-v2"] });
    },
  });
}

// ── Netto Month ───────────────────────────────────────────────────────────────

export function useNettoMonth(month: string) {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["netto-month", activeHouseholdId, month],
    queryFn: () =>
      apiRequest<{ netto: NettoMonth | null }>(`/api/fixed-costs/netto/${month}`),
    select: (data) => data.netto,
    enabled: !!activeHouseholdId,
  });
}

// ── Settlement V2 ─────────────────────────────────────────────────────────────

export function useSettlementV2(month: string) {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["settlement-v2", activeHouseholdId, month],
    queryFn: () =>
      apiRequest<{ settlement: SettlementV2 }>(`/api/fixed-costs/settlement/${month}`),
    select: (data) => data.settlement,
    enabled: !!activeHouseholdId,
  });
}
