import { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { fetchAdminCompetitionWinnerWinners } from '../../api/session'
import type { CompetitionWinnerAdminWinnerRow, CompetitionWinnerAdminWinnersResponse } from '../../api/types'
import { ApiScopeNote, CompetitionPageShell, competitionLabel } from './competitionWinnersShared'

/** CI `admin/competition_winners/winners.php` */
export function CompetitionWinnerWinnersPage() {
  const { id } = useParams()
  const competitionId = Number(id)
  const [data, setData] = useState<CompetitionWinnerAdminWinnersResponse | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!Number.isFinite(competitionId) || competitionId <= 0) return
    ;(async () => {
      try {
        const response = await fetchAdminCompetitionWinnerWinners(competitionId)
        setData(response)
        setError(response.ok ? null : response.message ?? 'Competition not found.')
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Unable to load winners.')
      }
    })()
  }, [competitionId])

  const totalPrize = useMemo(
    () => (data?.rows ?? []).reduce((sum, row) => sum + Number(row.prize_amount ?? 0), 0),
    [data?.rows],
  )

  return (
    <CompetitionPageShell title="School Winners">
      <ApiScopeNote>
        This listing comes from the admin winners table and reflects the last published winner set for the competition.
      </ApiScopeNote>
      {error ? <div className="alert alert-danger">{error}</div> : null}
      {data?.competition ? (
        <>
          <div className="mb-3">
            <div>
              <strong>Competition:</strong> {competitionLabel(data.competition)}
            </div>
            <div>
              <strong>School Year:</strong> {data.competition.school_year ?? '—'}
            </div>
            <div>
              <strong>Published:</strong> {data.competition.is_published ? 'Yes' : 'No'}
            </div>
          </div>
          {(data.rows ?? []).length === 0 ? (
            <div className="alert alert-warning">No published winners yet.</div>
          ) : (
            <div className="table-responsive">
              <table className="table table-bordered table-sm">
                <thead className="table-light">
                  <tr>
                    <th>Class</th>
                    <th>Student</th>
                    <th>School ID</th>
                    <th>Rank</th>
                    <th>Score</th>
                    <th>Prize</th>
                  </tr>
                </thead>
                <tbody>
                  {(data.rows ?? []).map((row: CompetitionWinnerAdminWinnerRow, index) => (
                    <tr key={`${row.class_section_id ?? 'class'}-${row.student_id ?? index}-${index}`}>
                      <td>{data.sectionMap?.[String(row.class_section_id ?? '')] ?? `Class ${row.class_section_id ?? ''}`}</td>
                      <td>
                        {row.name ??
                          (`${row.firstname ?? ''} ${row.lastname ?? ''}`.trim() ||
                            `Student #${row.student_id ?? ''}`)}
                      </td>
                      <td>{row.school_id ?? '—'}</td>
                      <td>{row.rank ?? '—'}</td>
                      <td>{row.score ?? '—'}</td>
                      <td>{row.prize_amount ?? '—'}</td>
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr>
                    <th colSpan={5} className="text-end">
                      Total Prizes
                    </th>
                    <th>{totalPrize.toFixed(2)}</th>
                  </tr>
                </tfoot>
              </table>
            </div>
          )}
        </>
      ) : null}
    </CompetitionPageShell>
  )
}
