import { useCallback, useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { CiAcademicFilter } from '../../components/CiPartials'
import { fetchLoginActivity, type LoginActivityRow } from '../../api/session'

function formatDt(value?: string | null): string {
  if (!value) return '—'
  const date = new Date(String(value).replace(' ', 'T'))
  if (Number.isNaN(date.valueOf())) return value
  const pad = (n: number) => String(n).padStart(2, '0')
  const datePart = `${pad(date.getMonth() + 1)}-${pad(date.getDate())}-${date.getFullYear()}`
  const hasTime = /[T ]\d{2}:\d{2}/.test(String(value))
  if (!hasTime) return datePart
  return `${datePart} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

/** CI `user/login_activity.php` — paginated JSON from administrator API. */
export function LoginActivityPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const [rows, setRows] = useState<LoginActivityRow[]>([])
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [pageCount, setPageCount] = useState(1)
  const [perPage, setPerPage] = useState(25)

  const load = useCallback(async () => {
    try {
      const data = await fetchLoginActivity({
        page,
        per_page: perPage,
        school_year: searchParams.get('school_year') ?? undefined,
        semester: searchParams.get('semester') ?? undefined,
      })
      setRows(data.activities ?? [])
      const p = data.pagination
      if (p?.currentPage) setPage(p.currentPage)
      if (p?.pageCount) setPageCount(p.pageCount)
      setError(null)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Unable to load login activity.')
    }
  }, [page, perPage, searchParams])

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

  return (
    <div className="container-fluid py-3">
      <h2 className="text-center mt-4 mb-3">Login Activity</h2>
      <CiAcademicFilter
        onApply={({ schoolYear, semester }) => {
          const next = new URLSearchParams()
          if (schoolYear) next.set('school_year', schoolYear)
          if (semester) next.set('semester', semester)
          setSearchParams(next)
          setPage(1)
        }}
      />

      {error ? (
        <div id="loginActivityAlert" className="alert alert-danger" role="alert">
          {error}
        </div>
      ) : null}

      <div className="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-3">
        <div>
          <label htmlFor="perPageSelect" className="form-label mb-0 me-2">
            Rows per page:
          </label>
          <select
            id="perPageSelect"
            className="form-select d-inline-block w-auto"
            value={perPage}
            onChange={(e) => {
              setPerPage(Number(e.target.value))
              setPage(1)
            }}
          >
            {[10, 25, 50, 100].map((n) => (
              <option key={n} value={n}>
                {n}
              </option>
            ))}
          </select>
        </div>
        <div className="d-flex align-items-center gap-2">
          <button
            type="button"
            className="btn btn-outline-secondary"
            disabled={page <= 1}
            onClick={() => setPage((p) => Math.max(1, p - 1))}
          >
            Previous
          </button>
          <span className="text-muted small">
            Page {page} of {pageCount}
          </span>
          <button
            type="button"
            className="btn btn-outline-secondary"
            disabled={page >= pageCount}
            onClick={() => setPage((p) => p + 1)}
          >
            Next
          </button>
        </div>
      </div>

      <div className="table-responsive">
        <table className="table table-striped table-bordered align-middle mb-0">
          <thead className="table-dark">
            <tr>
              <th>User ID</th>
              <th>Email</th>
              <th>Login Time</th>
              <th>Logout Time</th>
              <th>IP Address</th>
              <th>User Agent</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 ? (
              <tr>
                <td colSpan={6} className="text-center text-muted">
                  No login activities found.
                </td>
              </tr>
            ) : (
              rows.map((activity, i) => (
                <tr key={`${activity.user_id}-${activity.login_time}-${i}`}>
                  <td>{activity.user_id ?? '—'}</td>
                  <td>{activity.email ?? '—'}</td>
                  <td>{formatDt(activity.login_time)}</td>
                  <td>{formatDt(activity.logout_time)}</td>
                  <td>{activity.ip_address ?? '—'}</td>
                  <td style={{ maxWidth: 280, whiteSpace: 'normal', wordBreak: 'break-word' }}>
                    {activity.user_agent ?? '—'}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
