// src/client/entities/employee/model/useMaidPeriods.ts
// Composable for managing employee maid periods with add/remove/end/reopen operations

import { ref, computed } from 'vue';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc.js';
import timezone from 'dayjs/plugin/timezone.js';

dayjs.extend(utc);
dayjs.extend(timezone);

export interface MaidPeriod {
  id?: string;
  startDate: string;
  endDate: string | null;
  _deleted?: boolean;
}

export function useMaidPeriods() {
  // State
  const maidPeriods = ref<MaidPeriod[]>([]);
  const deletedMaidPeriods = ref<MaidPeriod[]>([]);

  // Helper function to get maid period status
  const getMaidPeriodStatus = (period: MaidPeriod): string => {
    const today = dayjs().tz('Europe/Moscow').startOf('day').toDate();
    
    const startDate = dayjs(period.startDate).tz('Europe/Moscow').startOf('day').toDate();
    const endDate = period.endDate ? dayjs(period.endDate).tz('Europe/Moscow').startOf('day').toDate() : null;
    
    // "Запланирован" only if startDate > today
    if (startDate > today) {
      return 'Запланирован';
    }
    
    // "Активен" if startDate <= today AND (endDate == null OR endDate >= today)
    if (startDate <= today && (!endDate || endDate >= today)) {
      return 'Активен';
    }
    
    // Otherwise "Завершен"
    return 'Завершен';
  };

  // Helper function to add a new maid period
  const addMaidPeriod = (hireDate?: string) => {
    maidPeriods.value.push({
      startDate: hireDate || dayjs().tz('Europe/Moscow').format('YYYY-MM-DD'),
      endDate: null,
    });
  };

  // Helper function to mark a maid period as deleted (not actually deleted until save)
  const removeMaidPeriod = (index: number) => {
    const period = maidPeriods.value[index];
    if (period) {
      // Mark as deleted in the form
      period._deleted = true;
      // Also track in deletedMaidPeriods for backend
      deletedMaidPeriods.value.push({ ...period });
    }
  };

  // Helper function to undo deletion of a maid period
  const undoRemoveMaidPeriod = (index: number) => {
    const period = maidPeriods.value[index];
    if (period) {
      // Remove the _deleted flag
      delete period._deleted;
      // Remove from deletedMaidPeriods
      const deletedIndex = deletedMaidPeriods.value.findIndex(p => p.id === period.id);
      if (deletedIndex !== -1) {
        deletedMaidPeriods.value.splice(deletedIndex, 1);
      }
    }
  };

  // Helper function to edit a maid period (set end date)
  const endMaidPeriod = (index: number) => {
    const period = maidPeriods.value[index];
    if (period) {
      period.endDate = dayjs().tz('Europe/Moscow').format('YYYY-MM-DD');
    }
  };

  // Helper function to reopen a maid period (clear end date)
  const reopenMaidPeriod = (index: number) => {
    const period = maidPeriods.value[index];
    if (period) {
      period.endDate = null;
    }
  };

  // Computed property to check if maid periods section should be shown
  const showMaidPeriodsSection = computed(() => {
    // This will be used with formData.role, which is passed from parent
    return maidPeriods.value.length > 0;
  });

  // Computed property for dynamic section title
  const maidPeriodsSectionTitle = computed(() => {
    // This will be used with formData.role, which is passed from parent
    return 'Периоды работы (Горничная)';
  });

  // Computed property to disable save button based on validation
  const isSaveDisabled = computed(() => {
    // Validate maid periods don't overlap (exclude deleted periods)
    const activePeriods = maidPeriods.value.filter(p => !p._deleted);
    if (activePeriods.length > 1) {
      const today = dayjs().tz('Europe/Moscow').startOf('day').toDate();
      
      for (let i = 0; i < activePeriods.length; i++) {
        const p1 = activePeriods[i];
        const p1Start = dayjs(p1.startDate).tz('Europe/Moscow').startOf('day').toDate();
        const p1End = p1.endDate ? dayjs(p1.endDate).tz('Europe/Moscow').startOf('day').toDate() : dayjs('9999-12-31').toDate();
        
        for (let j = i + 1; j < activePeriods.length; j++) {
          const p2 = activePeriods[j];
          const p2Start = dayjs(p2.startDate).tz('Europe/Moscow').startOf('day').toDate();
          const p2End = p2.endDate ? dayjs(p2.endDate).tz('Europe/Moscow').startOf('day').toDate() : dayjs('9999-12-31').toDate();
          
          // Check for overlap: periods overlap if p1Start < p2End AND p2Start < p1End
          if (p1Start < p2End && p2Start < p1End) {
            return true;
          }
        }
      }
    }
    
    return false;
  });

  return {
    // State
    maidPeriods,
    deletedMaidPeriods,
    
    // Actions
    addMaidPeriod,
    removeMaidPeriod,
    undoRemoveMaidPeriod,
    endMaidPeriod,
    reopenMaidPeriod,
    
    // Helpers
    getMaidPeriodStatus,
    
    // Computed
    showMaidPeriodsSection,
    maidPeriodsSectionTitle,
    isSaveDisabled,
  };
}
