import {
  DIRECTOR_DASHBOARD_COMPLETION_TREND_THRESHOLD,
  DIRECTOR_DASHBOARD_FRAME_PREVIEW_LIMIT,
  DIRECTOR_DASHBOARD_HIGH_ABSENCE_THRESHOLD,
  DIRECTOR_DASHBOARD_HIGH_INCOMPLETE_STAFF_THRESHOLD,
  DIRECTOR_DASHBOARD_TEXT_PREVIEW_LENGTH,
} from '@/shared/constants/directorDashboard';
import {
  countStaffAttendanceStatus,
  staffAttendanceRate,
} from '@/business/staff-attendance/selectors';
import type { FrameEntryViewModel } from '@/business/frame/types';
import type { StaffAttendanceRecordViewModel } from '@/business/staff-attendance/types';
import type { SafetyQuizResultDto } from '@/shared/types/safetyQuiz';
import type {
  DirectorFramePreview,
  DirectorOverviewCard,
  DirectorRiskArea,
} from '@/business/director-dashboard/types';

export function calculateQuizCompletionRate(
  quizResults: readonly SafetyQuizResultDto[],
  staffCount: number,
): number {
  if (staffCount <= 0) {
    return 0;
  }

  return Math.round((quizResults.length / staffCount) * 100);
}

export function buildDirectorOverviewCards(
  attendanceRecords: readonly StaffAttendanceRecordViewModel[],
  quizResults: readonly SafetyQuizResultDto[],
  frameEntries: readonly FrameEntryViewModel[],
  staffCount: number,
): readonly DirectorOverviewCard[] {
  const attendanceRate = staffAttendanceRate(attendanceRecords);
  const quizCompletionRate = calculateQuizCompletionRate(quizResults, staffCount);

  return [
    {
      label: 'Staff Attendance',
      value: `${attendanceRate}%`,
      change: `${attendanceRecords.length} records`,
      trend: 'up',
      iconId: 'clock',
      tone: 'orange',
      module: 'attendance',
    },
    {
      label: 'De-escalation Completion',
      value: `${quizResults.length}/${staffCount}`,
      change: `${quizCompletionRate}%`,
      trend: quizCompletionRate > DIRECTOR_DASHBOARD_COMPLETION_TREND_THRESHOLD ? 'up' : 'down',
      iconId: 'shield',
      tone: 'blue',
      module: 'qbs',
    },
    {
      label: 'F.R.A.M.E. Entries',
      value: frameEntries.length.toString(),
      change: 'Total entries',
      trend: 'up',
      iconId: 'eye',
      tone: 'amber',
      module: 'frame',
    },
    {
      label: 'Staff Members',
      value: staffCount.toString(),
      change: 'Active',
      trend: 'up',
      iconId: 'users',
      tone: 'purple',
      module: 'attendance',
    },
  ];
}

export function buildDirectorRiskAreas(
  attendanceRecords: readonly StaffAttendanceRecordViewModel[],
  quizResults: readonly SafetyQuizResultDto[],
  staffCount: number,
): readonly DirectorRiskArea[] {
  const incompleteStaffCount = Math.max(staffCount - quizResults.length, 0);
  const absenceCount = countStaffAttendanceStatus(attendanceRecords, 'absent');

  return [
    {
      issue: `${incompleteStaffCount} staff haven't completed de-escalation quiz`,
      severity: incompleteStaffCount > DIRECTOR_DASHBOARD_HIGH_INCOMPLETE_STAFF_THRESHOLD ? 'high' : 'medium',
      module: 'qbs',
    },
    {
      issue: `${absenceCount} absences recorded this period`,
      severity: absenceCount > DIRECTOR_DASHBOARD_HIGH_ABSENCE_THRESHOLD ? 'high' : 'low',
      module: 'attendance',
    },
  ];
}

export function buildDirectorFramePreviews(
  frameEntries: readonly FrameEntryViewModel[],
): readonly DirectorFramePreview[] {
  return frameEntries.slice(0, DIRECTOR_DASHBOARD_FRAME_PREVIEW_LIMIT).map((entry) => ({
    id: entry.id,
    week: entry.weekOf,
    sections: [
      { letter: 'F', text: truncatePreview(entry.formal) },
      { letter: 'R', text: truncatePreview(entry.recognition) },
      { letter: 'A', text: truncatePreview(entry.application) },
      { letter: 'M', text: truncatePreview(entry.management) },
      { letter: 'E', text: truncatePreview(entry.emotional) },
    ],
  }));
}

function truncatePreview(value: string): string {
  if (value.length <= DIRECTOR_DASHBOARD_TEXT_PREVIEW_LENGTH) {
    return value;
  }

  return `${value.slice(0, DIRECTOR_DASHBOARD_TEXT_PREVIEW_LENGTH)}...`;
}
