import { type FormEvent, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import {
  displayNameOf,
  fetchBadgeScanLogs,
  type BadgeScanLogRow,
} from '../../api/badgeScan'
import { useSchoolYearOptions } from '../../hooks/useSchoolYearOptions'

function formatDateTime(raw: string | null): string {
  if (!raw) return '—'
  const d = new Date(raw)
  if (isNaN(d.getTime())) return raw
  return d.toLocaleString(undefined, {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function userType(row: BadgeScanLogRow): string {
  const hasStu = Boolean(row.student_firstname || row.student_lastname)
  const hasUser = Boolean(row.user_firstname || row.user_lastname)
  if (hasStu && !hasUser) return 'Student'
  if (hasUser) return 'Staff / User'
  return '—'
}

export function BadgeScanLogsPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? ''
  const semester = searchParams.get('semester') ?? ''

  const [logs, setLogs] = useState<BadgeScanLogRow[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [q, setQ] = useState('')

  function load() {
    let cancelled = false
    setLoading(true)
    setError(null)
    fetchBadgeScanLogs()
      .then((res) => { if (!cancelled) setLogs(res.logs) })
      .catch((e) => { if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load.') })
      .finally(() => { if (!cancelled) setLoading(false) })
    return () => { cancelled = true }
  }

  useEffect(load, [])

  function applyFilter(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const p = new URLSearchParams()
    const sy = String(fd.get('school_year') ?? '').trim()
    const sem = String(fd.get('semester') ?? '').trim()
    if (sy) p.set('school_year', sy)
    if (sem) p.set('semester', sem)
    setSearchParams(p, { replace: true })
  }

  const filtered = useMemo(() => {
    let rows = logs
    if (schoolYear) rows = rows.filter((r) => r.school_year === schoolYear)
    if (semester) rows = rows.filter((r) => r.semester === semester)
    if (q.trim()) {
      const lq = q.toLowerCase()
      rows = rows.filter(
        (r) =>
          displayNameOf(r).toLowerCase().includes(lq) ||
          r.card_id.toLowerCase().includes(lq),
      )
    }
    return rows
  }, [logs, schoolYear, semester, q])

  const schoolYears = useMemo(
    () => [...new Set(logs.map((r) => r.school_year).filter(Boolean))].sort().reverse() as string[],
    [logs],
  )
  const { options } = useSchoolYearOptions({
    legacyYears: schoolYears,
    preferredYear: schoolYear,
  })

  return (
    <div className="container-fluid px-0">
      <h2 className="text-center mt-4 mb-1">Badge Scan Log</h2>
      <p className="text-center text-muted small mb-3">
        All badge scans for administrators, staff, teachers, and students.
      </p>

      <div className="d-flex justify-content-center mb-3">
        <form className="row g-2 align-items-end" onSubmit={applyFilter}>
          <div className="col-auto">
            <label htmlFor="bsl-school-year" className="form-label small mb-0">School Year</label>
            <select id="bsl-school-year" name="school_year" className="form-select form-select-sm" defaultValue={schoolYear}>
              <option value="">— All —</option>
              {options.map((option) => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
          </div>
          <div className="col-auto">
            <label htmlFor="bsl-semester" className="form-label small mb-0">Semester</label>
            <select id="bsl-semester" name="semester" className="form-select form-select-sm" defaultValue={semester}>
              <option value="">— All —</option>
              <option value="Fall">Fall</option>
              <option value="Spring">Spring</option>
            </select>
          </div>
          <div className="col-auto">
            <button type="submit" className="btn btn-sm btn-secondary">Apply</button>
          </div>
          <div className="col-auto">
            <button type="button" className="btn btn-sm btn-outline-secondary" onClick={load} disabled={loading}>
              {loading ? 'Loading…' : 'Refresh'}
            </button>
          </div>
        </form>
      </div>

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

      <div className="px-3">
        <div className="card border-0 shadow-sm rounded-3">
          <div className="card-body p-0">
            <div className="d-flex align-items-center justify-content-between px-3 pt-3 pb-2 gap-2 flex-wrap">
              <span className="text-muted small">
                {loading ? 'Loading…' : `${filtered.length} scan${filtered.length !== 1 ? 's' : ''}`}
              </span>
              <input
                id="bsl-quick-filter"
                name="q"
                type="search"
                className="form-control form-control-sm"
                style={{ maxWidth: 220 }}
                placeholder="Filter by name or card ID…"
                value={q}
                onChange={(e) => setQ(e.target.value)}
              />
            </div>
            <div className="table-responsive">
              <table className="table table-sm table-hover mb-0">
                <thead className="table-light">
                  <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Card ID</th>
                    <th>Scan Time</th>
                    <th>School Year</th>
                    <th>Semester</th>
                  </tr>
                </thead>
                <tbody>
                  {loading ? (
                    <tr>
                      <td colSpan={7} className="text-center text-muted py-4">Loading…</td>
                    </tr>
                  ) : filtered.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="text-center text-muted py-4">No scans found.</td>
                    </tr>
                  ) : (
                    filtered.map((row, idx) => (
                      <tr key={`${row.id}-${idx}`}>
                        <td className="text-muted small">{row.id}</td>
                        <td>{displayNameOf(row)}</td>
                        <td>
                          <span className={`badge ${userType(row) === 'Student' ? 'bg-info text-dark' : 'bg-secondary'}`}>
                            {userType(row)}
                          </span>
                        </td>
                        <td><code className="small">{row.card_id}</code></td>
                        <td className="small">{formatDateTime(row.scan_time)}</td>
                        <td className="small">{row.school_year ?? '—'}</td>
                        <td className="small">{row.semester ?? '—'}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
