import { useQuery } from "@tanstack/react-query";
import { getReportRO } from "@/record-management/services/api/reportService";
type CountItem = Record<string, number>;
type CountGroup = Record<string, CountItem>;
type BoxCount = Record<string, number>;

const getDateRanges = () => {
  // helpers
  const pad2 = (n: number) => String(n).padStart(2, "0");
  const ymdLocal = (d: Date) =>
    `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;

  // now (local)
  const now = new Date();

  // daily: start of today -> start of tomorrow (exclusive end)
  const startOfToday = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate()
  );
  const startOfTomorrow = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate() + 1
  );
  const dailyFrom = ymdLocal(startOfToday);
  const dailyTo = ymdLocal(startOfTomorrow);

  // weekly (Monday..next Monday exclusive)
  const tmp = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // copy
  const dow = tmp.getDay(); // 0 = Sun, 1 = Mon, ...
  const diffToMonday = (dow + 6) % 7; // days back to Monday
  const startOfWeek = new Date(
    tmp.getFullYear(),
    tmp.getMonth(),
    tmp.getDate() - diffToMonday
  );
  const startOfNextWeek = new Date(
    startOfWeek.getFullYear(),
    startOfWeek.getMonth(),
    startOfWeek.getDate() + 7
  );
  const weeklyFrom = ymdLocal(startOfWeek);
  const weeklyTo = ymdLocal(startOfNextWeek);

  // monthly: first of month -> first of next month (exclusive end)
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0); // last day of current month

  const monthlyFrom = ymdLocal(startOfMonth);
  const monthlyTo = ymdLocal(endOfMonth);
  return {
    daily: { fromDate: dailyFrom, toDate: dailyTo },
    weekly: { fromDate: weeklyFrom, toDate: weeklyTo },
    monthly: { fromDate: monthlyFrom, toDate: monthlyTo },
  };
};

export const useIncomingRecordCounts = () => {
  const ranges = getDateRanges();

  // daily
  const { data: daily } = useQuery({
    queryKey: ["incomingRecords", "daily"],
    queryFn: () => getReportRO(ranges.daily),
  });

  // weekly
  const { data: weekly } = useQuery({
    queryKey: ["incomingRecords", "weekly"],
    queryFn: () => getReportRO(ranges.weekly),
  });

  // monthly
  const { data: monthly } = useQuery({
    queryKey: ["incomingRecords", "monthly"],
    queryFn: () => getReportRO(ranges.monthly),
  });
  // Smart: recordBoxCount (flat object with numbers)
  const sumSmart = (data?: BoxCount) => {
    if (!data) return 0;

    return Object.values(data).reduce((a, b) => a + b, 0);
  };

  // Incoming: recordCount (object of objects)
  const sumIncoming = (data?: CountGroup) => {
    if (!data) return 0;

    return Object.entries(data)
      .filter(
        ([key]) => !["internal", "internal_memo", "external"].includes(key)
      )
      .flatMap(([_, obj]) => Object.values(obj))
      .reduce((a, b) => a + b, 0);
  };

  // Combine both
  const calculateTotal = (
    recordCount?: CountGroup,
    recordBoxCount?: BoxCount
  ) => {
    return sumIncoming(recordCount) + sumSmart(recordBoxCount);
  };
  const monthlytotalOutgoing = monthly?.outgoingInstanceCount?.Dispatched || 0;
  const weeklytotalOutgoing = weekly?.outgoingInstanceCount?.Dispatched || 0;
  const dailytotalOutgoing = daily?.outgoingInstanceCount?.Dispatched || 0;
  return {
    dailyCount: calculateTotal(daily?.recordCount, daily?.recordBoxCount),
    weeklyCount: calculateTotal(weekly?.recordCount, weekly?.recordBoxCount),
    monthlyCount: calculateTotal(monthly?.recordCount, monthly?.recordBoxCount),
    dailyCountOutgoing: dailytotalOutgoing,
    weeklyCountOutgoing: weeklytotalOutgoing,
    monthlyCountOutgoing: monthlytotalOutgoing,
  };
};
