import { useState } from 'react';

import { useFrameEntries } from '@/business/frame/hooks';
import { useSafetyQuizResults } from '@/business/safety-quiz/hooks';
import {
  useStaffAttendanceRecords,
  useStaffAttendanceSummary,
} from '@/business/staff-attendance/hooks';
import {
  buildDirectorFramePreviews,
  buildDirectorOverviewCards,
  buildDirectorRiskAreas,
} from '@/business/director-dashboard/selectors';
import type { DirectorDashboardPage } from '@/business/director-dashboard/types';
import {
  DIRECTOR_DASHBOARD_QUICK_ACTIONS,
  type DirectorDashboardTimeRange,
} from '@/shared/constants/directorDashboard';

export function useDirectorDashboardPage(): DirectorDashboardPage {
  const [timeRange, setTimeRangeState] = useState<DirectorDashboardTimeRange>('month');
  const frameEntriesQuery = useFrameEntries();
  const quizResultsQuery = useSafetyQuizResults();
  const staffAttendanceRecordsQuery = useStaffAttendanceRecords();
  const staffAttendanceSummaryQuery = useStaffAttendanceSummary();
  const frameEntries = frameEntriesQuery.data ?? [];
  const quizResults = quizResultsQuery.data ?? [];
  const attendanceRecords = staffAttendanceRecordsQuery.data ?? [];
  const staffCount = staffAttendanceSummaryQuery.data?.staffCount ?? 0;
  const isLoading = frameEntriesQuery.isLoading
    || quizResultsQuery.isLoading
    || staffAttendanceRecordsQuery.isLoading
    || staffAttendanceSummaryQuery.isLoading;
  const error = frameEntriesQuery.error
    ?? quizResultsQuery.error
    ?? staffAttendanceRecordsQuery.error
    ?? staffAttendanceSummaryQuery.error;

  return {
    timeRange,
    overviewCards: buildDirectorOverviewCards(
      attendanceRecords,
      quizResults,
      frameEntries,
      staffCount,
    ),
    riskAreas: buildDirectorRiskAreas(attendanceRecords, quizResults, staffCount),
    framePreviews: buildDirectorFramePreviews(frameEntries),
    quickActions: DIRECTOR_DASHBOARD_QUICK_ACTIONS,
    quizResults,
    isLoading,
    error,
    setTimeRange: setTimeRangeState,
  };
}
