import {
  attendancePastPresentStatuses,
  attendancePresentStatuses,
} from './helpers';

export type IndividualSummaryBucket =
  | 'present'
  | 'late'
  | 'half_day'
  | 'leave'
  | 'absent'
  | 'skip';

const IN_PROGRESS_STATUSES = ['check_in', 'on_break'] as const;
const SKIP_STATUSES = ['weekend', 'holiday'] as const;

export function isAttendanceToday(
  date: Date | string,
  todayStartUtc: Date,
  todayEndUtc: Date,
): boolean {
  const attendanceDate = new Date(date);
  return attendanceDate >= todayStartUtc && attendanceDate <= todayEndUtc;
}

export function isGroupedPresent(status: string, isToday: boolean): boolean {
  if (isToday) {
    return attendancePresentStatuses.includes(status as any);
  }

  return attendancePastPresentStatuses.includes(status as any);
}

export function classifyIndividualSummaryBucket(
  status: string,
  isToday: boolean,
): IndividualSummaryBucket {
  if (SKIP_STATUSES.includes(status as any)) {
    return 'skip';
  }

  if (status === 'on_leave') {
    return 'leave';
  }

  if (status === 'absent') {
    return 'absent';
  }

  if (status === 'late') {
    return 'late';
  }

  if (status === 'half_day') {
    return 'half_day';
  }

  if (status === 'present' || status === 'remote') {
    return 'present';
  }

  if (IN_PROGRESS_STATUSES.includes(status as any)) {
    return isToday ? 'present' : 'absent';
  }

  return 'skip';
}

export function isGroupedAbsent(status: string, isToday: boolean): boolean {
  if (status === 'absent') {
    return true;
  }

  if (!isToday && IN_PROGRESS_STATUSES.includes(status as any)) {
    return true;
  }

  return false;
}

export type MemberMonthSummaryField =
  | 'total_present'
  | 'total_late'
  | 'total_absent'
  | 'total_leave'
  | 'skip';

/**
 * Own-attendance month cards: Present, Late, Absent, Leave (no half_day card).
 * - Today: check_in / on_break → present
 * - Past: present / remote / half_day → present; late → late
 * Invariant with dashboard: total_present + total_late === countGroupedPresentRecords(...)
 */
export function classifyMemberMonthSummaryField(
  status: string,
  isToday: boolean,
): MemberMonthSummaryField {
  if (SKIP_STATUSES.includes(status as any)) {
    return 'skip';
  }

  if (status === 'on_leave') {
    return 'total_leave';
  }

  if (status === 'absent') {
    return 'total_absent';
  }

  if (status === 'late') {
    return 'total_late';
  }

  if (
    status === 'present' ||
    status === 'remote' ||
    status === 'half_day'
  ) {
    return 'total_present';
  }

  if (IN_PROGRESS_STATUSES.includes(status as any)) {
    return isToday ? 'total_present' : 'total_absent';
  }

  return 'skip';
}

export function countGroupedPresentRecords(
  records: { status: string; date: Date | string }[],
  todayStartUtc: Date,
  todayEndUtc: Date,
): number {
  return records.filter((record) =>
    isGroupedPresent(
      record.status,
      isAttendanceToday(record.date, todayStartUtc, todayEndUtc),
    ),
  ).length;
}
