import type { Ref } from 'vue'
import type { Employee } from '~/services/dto/employee'
import type { ContractPhase } from '~/services/dto/contract-phase'
import { CONTRACT_TYPES } from '~/services/dto/contract'

const formatDateFr = (iso: string | null): string => {
  if (!iso) return ''
  const [y, m, d] = iso.split('-')
  return `${d}/${m}/${y}`
}

const formatContractTypeLabel = (phase: ContractPhase): string => {
  switch (phase.contractType) {
    case CONTRACT_TYPES.FORFAIT:
      return 'FORFAIT'
    case CONTRACT_TYPES.H35:
      return '35h'
    case CONTRACT_TYPES.H39:
      return '39h'
    case CONTRACT_TYPES.INTERIM:
      return 'Intérim'
    case CONTRACT_TYPES.CUSTOM:
      return `CUSTOM (${phase.weeklyHours ?? '?'}h)`
    default:
      return String(phase.contractType)
  }
}

export const formatPhaseLabel = (phase: ContractPhase): string => {
  const base = formatContractTypeLabel(phase)
  const driver = phase.isDriver ? ' (driver)' : ''
  const dates = phase.endDate
    ? `${formatDateFr(phase.startDate)} → ${formatDateFr(phase.endDate)}`
    : `depuis ${formatDateFr(phase.startDate)}`
  const suffix = phase.isCurrent ? ' (actuel)' : ''
  return `${base}${driver} — ${dates}${suffix}`
}

export const useEmployeeContractPhase = (employee: Ref<Employee | null>) => {
  const selectedPhaseId = ref<number | null>(null)

  const availablePhases = computed<ContractPhase[]>(() => employee.value?.contractPhases ?? [])

  const currentPhase = computed<ContractPhase | null>(() => {
    return availablePhases.value.find((p) => p.isCurrent) ?? availablePhases.value[0] ?? null
  })

  const selectedPhase = computed<ContractPhase | null>(() => {
    if (selectedPhaseId.value === null) return currentPhase.value
    return availablePhases.value.find((p) => p.id === selectedPhaseId.value) ?? currentPhase.value
  })

  const isViewingPastPhase = computed<boolean>(() => {
    if (!selectedPhase.value || !currentPhase.value) return false
    return selectedPhase.value.id !== currentPhase.value.id
  })

  const phaseOptions = computed(() =>
    availablePhases.value.map((p) => ({ value: p.id, label: formatPhaseLabel(p) }))
  )

  const showPicker = computed(() => availablePhases.value.length > 1)

  const setSelectedPhase = (phaseId: number) => {
    selectedPhaseId.value = phaseId
  }

  const resetToCurrent = () => {
    selectedPhaseId.value = null
  }

  return {
    selectedPhaseId,
    selectedPhase,
    currentPhase,
    availablePhases,
    phaseOptions,
    showPicker,
    isViewingPastPhase,
    setSelectedPhase,
    resetToCurrent,
  }
}
