import { useId } from 'react'
import { useSchoolYear } from '../../context/SchoolYearContext'
import { isCurrentSchoolYear } from '../../lib/schoolYearSelection'
import { SchoolYearStatusBadge } from './SchoolYearStatusBadge'

export function SchoolYearSelector({ compact = false }: { compact?: boolean }) {
  const {
    schoolYears,
    selectedSchoolYear,
    isLoadingSchoolYears,
    schoolYearError,
    setSelectedSchoolYearName,
  } = useSchoolYear()
  const selectId = useId()

  if (schoolYears.length === 0 && !isLoadingSchoolYears) {
    return schoolYearError ? (
      <span className="badge text-bg-warning" title={schoolYearError}>
        School years unavailable
      </span>
    ) : null
  }

  return (
    <div className={`school-year-selector d-flex align-items-center gap-2 ${compact ? 'school-year-selector--compact' : ''}`}>
      <label className="form-label mb-0 small text-nowrap" htmlFor={selectId}>
        School Year
      </label>
      <select
        id={selectId}
        className="form-select form-select-sm"
        value={selectedSchoolYear?.name ?? ''}
        disabled={isLoadingSchoolYears || schoolYears.length === 0}
        onChange={(event) => {
          setSelectedSchoolYearName(event.target.value || null)
        }}
      >
        {isLoadingSchoolYears && schoolYears.length === 0 ? (
          <option value="">Loading…</option>
        ) : null}
        {schoolYears.map((year) => (
          <option key={year.name} value={year.name}>
            {year.name}
            {isCurrentSchoolYear(year) ? ' Current' : ''}
            {year.status && !isCurrentSchoolYear(year) ? ` ${year.status}` : ''}
          </option>
        ))}
      </select>
      {selectedSchoolYear ? <SchoolYearStatusBadge status={selectedSchoolYear.status} /> : null}
    </div>
  )
}
