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 { usePolicyAcknowledgmentReport } from '@/business/policies/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';
import { useAuth } from '@/shared/app/useAuth';
import { getLeadershipDashboardName } from '@/business/app-shell/selectors';
import { getActiveTenant } from '@/business/scope/selectors';
import { DEFAULT_PRODUCT_ROLE } from '@/shared/constants/roles';

export function useDirectorDashboardPage(): DirectorDashboardPage {
  const { user, profile } = useAuth();
  const role = profile?.role ?? DEFAULT_PRODUCT_ROLE;
  const title = getLeadershipDashboardName(role);
  const scopeLabel = getActiveTenant(user)?.name ?? '';
  const [timeRange, setTimeRangeState] = useState<DirectorDashboardTimeRange>('month');
  const frameEntriesQuery = useFrameEntries();
  const quizResultsQuery = useSafetyQuizResults();
  const staffAttendanceRecordsQuery = useStaffAttendanceRecords();
  const staffAttendanceSummaryQuery = useStaffAttendanceSummary();
  const acknowledgmentReportQuery = usePolicyAcknowledgmentReport();
  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
    || acknowledgmentReportQuery.isLoading;
  const error = frameEntriesQuery.error
    ?? quizResultsQuery.error
    ?? staffAttendanceRecordsQuery.error
    ?? staffAttendanceSummaryQuery.error
    ?? acknowledgmentReportQuery.error;

  return {
    title,
    scopeLabel,
    timeRange,
    overviewCards: buildDirectorOverviewCards(
      attendanceRecords,
      quizResults,
      frameEntries,
      staffCount,
      acknowledgmentReportQuery.data?.summary,
    ),
    riskAreas: buildDirectorRiskAreas(attendanceRecords, quizResults, staffCount),
    framePreviews: buildDirectorFramePreviews(frameEntries),
    quickActions: DIRECTOR_DASHBOARD_QUICK_ACTIONS,
    quizResults,
    isLoading,
    error,
    setTimeRange: setTimeRangeState,
  };
}
