import { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { fetchPublishedCompetition, fetchPublishedCompetitions } from '../../api/session'
import type { PublicCompetitionRow, PublicCompetitionWinnerRow } from '../../api/types'

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

export function PublicWinnersCompetitionsIndexPage() {
  const [competitions, setCompetitions] = useState<PublicCompetitionRow[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const res = await fetchPublishedCompetitions()
        if (cancelled) return
        setCompetitions(res.data?.competitions ?? [])
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load competitions.')
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  return (
    <div className="container mt-4">
      <h3>Competition Winners</h3>
      <p className="text-muted">Published competition winner announcements.</p>
      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="list-group">
        {competitions.map((c) => (
          <Link
            key={c.id}
            className="list-group-item list-group-item-action"
            to={`/app/winners/competitions/${c.id}`}
          >
            <div className="d-flex justify-content-between">
              <div>
                <strong>{c.title}</strong>
              </div>
              <small className="text-muted">{formatPublishedAt(c.published_at)}</small>
            </div>
          </Link>
        ))}
      </div>

      {competitions.length === 0 && !error ? (
        <div className="alert alert-info">No winners published yet.</div>
      ) : null}
    </div>
  )
}

export function PublicWinnersCompetitionShowPage() {
  const { competitionId } = useParams()
  const id = Number(competitionId)
  const [title, setTitle] = useState('')
  const [publishedAt, setPublishedAt] = useState('')
  const [winnersByClass, setWinnersByClass] = useState<Record<string, PublicCompetitionWinnerRow[]>>({})
  const [sectionMap, setSectionMap] = useState<Record<string, string>>({})
  const [questionCounts, setQuestionCounts] = useState<Record<string, number>>({})
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!id) return
    let cancelled = false
    ;(async () => {
      try {
        const res = await fetchPublishedCompetition(id)
        if (cancelled) return
        const data = res.data
        if (data?.competition) {
          setTitle(data.competition.title ?? '')
          setPublishedAt(formatPublishedAt(data.competition.published_at))
        }
        setWinnersByClass(data?.winners_by_class ?? {})
        setSectionMap(data?.section_map ?? {})
        setQuestionCounts(data?.question_counts ?? {})
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load competition.')
      }
    })()
    return () => {
      cancelled = true
    }
  }, [id])

  return (
    <div className="container mt-4">
      <Link className="btn btn-outline-secondary btn-sm mb-3" to="/app/winners/competitions">
        &larr; Back
      </Link>

      <h3>{title}</h3>
      <div className="text-muted mb-3">Published: {publishedAt}</div>
      {error ? <div className="alert alert-danger">{error}</div> : null}

      {Object.keys(winnersByClass).length === 0 && !error ? (
        <div className="alert alert-info">No winners found.</div>
      ) : null}

      {Object.entries(winnersByClass).map(([classId, rows]) => {
        const classLabel = sectionMap[classId] ?? `Class ${classId}`
        const questions = questionCounts[classId]
        return (
          <section key={classId}>
            <h5 className="mt-4">{classLabel}</h5>
            {questions !== undefined && questions !== null ? (
              <div className="text-muted mb-2">Questions: {questions}</div>
            ) : null}
            <table className="table table-bordered" data-no-mgmt-sticky>
              <thead className="table-light">
                <tr>
                  <th style={{ width: 90 }}>Rank</th>
                  <th>Student</th>
                  <th style={{ width: 140 }}>Score</th>
                  <th style={{ width: 160 }}>Prize</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((w, i) => (
                  <tr key={`${classId}-${i}`}>
                    <td>{w.rank ?? i + 1}</td>
                    <td>
                      {(w.name ??
                        `${w.firstname ?? ''} ${w.lastname ?? ''}`.trim()) ||
                        `Student #${w.student_id ?? ''}`}
                    </td>
                    <td>{w.score ?? '—'}</td>
                    <td>{w.prize_amount !== undefined && w.prize_amount !== '' ? w.prize_amount : '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>
        )
      })}
    </div>
  )
}
