import { queryOptions } from "@tanstack/react-query";
import { jsonQuery, paginatedJsonQuery } from "../apiAdapter";

export interface TripVehicle {
  id: number;
  spz: string;
  name: string;
}

export interface TripUser {
  id: number;
  name: string;
}

export interface BackendTrip {
  id: number;
  vehicle_id: number;
  user_id: number;
  trip_date: string;
  start_km: number;
  end_km: number;
  distance: number | null;
  route_from: string;
  route_to: string;
  is_business: boolean;
  notes: string | null;
  users: { id: number; first_name: string; last_name: string };
  vehicles: { id: number; name: string; spz: string };
}

export const tripListOptions = (filters: {
  month?: number;
  year?: number;
  vehicleId?: number;
  userId?: number;
  page?: number;
  perPage?: number;
}) =>
  queryOptions({
    queryKey: [
      "trips",
      "list",
      {
        month: filters.month,
        year: filters.year,
        vehicleId: filters.vehicleId,
        userId: filters.userId,
        page: filters.page,
        perPage: filters.perPage,
      },
    ],
    queryFn: () => {
      const params = new URLSearchParams();
      if (filters.month) params.set("month", String(filters.month));
      if (filters.year) params.set("year", String(filters.year));
      if (filters.vehicleId)
        params.set("vehicle_id", String(filters.vehicleId));
      if (filters.userId) params.set("user_id", String(filters.userId));
      if (filters.page) params.set("page", String(filters.page));
      if (filters.perPage) params.set("per_page", String(filters.perPage));
      const qs = params.toString();
      return paginatedJsonQuery<BackendTrip>(
        `/api/admin/trips${qs ? `?${qs}` : ""}`,
      );
    },
  });

export const tripVehiclesOptions = () =>
  queryOptions({
    queryKey: ["trips", "vehicles"],
    queryFn: () => jsonQuery<TripVehicle[]>("/api/admin/vehicles"),
    staleTime: 2 * 60_000,
  });

export const tripUsersOptions = () =>
  queryOptions({
    queryKey: ["trips", "users"],
    queryFn: () => jsonQuery<TripUser[]>("/api/admin/trips/users"),
    staleTime: 2 * 60_000,
  });

export const tripHistoryOptions = (filters: {
  month?: string;
  vehicleId?: number;
  userId?: number;
  page?: number;
  perPage?: number;
}) =>
  queryOptions({
    queryKey: [
      "trips",
      "history",
      {
        month: filters.month,
        vehicleId: filters.vehicleId,
        userId: filters.userId,
        page: filters.page,
        perPage: filters.perPage,
      },
    ],
    queryFn: () => {
      const params = new URLSearchParams();
      if (filters.month) params.set("month", filters.month);
      if (filters.vehicleId)
        params.set("vehicle_id", String(filters.vehicleId));
      if (filters.userId) params.set("user_id", String(filters.userId));
      if (filters.page) params.set("page", String(filters.page));
      if (filters.perPage) params.set("per_page", String(filters.perPage));
      const qs = params.toString();
      return paginatedJsonQuery<BackendTrip>(
        `/api/admin/trips${qs ? `?${qs}` : ""}`,
      );
    },
  });

export interface TripStats {
  count: number;
  total_km: number;
  business_km: number;
  private_km: number;
}

// Count/km totals over the WHOLE filtered set (not one page) — hits
// /trips/stats with the same filters the lists use. `month` accepts either a
// numeric month (paired with `year`, TripsAdmin style) or a combined
// "YYYY-MM" string (TripsHistory style); the server supports both.
export const tripStatsOptions = (filters: {
  month?: number | string;
  year?: number;
  vehicleId?: number;
  userId?: number;
}) =>
  queryOptions({
    queryKey: [
      "trips",
      "stats",
      {
        month: filters.month,
        year: filters.year,
        vehicleId: filters.vehicleId,
        userId: filters.userId,
      },
    ],
    queryFn: () => {
      const params = new URLSearchParams();
      if (filters.month) params.set("month", String(filters.month));
      if (filters.year) params.set("year", String(filters.year));
      if (filters.vehicleId)
        params.set("vehicle_id", String(filters.vehicleId));
      if (filters.userId) params.set("user_id", String(filters.userId));
      const qs = params.toString();
      return jsonQuery<TripStats>(
        `/api/admin/trips/stats${qs ? `?${qs}` : ""}`,
      );
    },
  });
