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

// ── Types ─────────────────────────────────────────────────────────────────────

export type Trip = {
  id: string;
  householdId: string;
  name: string;
  destination: string | null;
  budget: number;
  startDate: string; // YYYY-MM-DD
  endDate: string; // YYYY-MM-DD
  status: "active" | "completed";
  spent: number; // computed by server
  createdAt: string;
  settlementFromUserId: string | null;
  settlementToUserId: string | null;
  settlementAmount: number | null;
  settledAt: string | null;
};

export type TripSettlement = {
  total: number;
  fairShare: number;
  balances: Array<{
    userId: string;
    name: string;
    paid: number;
    fairShare: number;
    balance: number;
  }>;
  settlement: {
    from: string;
    fromName: string;
    to: string;
    toName: string;
    amount: number;
  } | null;
};

export type TripExpense = {
  id: string;
  tripId: string;
  householdId: string;
  label: string;
  amount: number;
  category: "unterkunft" | "essen" | "transport" | "aktivitaeten" | "sonstiges";
  paidBy: string; // userId
  date: string;
  note: string | null;
  createdAt: string;
};

export type TripSummary = {
  trip: Trip;
  totalSpent: number;
  remaining: number;
  byCategory: Record<string, number>;
};

export type CreateTripInput = {
  name: string;
  destination?: string;
  budget: number;
  startDate: string;
  endDate: string;
};

export type UpdateTripInput = {
  name?: string;
  destination?: string | null;
  budget?: number;
  startDate?: string;
  endDate?: string;
};

export type CreateTripExpenseInput = {
  label: string;
  amount: number;
  category: TripExpense["category"];
  paidBy: string;
  date: string;
  note?: string;
};

export type UpdateTripExpenseInput = {
  label?: string;
  amount?: number;
  category?: TripExpense["category"];
  paidBy?: string;
  date?: string;
  note?: string | null;
};

// ── Trip Queries ──────────────────────────────────────────────────────────────

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

export function useTrip(id: string) {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["trip-summary", id, activeHouseholdId],
    queryFn: () => apiRequest<{ summary: TripSummary }>(`/api/trips/${id}/summary`),
    select: (data) => data.summary,
    enabled: !!activeHouseholdId && !!id,
  });
}

export function useTripExpenses(tripId: string) {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["trip-expenses", tripId, activeHouseholdId],
    queryFn: () => apiRequest<{ expenses: TripExpense[] }>(`/api/trips/${tripId}/expenses`),
    select: (data) => data.expenses,
    enabled: !!activeHouseholdId && !!tripId,
  });
}

export function useTripSettlement(tripId: string) {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["trip-settlement", tripId, activeHouseholdId],
    queryFn: () =>
      apiRequest<{ settlement: TripSettlement }>(`/api/trips/${tripId}/settlement`),
    select: (data) => data.settlement,
    enabled: !!tripId && !!activeHouseholdId,
  });
}

// ── Trip Mutations ────────────────────────────────────────────────────────────

export function useCreateTrip() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateTripInput) =>
      apiRequest<{ trip: Trip }>("/api/trips", {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["trips"] });
    },
  });
}

export function useUpdateTrip(id: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: UpdateTripInput) =>
      apiRequest<{ trip: Trip }>(`/api/trips/${id}`, {
        method: "PATCH",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["trips"] });
      void queryClient.invalidateQueries({ queryKey: ["trip-summary", id] });
    },
  });
}

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

export function useCompleteTrip() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiRequest<{ trip: Trip }>(`/api/trips/${id}/complete`, { method: "POST" }),
    onSuccess: (_data, id) => {
      void queryClient.invalidateQueries({ queryKey: ["trips"] });
      void queryClient.invalidateQueries({ queryKey: ["trip-summary", id] });
      void queryClient.invalidateQueries({ queryKey: ["trip-settlement", id] });
    },
  });
}

// ── Trip Expense Mutations ────────────────────────────────────────────────────

export function useCreateTripExpense(tripId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateTripExpenseInput) =>
      apiRequest<{ expense: TripExpense }>(`/api/trips/${tripId}/expenses`, {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["trip-expenses", tripId] });
      void queryClient.invalidateQueries({ queryKey: ["trip-summary", tripId] });
      void queryClient.invalidateQueries({ queryKey: ["trips"] });
    },
  });
}

export function useDeleteTripExpense(tripId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (expenseId: string) =>
      apiRequest<{ success: boolean }>(`/api/trips/${tripId}/expenses/${expenseId}`, {
        method: "DELETE",
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["trip-expenses", tripId] });
      void queryClient.invalidateQueries({ queryKey: ["trip-summary", tripId] });
      void queryClient.invalidateQueries({ queryKey: ["trips"] });
    },
  });
}

export function useUpdateTripExpense(tripId: string) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ expenseId, input }: { expenseId: string; input: UpdateTripExpenseInput }) =>
      apiRequest<{ expense: TripExpense }>(`/api/trips/${tripId}/expenses/${expenseId}`, {
        method: "PATCH",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["trip-expenses", tripId] });
      void queryClient.invalidateQueries({ queryKey: ["trip-summary", tripId] });
      void queryClient.invalidateQueries({ queryKey: ["trips"] });
    },
  });
}
