import { useCallback, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { fetchStaffIndex, type StaffListRow } from '../../api/staff'
import { ReadOnlyBanner, SchoolYearSelector } from '../../components/schoolYear'
import { useSchoolYear } from '../../context/SchoolYearContext'

export function StaffIndexPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const { selectedSchoolYearName, isReadOnlyYear } = useSchoolYear()
  const [rows, setRows] = useState<StaffListRow[]>([])
  const [issuesCount, setIssuesCount] = useState(0)
  const [schoolYear, setSchoolYear] = useState<string | null>(null)
  const [semester, setSemester] = useState<string | null>(null)
  const [search, setSearch] = useState(searchParams.get('search') ?? '')
  const [status, setStatus] = useState(searchParams.get('status') ?? '')
  const [role, setRole] = useState(searchParams.get('role') ?? '')
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(async () => {
    const sy = selectedSchoolYearName ?? searchParams.get('school_year') ?? undefined
    try {
      const sem = searchParams.get('semester') ?? undefined
      const data = await fetchStaffIndex({
        school_year: sy,
        semester: sem,
        search: searchParams.get('search') ?? undefined,
        status: searchParams.get('status') ?? undefined,
        role: searchParams.get('role') ?? undefined,
      })
      setRows(data.staff ?? [])
      setIssuesCount(Number(data.issues_count ?? 0))
      setSchoolYear(data.school_year ?? null)
      setSemester(data.semester ?? null)
      setError(null)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Unable to load staff.')
    }
  }, [searchParams, selectedSchoolYearName])

  useEffect(() => {
    if (!selectedSchoolYearName) return
    setSearchParams((current) => {
      const next = new URLSearchParams(current)
      next.delete('school_year_id')
      next.delete('year')
      next.set('school_year', selectedSchoolYearName)
      return next.toString() === current.toString() ? current : next
    }, { replace: true })
  }, [selectedSchoolYearName, setSearchParams])

  useEffect(() => {
    void load()
  }, [load])

  function applyFilters() {
    const next = new URLSearchParams()
    if (selectedSchoolYearName) next.set('school_year', selectedSchoolYearName)
    if (semester) next.set('semester', semester)
    if (search.trim()) next.set('search', search.trim())
    if (status) next.set('status', status)
    if (role) next.set('role', role)
    setSearchParams(next)
  }

  const selectedYear = selectedSchoolYearName ?? schoolYear ?? ''
  const selectedQuery = selectedYear ? `?school_year=${encodeURIComponent(selectedYear)}` : ''

  return (
    <div className="container-fluid mt-4">
      <div className="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
        <div>
          <h2 className="mb-1">Staff List</h2>
          <div className="text-muted small">School year: {selectedYear || '—'}</div>
        </div>
        <div className="d-flex flex-wrap gap-2 align-items-center">
          <SchoolYearSelector compact />
          {!isReadOnlyYear ? (
            <Link className="btn btn-primary btn-sm" to={`/app/staff/create${selectedQuery}`}>Add Staff</Link>
          ) : null}
        </div>
      </div>

      <ReadOnlyBanner />

      <div className="row g-2 align-items-end mb-3">
        <div className="col-md-4">
          <label className="form-label">Search</label>
          <input className="form-control" value={search} onChange={(event) => setSearch(event.target.value)} />
        </div>
        <div className="col-md-2">
          <label className="form-label">Semester</label>
          <input className="form-control" value={semester ?? ''} onChange={(event) => setSemester(event.target.value)} placeholder="Fall" />
        </div>
        <div className="col-md-2">
          <label className="form-label">Role</label>
          <input className="form-control" value={role} onChange={(event) => setRole(event.target.value)} />
        </div>
        <div className="col-md-2">
          <label className="form-label">Status</label>
          <select className="form-select" value={status} onChange={(event) => setStatus(event.target.value)}>
            <option value="">Any</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
          </select>
        </div>
        <div className="col-md-2">
          <button className="btn btn-outline-primary w-100" type="button" onClick={applyFilters}>Apply</button>
        </div>
      </div>

      {issuesCount > 0 ? (
        <div className="alert alert-warning" role="alert">
          {issuesCount} teacher/assistant {issuesCount === 1 ? 'has' : 'have'} no class assignment for{' '}
          {schoolYear ?? 'the selected school year'}.
        </div>
      ) : null}

      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="table-responsive">
        <table className="table table-striped table-bordered table-hover w-100" style={{ width: '100%' }}>
          <thead>
            <tr>
              <th>#</th>
              <th>School ID</th>
              <th>First Name</th>
              <th>Last Name</th>
              <th>School Email</th>
              <th>Phone</th>
              <th>Position</th>
              <th>Class-Section</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((s, i) => (
              <tr key={s.id} className={s.verification_issue ? 'table-warning' : undefined}>
                <td style={{ textAlign: 'center' }}>{i + 1}</td>
                <td>{s.school_id ?? ''}</td>
                <td>{s.firstname ?? ''}</td>
                <td>{s.lastname ?? ''}</td>
                <td>{s.email ?? ''}</td>
                <td>{s.phone ?? ''}</td>
                <td>{s.active_role ?? ''}</td>
                <td>{s.class_section ?? ''}</td>
                <td>
                  <Link className="btn btn-sm btn-warning" to={`/app/staff/edit/${s.id}${selectedQuery}`}>
                    Edit
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
