import type { Ref } from 'vue'
import type { ContractPhase } from '~/services/dto/contract-phase'
import type { EmployeeRttSummary } from '~/services/dto/employee-rtt-summary'
import type { Employee } from '~/services/dto/employee'
import { getEmployeeRttSummary, createRttPayment } from '~/services/employee-rtt-summary'

export type RttYearOption = {
  value: number
  label: string
}

export const useEmployeeRtt = (
  employee: Ref<Employee | null>,
  reloadEmployee: () => Promise<void>,
  selectedPhase: Ref<ContractPhase | null>,
) => {
  const rttSummary = ref<EmployeeRttSummary | null>(null)
  const isRttLoading = ref(false)
  const rttDataLoaded = ref(false)
  const selectedRttYear = ref<number | null>(null)

  // Exercice RTT : Juin (Y-1) → Mai (Y). Toujours, peu importe le type de contrat
  // (l'onglet RTT est masqué pour les FORFAIT côté page).
  const computeRttYearForDate = (date: Date): number =>
    date.getMonth() >= 5 ? date.getFullYear() + 1 : date.getFullYear()

  const currentRttYear = computed<number | null>(() => {
    if (!employee.value) return null
    return computeRttYearForDate(new Date())
  })

  const availableRttYears = computed<RttYearOption[]>(() => {
    if (!employee.value || !selectedPhase.value || currentRttYear.value === null) return []
    const phase = selectedPhase.value

    // Plage = exercices intersectant la phase.
    const phaseStartYear = computeRttYearForDate(new Date(`${phase.startDate}T00:00:00`))
    // Borne haute : fin de phase si clôturée ; sinon l'exercice courant.
    // Contrairement à l'onglet Congés, on NE propose PAS l'exercice suivant en RTT :
    // consulter un exercice RTT à venir (heures non saisies, rien à payer) n'a pas de sens.
    const maxYear = phase.endDate
      ? computeRttYearForDate(new Date(`${phase.endDate}T00:00:00`))
      : currentRttYear.value

    // Hard floor : rttStartDate (env RTT_START_DATE) — pas d'historique avant.
    let dataFloor: number | null = null
    const dataStart = rttSummary.value?.rttStartDate
    if (dataStart) {
      const dataStartDate = new Date(`${dataStart.substring(0, 10)}T00:00:00`)
      if (!Number.isNaN(dataStartDate.getTime())) {
        dataFloor = computeRttYearForDate(dataStartDate)
      }
    }

    const minYear = dataFloor !== null ? Math.max(phaseStartYear, dataFloor) : phaseStartYear

    const years: RttYearOption[] = []
    for (let y = maxYear; y >= minYear; y -= 1) {
      years.push({ value: y, label: `Juin ${y - 1} → Mai ${y}` })
    }
    return years
  })

  const initSelectedRttYear = () => {
    if (selectedRttYear.value !== null) return
    if (currentRttYear.value !== null) {
      selectedRttYear.value = currentRttYear.value
    }
  }

  const loadRttData = async () => {
    if (!employee.value || isRttLoading.value) return
    initSelectedRttYear()
    if (selectedRttYear.value === null) return
    isRttLoading.value = true
    try {
      rttSummary.value = await getEmployeeRttSummary(
        employee.value.id,
        selectedRttYear.value,
        selectedPhase.value?.id,
      )
      rttDataLoaded.value = true
    } finally {
      isRttLoading.value = false
    }
  }

  const setSelectedRttYear = async (year: number) => {
    if (selectedRttYear.value === year) return
    selectedRttYear.value = year
    rttDataLoaded.value = false
    await loadRttData()
  }

  const resetLoaded = () => {
    rttDataLoaded.value = false
    selectedRttYear.value = null
  }

  watch(() => selectedPhase.value?.id, (newId, oldId) => {
    // Ignore la résolution initiale (undefined → phase courante au montage) :
    // l'initialisation de l'année est pilotée par loadRttData. Même convention que
    // le watch de useEmployeeDetailPage (évite un reset concurrent du sélecteur).
    if (oldId === undefined || newId === oldId) return
    // Changement de phase réel : reset l'année car la plage a peut-être changé.
    selectedRttYear.value = null
    rttDataLoaded.value = false
    // Le rechargement effectif est piloté par useEmployeeDetailPage.
  })

  const submitRttPayment = async (month: number, base25Minutes: number, bonus25Minutes: number, base50Minutes: number, bonus50Minutes: number) => {
    if (!employee.value) return
    const year = rttSummary.value?.year ?? undefined
    await createRttPayment(employee.value.id, month, base25Minutes, bonus25Minutes, base50Minutes, bonus50Minutes, year)
    await reloadEmployee()
  }

  return {
    rttSummary,
    isRttLoading,
    rttDataLoaded,
    selectedRttYear,
    currentRttYear,
    availableRttYears,
    setSelectedRttYear,
    loadRttData,
    resetLoaded,
    submitRttPayment
  }
}
