import { type FormEvent, useEffect, useMemo, useRef, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import {
  fetchStudentScoreCard,
  searchAdministratorDashboard,
} from '../../api/session'
import type { AdministratorDashboardSearchResponse, StudentScoreCardRow } from '../../api/types'

const MAX_RESULTS = 50

function buildSuggestionValue(stu: Record<string, unknown>): string {
  const schoolId = String(stu.school_id ?? '').trim()
  const label = `${String(stu.firstname ?? '')} ${String(stu.lastname ?? '')}`.trim()
  return schoolId !== '' ? `${schoolId} - ${label}` : label
}

/** CI `admin/student_score_card.php` — search, datalist, status badges, score table. */
export function AdminStudentScoreCardPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const qParam = searchParams.get('q') ?? ''

  const [query, setQuery] = useState(qParam)
  const [suggestions, setSuggestions] = useState<Array<Record<string, unknown>>>([])
  const [results, setResults] = useState<Array<Record<string, unknown>>>([])
  const [selectedStudentId, setSelectedStudentId] = useState<number | null>(null)
  const [selectedStudent, setSelectedStudent] = useState<{
    firstname?: string | null
    lastname?: string | null
    school_id?: string | null
  } | null>(null)
  const [rows, setRows] = useState<StudentScoreCardRow[]>([])
  const [error, setError] = useState<string | null>(null)
  const lastAutoQuery = useRef('')

  const suggestionOptions = useMemo(() => {
    const seen = new Set<string>()
    const out: string[] = []
    for (const stu of suggestions) {
      const v = buildSuggestionValue(stu).trim()
      if (!v || seen.has(v)) continue
      seen.add(v)
      out.push(v)
    }
    return out
  }, [suggestions])

  useEffect(() => {
    setQuery(qParam)
  }, [qParam])

  useEffect(() => {
    ;(async () => {
      try {
        const data: AdministratorDashboardSearchResponse = await searchAdministratorDashboard('')
        setSuggestions(data.results?.students ?? [])
      } catch {
        setSuggestions([])
      }
    })()
  }, [])

  useEffect(() => {
    if (!qParam.trim()) return
    void runSearchQuery(qParam)
  }, [qParam])

  async function runSearchQuery(q: string) {
    const trimmed = q.trim()
    if (!trimmed) return
    try {
      const data: AdministratorDashboardSearchResponse = await searchAdministratorDashboard(trimmed)
      const list = data.results?.students ?? []
      setResults(list.slice(0, MAX_RESULTS))
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to search students.')
    }
  }

  async function runSearch(e?: FormEvent) {
    e?.preventDefault()
    const trimmed = query.trim()
    setSearchParams(trimmed ? { q: trimmed } : {})
    await runSearchQuery(trimmed)
  }

  async function openScoreCard(studentId: number) {
    try {
      const data = await fetchStudentScoreCard(studentId)
      setSelectedStudentId(studentId)
      setSelectedStudent(data.student)
      setRows(data.rows ?? [])
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to load student score card.')
    }
  }

  function tryAutoRun(currentValue: string) {
    const val = currentValue.trim()
    if (!val) return
    if (suggestionOptions.includes(val) && val !== lastAutoQuery.current) {
      lastAutoQuery.current = val
      void runSearchQuery(val)
      setSearchParams({ q: val })
    }
  }

  return (
    <div className="container-fluid py-4">
      <style>{`
        .admin-score-table { margin-top: 4px; }
        .admin-score-table thead th { position: static; }
      `}</style>
      <div className="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
        <div>
          <h2 className="mb-0">Student Score Card (Admin)</h2>
          <div className="text-muted small">Search for a student, then open their score card.</div>
        </div>
      </div>

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

      <div className="card shadow-sm mb-3">
        <div className="card-body">
          <form
            id="studentSearchForm"
            onSubmit={(e) => void runSearch(e)}
          >
            <div className="row g-2 justify-content-center">
              <div className="col-12 col-md-8 col-lg-6">
                <div className="input-group">
                  <span className="input-group-text">Search Student</span>
                  <input
                    id="globalStudentSearch"
                    className="form-control"
                    type="text"
                    name="q"
                    placeholder="Type School ID or Student Name"
                    list="studentSuggestions"
                    autoComplete="off"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    onInput={(e) => {
                      const v = (e.target as HTMLInputElement).value
                      window.setTimeout(() => tryAutoRun(v), 50)
                    }}
                  />
                  <button
                    id="globalStudentSearchClear"
                    className="btn btn-outline-secondary"
                    type="button"
                    title="Clear search"
                    onClick={() => {
                      setQuery('')
                      lastAutoQuery.current = ''
                      setSearchParams({})
                    }}
                  >
                    Clear
                  </button>
                </div>
                <small className="text-muted">Searches all grades.</small>
              </div>
            </div>
            <button type="submit" className="d-none">
              Search
            </button>
          </form>
        </div>
      </div>

      <datalist id="studentSuggestions">
        {suggestionOptions.map((v) => (
          <option key={v} value={v} />
        ))}
      </datalist>

      {query.trim() && results.length === 0 ? (
        <div className="alert alert-warning">No students found.</div>
      ) : null}

      {results.length > 0 ? (
        <div className="card shadow-sm">
          <div className="card-header d-flex justify-content-between align-items-center">
            <strong>Results</strong>
            <span className="text-muted small">Showing up to {MAX_RESULTS}</span>
          </div>
          <div className="card-body table-responsive pt-2">
            <table className="table table-striped table-hover align-middle admin-score-table no-mgmt-sticky" data-no-mgmt-sticky="1">
              <thead className="table-light">
                <tr>
                  <th>School ID</th>
                  <th>Student</th>
                  <th>Status</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                {results.map((s) => (
                  <tr key={String(s.id ?? '')}>
                    <td>{String(s.school_id ?? '')}</td>
                    <td>{`${String(s.firstname ?? '')} ${String(s.lastname ?? '')}`.trim()}</td>
                    <td>
                      {Number(s.is_active ?? 0) === 1 ? (
                        <span className="badge text-bg-success">Active</span>
                      ) : (
                        <span className="badge text-bg-secondary">Inactive</span>
                      )}
                    </td>
                    <td className="text-end">
                      <button
                        className="btn btn-sm btn-outline-primary"
                        type="button"
                        onClick={() => void openScoreCard(Number(s.id))}
                      >
                        Open Score Card
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}

      {selectedStudentId && selectedStudent ? (
        <div className="card shadow-sm mt-4">
          <div className="card-header">
            <strong>{`${selectedStudent.firstname ?? ''} ${selectedStudent.lastname ?? ''}`.trim()}</strong>
            <span className="text-muted ms-2">{selectedStudent.school_id ?? ''}</span>
          </div>
          <div className="card-body table-responsive">
            <table className="table table-bordered table-sm align-middle mb-0">
              <thead className="table-light">
                <tr>
                  <th>School Year</th>
                  <th>Semester</th>
                  <th>Class</th>
                  <th>Homework</th>
                  <th>Project</th>
                  <th>Participation</th>
                  <th>Quiz</th>
                  <th>Test</th>
                  <th>Attendance</th>
                  <th>PTAP</th>
                  <th>Midterm</th>
                  <th>Semester</th>
                  <th>Year Avg</th>
                </tr>
              </thead>
              <tbody>
                {rows.length === 0 ? (
                  <tr>
                    <td colSpan={13} className="text-muted">
                      No score rows found.
                    </td>
                  </tr>
                ) : (
                  rows.map((row, index) => (
                    <tr key={`${row.school_year}-${row.semester}-${index}`}>
                      <td>{row.school_year ?? '—'}</td>
                      <td>{row.semester ?? '—'}</td>
                      <td>{row.class_section_name ?? '—'}</td>
                      <td>{row.homework_avg ?? '—'}</td>
                      <td>{row.project_avg ?? '—'}</td>
                      <td>{row.participation_score ?? '—'}</td>
                      <td>{row.quiz_avg ?? '—'}</td>
                      <td>{row.test_avg ?? '—'}</td>
                      <td>{row.attendance_score ?? '—'}</td>
                      <td>{row.ptap_score ?? '—'}</td>
                      <td>{row.midterm_exam_score ?? '—'}</td>
                      <td>{row.semester_score ?? '—'}</td>
                      <td>{row.year_score ?? '—'}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}
    </div>
  )
}
