import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchCertificatesAuditLog, type CertificateAuditPayload } from '../../api/certificates'

function formatDateTime(value?: string | null) {
  if (!value) return '—'
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? value : date.toLocaleString()
}

function formatDate(value?: string | null) {
  if (!value) return '—'
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString()
}

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

  const [data, setData] = useState<CertificateAuditPayload | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    setError(null)

    fetchCertificatesAuditLog({ school_year: schoolYear || undefined })
      .then((payload) => {
        if (!cancelled) setData(payload)
      })
      .catch((e) => {
        if (!cancelled) {
          setError(e instanceof ApiHttpError ? e.message : 'Failed to load certificate audit log.')
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })

    return () => {
      cancelled = true
    }
  }, [schoolYear])

  function onYearChange(nextYear: string) {
    const next = new URLSearchParams(searchParams)
    if (nextYear) next.set('school_year', nextYear)
    else next.delete('school_year')
    setSearchParams(next, { replace: true })
  }

  return (
    <div className="container-fluid py-4">
      <div className="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
        <div>
          <h2 className="mb-0">
            <i className="bi bi-journal-check me-2" />
            Certificate Audit Log
          </h2>
          <div className="text-muted small">
            Every issued certificate is recorded here for tracking and auditing.
          </div>
        </div>
        <Link to="/app/administrator/certificates" className="btn btn-outline-secondary btn-sm">
          <i className="bi bi-award me-1" />
          Generate Certificates
        </Link>
      </div>

      {error ? <div className="alert alert-danger">{error}</div> : null}
      {loading ? <div className="text-muted">Loading audit log…</div> : null}

      {(data?.year_summary?.length ?? 0) > 0 ? (
        <div className="row g-3 mb-4">
          {data?.year_summary.map((row) => (
            <div className="col-auto" key={row.school_year}>
              <div className="card shadow-sm text-center px-4 py-2" style={{ minWidth: 150 }}>
                <div className="fw-bold fs-4">{row.total}</div>
                <div className="text-muted small">{row.school_year}</div>
              </div>
            </div>
          ))}
        </div>
      ) : null}

      <div className="card shadow-sm mb-4">
        <div className="card-body py-2">
          <div className="row g-2 align-items-center">
            <div className="col-auto">
              <label className="col-form-label fw-semibold">School Year</label>
            </div>
            <div className="col-auto">
              <select
                className="form-select form-select-sm"
                value={schoolYear}
                onChange={(event) => onYearChange(event.target.value)}
              >
                <option value="">— All years —</option>
                {(data?.year_summary ?? []).map((row) => (
                  <option key={row.school_year} value={row.school_year}>
                    {row.school_year} ({row.total})
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>
      </div>

      <div className="card shadow-sm">
        <div className="card-header d-flex justify-content-between align-items-center">
          <span className="fw-semibold">
            Issued Certificates <span className="badge bg-secondary ms-1">{data?.records.length ?? 0}</span>
          </span>
        </div>
        <div className="card-body p-0">
          <div className="table-responsive">
            <table className="table table-hover table-striped align-middle mb-0 no-mgmt-sticky">
              <thead className="table-light">
                <tr>
                  <th>Certificate #</th>
                  <th>Student</th>
                  <th>Grade</th>
                  <th>Cert Date</th>
                  <th>School Year</th>
                  <th>Issued By</th>
                  <th>Issued At</th>
                </tr>
              </thead>
              <tbody>
                {(data?.records.length ?? 0) === 0 ? (
                  <tr>
                    <td colSpan={7} className="text-center text-muted py-4">
                      No certificates issued yet.
                    </td>
                  </tr>
                ) : (
                  data?.records.map((record) => (
                    <tr key={`${record.certificate_number}-${record.issued_at ?? ''}`}>
                      <td><code>{record.certificate_number}</code></td>
                      <td>{record.student_name}</td>
                      <td>{record.grade || '—'}</td>
                      <td>{formatDate(record.cert_date)}</td>
                      <td>{record.school_year || '—'}</td>
                      <td>{`${record.admin_firstname ?? ''} ${record.admin_lastname ?? ''}`.trim() || '—'}</td>
                      <td>{formatDateTime(record.issued_at)}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  )
}
