import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
import useAuth from "@/hooks/useAuth";
import { getMyInvoices } from "@/lib/currentCustomer";
import { api } from "@/services/api";
import { ACTIVE_STATUSES } from "./constants";

export function useMyPortalData(selectedProfileId?: string) {
  const { user, customer, company } = useAuth();
  const myInvoices = useMemo(() => getMyInvoices(), []);

  const companyProfiles = company?.company?.companyProfiles ?? [];

  const bookingsQuery = useQuery(
    api.bookings.list.queryOptions({
      input: {
        sortBy: "createdAt",
        sortOrder: "DESC",
        companyProfileId: selectedProfileId,
      },
    }),
  );

  const dashboardQuery = useQuery(
    api.companies.getDashboard.queryOptions({ input: selectedProfileId }),
  );

  const allBookings = bookingsQuery.data?.items ?? [];
  const activeBookings = allBookings.filter((b) =>
    ACTIVE_STATUSES.includes(b.status),
  );

  const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
  const newActiveThisWeek = activeBookings.filter(
    (b) => new Date(b.createdAt).getTime() >= weekAgo,
  ).length;

  const outstandingInvoices = myInvoices.filter(
    (inv) => inv.status === "Sent" || inv.status === "Overdue",
  );

  const totalOutstanding = outstandingInvoices.reduce(
    (sum, inv) => sum + inv.amount,
    0,
  );

  const displayName = user?.name?.en ?? user?.username ?? user?.email ?? "—";
  const companyName = (customer as any)?.companyName ?? displayName;

  const hour = new Date().getHours();
  const greeting =
    hour < 12
      ? "Good morning,"
      : hour < 18
        ? "Good afternoon,"
        : "Good evening,";

  const recentInvoices = myInvoices.slice(0, 3);

  const dashboard = dashboardQuery.data;
  const volumePoints = dashboard?.freightVolume.monthly ?? [];
  const maxVolume = Math.max(1, ...volumePoints.map((p) => p.tonnes));

  return {
    user,
    customer,
    companyProfiles,
    bookingsQuery,
    dashboardQuery,
    allBookings,
    activeBookings,
    newActiveThisWeek,
    outstandingInvoices,
    totalOutstanding,
    companyName,
    greeting,
    recentInvoices,
    dashboard,
    volumePoints,
    maxVolume,
    myInvoices,
  };
}
