import { createFileRoute } from '@tanstack/react-router'
import { DashboardTemplate } from '@/template/dashboard-template'
import {
  useGetDashboardSummary,
  useGetDashboardGeneralInfo,
  useGetDeviceOverview,
  useGetDeviceStatusByRoom,
  useGetRoomUsage,
  useGetRoomManagement,
  useGetSoftwareDistribution,
} from '@/hooks/queries/useDashboardQueries'

export const Route = createFileRoute('/_auth/dashboard/')({
  component: RouteComponent,
  head: () => ({ meta: [{ title: 'Dashboard' }] }),
  loader: async ({ context }) => {
    context.breadcrumbs = [
      { title: "Dashboard", path: "#" },
    ];
  },
})

function RouteComponent() {
  const summaryQuery = useGetDashboardSummary();
  const generalQuery = useGetDashboardGeneralInfo();
  const deviceOverviewQuery = useGetDeviceOverview();
  const devicesByRoomQuery = useGetDeviceStatusByRoom();
  const roomUsageQuery = useGetRoomUsage();
  const roomsQuery = useGetRoomManagement();
  const softwareQuery = useGetSoftwareDistribution();

  const isLoading =
    summaryQuery.isLoading ||
    generalQuery.isLoading ||
    deviceOverviewQuery.isLoading ||
    devicesByRoomQuery.isLoading ||
    roomUsageQuery.isLoading ||
    roomsQuery.isLoading ||
    softwareQuery.isLoading;

  const isFetching =
    summaryQuery.isFetching ||
    generalQuery.isFetching ||
    deviceOverviewQuery.isFetching ||
    devicesByRoomQuery.isFetching ||
    roomUsageQuery.isFetching ||
    roomsQuery.isFetching ||
    softwareQuery.isFetching;

  const handleRefresh = async () => {
    await Promise.allSettled([
      summaryQuery.refetch(),
      generalQuery.refetch(),
      deviceOverviewQuery.refetch(),
      devicesByRoomQuery.refetch(),
      roomUsageQuery.refetch(),
      roomsQuery.refetch(),
      softwareQuery.refetch(),
    ]);
  };

  return (
    <DashboardTemplate
      generalInfo={generalQuery.data ?? summaryQuery.data?.generalInfo}
      deviceOverview={deviceOverviewQuery.data ?? summaryQuery.data?.deviceOverview}
      roomManagement={roomsQuery.data ?? summaryQuery.data?.roomManagement}
      roomUsage={roomUsageQuery.data ?? summaryQuery.data?.roomUsage}
      softwareDistribution={softwareQuery.data ?? summaryQuery.data?.softwareDistribution}
      devicesByRoom={devicesByRoomQuery.data}
      isLoading={isLoading}
      isFetching={isFetching}
      onRefresh={handleRefresh}
    />
  );
}
