import { useCallback, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { CiAcademicFilter } from '../../components/CiPartials'
import { fetchStaffIndex, type StaffListRow } from '../../api/staff'

export function StaffIndexPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const [rows, setRows] = useState<StaffListRow[]>([])
  const [issuesCount, setIssuesCount] = useState(0)
  const [schoolYear, setSchoolYear] = useState<string | null>(null)
  const [schoolYears, setSchoolYears] = useState<string[]>([])
  const [semester, setSemester] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

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

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

  return (
    <div className="container-fluid mt-4">
      <h2 className="text-center mt-4 mb-3">Staff List</h2>
      <CiAcademicFilter
        schoolYears={schoolYears.length > 0 ? schoolYears : schoolYear ? [schoolYear] : []}
        selectedYear={searchParams.get('school_year') ?? schoolYear ?? undefined}
        selectedSemester={searchParams.get('semester') ?? semester ?? undefined}
        onApply={({ schoolYear: y, semester: sem }) => {
          const next = new URLSearchParams()
          if (y) next.set('school_year', y)
          if (sem) next.set('semester', sem)
          setSearchParams(next)
        }}
      />

      {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}`}>
                    Edit
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
