import { useCallback, useMemo } from 'react'

import type { CalendarDay, Employee, TimesheetStats, UseTimesheetStatsReturn } from '../types'

/**
 * Хук для вычисления статистики табеля учета времени
 */
export function useTimesheetStats(calendarData: CalendarDay[], employee?: Employee): UseTimesheetStatsReturn {
  const calculateStats = useCallback((data: CalendarDay[], emp: Employee): TimesheetStats => {
    const totalHours = data.reduce((sum, day) => sum + day.hours, 0)
    const totalOvertime = data.reduce((sum, day) => sum + day.overtime, 0)
    const workDays = data.filter(day => day.status === 'work' || day.status === 'remote' || day.status === 'business').length
    const weekendWorkDays = data.filter(day => {
      const dayOfWeek = new Date(2024, 0, day.day).getDay() // Примерная дата для определения дня недели
      const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
      return isWeekend && (day.status === 'work' || day.status === 'remote')
    }).length
    
    const completedTasks = data.reduce((sum, day) => sum + day.tasks, 0)
    const averageEfficiency = data
      .filter(day => day.efficiency !== null)
      .reduce((sum, day, _, arr) => sum + (day.efficiency || 0) / arr.length, 0)
    
    const averageHoursPerDay = workDays > 0 ? totalHours / workDays : 0

    return {
      totalHours: totalHours + totalOvertime,
      workDays,
      overtime: totalOvertime,
      efficiency: Math.round(averageEfficiency),
      completedTasks,
      projects: emp.projects,
      averageHoursPerDay: Math.round(averageHoursPerDay * 10) / 10,
      weekendWork: weekendWorkDays,
    }
  }, [])

  const stats = useMemo(() => {
    if (!employee || calendarData.length === 0) {
      return {
        totalHours: 0,
        workDays: 0,
        overtime: 0,
        efficiency: 0,
        completedTasks: 0,
        projects: 0,
        averageHoursPerDay: 0,
        weekendWork: 0,
      }
    }
    return calculateStats(calendarData, employee)
  }, [calendarData, employee, calculateStats])

  return {
    stats,
    calculateStats,
  }
}