// src/client/shared/lib/scheduleHelpers.ts 
// Utility functions for schedule status mapping and display

import dayjs from 'dayjs';

/**
 * Normalizes backend status to standard format (handles case insensitivity)
 * @param status - Raw status from backend (e.g., 'work', 'Work', 'WORK')
 * @returns Normalized status ('Blank', 'Work', 'Holiday', 'Unavailable')
 */
export function normalizeStatus(status: string): 'Blank' | 'Work' | 'Holiday' | 'Unavailable' {
  if (!status) return 'Blank';
  
  const normalized = status.toLowerCase();
  switch (normalized) {
    case 'blank':
    case '':
    case 'null':
      return 'Blank';
    case 'work':
      return 'Work';
    case 'holiday':
      return 'Holiday';
    case 'unavailable':
      return 'Unavailable';
    default:
      if (status === 'Blank' || status === 'Work' || status === 'Holiday' || status === 'Unavailable') {
        return status;
      }
      return 'Blank';
  }
}

/**
 * Maps backend status to UI display symbol based on role
 * @param status - Raw status from backend
 * @param role - User role ('Manager' or 'Maid')
 * @returns Display symbol ('С', 'О', 'X', or empty string for Blank)
 */
export function mapBackendStatusToUi(status: string, role: string): string {
  const normalizedStatus = normalizeStatus(status);
  
  switch (normalizedStatus) {
    case 'Work':
      return 'С';
    case 'Holiday':
      return 'О';
    case 'Unavailable':
      return 'X';
    case 'Blank':
    default:
      return '';
  }
}

/**
 * Maps UI display symbol back to backend status
 * @param symbol - Display symbol ('С', 'О', 'X', or empty)
 * @param role - User role ('Manager' or 'Maid')
 * @returns Backend status ('Blank', 'Work', 'Holiday', 'Unavailable')
 */
export function mapUiSymbolToBackendStatus(symbol: string, role: string): 'Blank' | 'Work' | 'Holiday' | 'Unavailable' {
  if (!symbol || symbol === '') return 'Blank';
  
  switch (symbol) {
    case 'С':
    case 'C':
      return 'Work';
    case 'О':
    case 'O':
      return 'Holiday';
    case 'X':
    case 'x':
      return 'Unavailable';
    default:
      return 'Blank';
  }
}

export interface StatusOption {
  label: string;
  value: string;
  symbol: string;
}

export function getStatusOptions(role: string): StatusOption[] {
  return [
    { label: 'Пусто', value: 'Blank', symbol: '' },
    { label: 'Смена', value: 'Work', symbol: '(С)' },
    { label: 'Отпуск', value: 'Holiday', symbol: '(О)' },
    { label: 'Недоступен', value: 'Unavailable', symbol: '(X)' },
  ];
}

/**
 * Gets CSS class for status color
 * @param status - Backend status value
 * @param isApproved - Whether the shift is approved by admin (optional)
 * @returns Tailwind CSS class string
 */
export function getStatusColorClass(status: string, isApproved?: boolean): string {
  const normalizedStatus = normalizeStatus(status);

  // ИСПРАВЛЕНИЕ: Если смена НЕ согласована (isApproved равен false или undefined), 
  // и это не пустая ячейка — всегда показываем цвет "на согласовании".
  // Это касается и статуса "X", чтобы он не подсвечивался красным раньше времени.
  if (isApproved !== true && normalizedStatus !== 'Blank') {
    // #E9CDFF — новый цвет для всех несогласованных изменений (черновиков)
    return 'bg-[#E9CDFF] cursor-not-allowed';
  }

  // Если смена утверждена админом — используем насыщенные цвета
  if (isApproved === true) {
    switch (normalizedStatus) {
      case 'Work':
        return 'bg-green-600 text-white hover:bg-green-700';
      case 'Holiday':
        return 'bg-[#FFDE5C] text-white hover:bg-[#FFD440]';
      case 'Unavailable':
        return 'bg-red-600 text-white hover:bg-red-700';
      case 'Blank':
      default:
        return 'bg-gray-100 hover:bg-gray-200';
    }
  }

  // Стандартные цвета для пустых ячеек
  return 'bg-gray-100 hover:bg-gray-200';
}

/**
 * Helper function to check if a day is a weekend (Saturday or Sunday)
 * @param day - Day of the month (1-31)
 * @param year - Year
 * @param month - Month (1-12)
 * @returns true if the day is Saturday or Sunday
 */
export function isWeekend(day: number, year: number, month: number): boolean {
  const date = dayjs().year(year).month(month - 1).date(day);
  return date.day() === 0 || date.day() === 6; // 0 - Вс, 6 - Сб
}

/**
 * Helper function to get weekday name in Russian (abbreviated)
 * @param day - Day of the month (1-31)
 * @param year - Year
 * @param month - Month (1-12)
 * @returns Abbreviated weekday name in Russian ('вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб')
 */
export function getWeekdayName(day: number, year: number, month: number): string {
  const date = dayjs().year(year).month(month - 1).date(day);
  const names = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'];
  return names[date.day()];
}

/**
 * Helper function to check if a day is in the past
 * @param day - Day of the month (1-31)
 * @param year - Year
 * @param month - Month (1-12)
 * @param today - Current dayjs object
 * @returns true if the day is before today
 */
export function isPastDay(day: number, year: number, month: number, today: dayjs.Dayjs): boolean {
  const cellDate = dayjs().year(year).month(month - 1).date(day).startOf('day');
  return cellDate.isBefore(today, 'day');
}

/**
 * Check if a date is outside the 60-day editing window
 * @param day - Day of the month (1-31)
 * @param year - Year
 * @param month - Month (1-12)
 * @param today - Current dayjs object
 * @returns true if date is strictly after today + 60 days
 */
export function isOutOfRange(day: number, year: number, month: number, today: dayjs.Dayjs): boolean {
  // Создаем объект даты, строго привязанный к пропсам года и месяца
  const cellDate = dayjs()
    .year(year)
    .month(month - 1)
    .date(day)
    .startOf('day');
  
  // Calculate the 60-day limit
  const limitDate = today.add(60, 'day').endOf('day');
  
  // Return true if date is strictly after today + 60 days
  return cellDate.isAfter(limitDate);
}

/**
 * Check if a day is in the highlight zone [today, today + 60 days]
 * @param day - Day of the month (1-31)
 * @param year - Year
 * @param month - Month (1-12)
 * @param today - Current dayjs object
 * @returns true if the day is in the highlight zone
 */
export function isDayInHighlightZone(day: number, year: number, month: number, today: dayjs.Dayjs): boolean {
  // Создаем объект даты, строго привязанный к пропсам года и месяца
  const cellDate = dayjs()
    .year(year)
    .month(month - 1)
    .date(day)
    .startOf('day');
  
  const startDate = today.startOf('day');
  const endDate = today.add(60, 'day').endOf('day');
  
  return (cellDate.isSame(startDate) || cellDate.isAfter(startDate)) &&
         (cellDate.isSame(endDate) || cellDate.isBefore(endDate));
}