import { type FormEvent, useEffect, useState } from 'react'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { useSchoolYearOptions } from '../../hooks/useSchoolYearOptions'

export function AcademicFilterBar({ schoolYears }: { schoolYears?: string[] }) {
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  const { pathname } = useLocation()
  const schoolYear = searchParams.get('school_year') ?? ''
  const semester = searchParams.get('semester') ?? ''
  const { options, selectedYear } = useSchoolYearOptions({
    legacyYears: schoolYears,
    preferredYear: schoolYear,
  })
  const [yearValue, setYearValue] = useState(schoolYear || selectedYear)
  const [semesterValue, setSemesterValue] = useState(semester)

  useEffect(() => {
    setYearValue(schoolYear || selectedYear)
  }, [schoolYear, selectedYear])

  useEffect(() => {
    setSemesterValue(semester)
  }, [semester])

  function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const next = new URLSearchParams()
    if (yearValue) next.set('school_year', yearValue)
    if (semesterValue) next.set('semester', semesterValue)
    navigate({ pathname, search: next.toString() ? `?${next}` : '' })
  }

  return (
    <form
      onSubmit={onSubmit}
      className="row g-2 align-items-center justify-content-center mb-3"
    >
      <div className="col-auto">
        <label className="form-label mb-0">School year</label>
      </div>
      <div className="col-auto">
        <select
          name="school_year"
          className="form-select form-select-sm"
          style={{ minWidth: 180 }}
          value={yearValue}
          onChange={(event) => setYearValue(event.target.value)}
        >
          {options.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </div>
      <div className="col-auto">
        <label className="form-label mb-0">Semester</label>
      </div>
      <div className="col-auto">
        <select
          name="semester"
          className="form-select form-select-sm"
          style={{ minWidth: 140 }}
          value={semesterValue}
          onChange={(event) => setSemesterValue(event.target.value)}
        >
          <option value="">—</option>
          <option value="Fall">Fall</option>
          <option value="Spring">Spring</option>
        </select>
      </div>
      <div className="col-auto">
        <button type="submit" className="btn btn-secondary btn-sm">
          Apply
        </button>
        <button
          type="button"
          className="btn btn-outline-secondary btn-sm ms-1"
          onClick={() => {
            setYearValue(selectedYear)
            setSemesterValue('')
            navigate({ pathname, search: '' })
          }}
        >
          Reset
        </button>
      </div>
    </form>
  )
}
