import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { loadLiveRoomList, subscribeRoomList } from '../lib/api'
import type { LiveRoomSummary } from '../types'

export function RoomListPage() {
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)
  const [rooms, setRooms] = useState<LiveRoomSummary[]>([])

  useEffect(() => {
    let active = true

    const load = async () => {
      try {
        const nextRooms = await loadLiveRoomList()

        if (!active) {
          return
        }

        setRooms(nextRooms)
        setError('')
      } catch (loadError) {
        if (!active) {
          return
        }

        setError(loadError instanceof Error ? loadError.message : '載入房間列表失敗。')
      } finally {
        if (active) {
          setLoading(false)
        }
      }
    }

    void load()
    const unsubscribe = subscribeRoomList((nextRooms) => {
      if (!active) {
        return
      }

      setRooms(nextRooms)
      setError('')
      setLoading(false)
    })

    return () => {
      active = false
      unsubscribe()
    }
  }, [])

  return (
    <section className="page-grid">
      <article className="panel panel-hero full-span">
        <p className="panel-kicker">Live Rooms</p>
        <h2>房間列表</h2>
        <p className="panel-copy">可查看目前正在進行中的房間，點進去就能即時觀戰。</p>
      </article>

      <article className="panel full-span">
        {loading ? <p>正在載入房間列表...</p> : null}
        {!loading && error ? <p className="history-empty">{error}</p> : null}
        {!loading && !error && rooms.length === 0 ? (
          <p className="history-empty">目前沒有正在進行中的房間。</p>
        ) : null}

        {!loading && !error && rooms.length > 0 ? (
          <div className="room-list-grid">
            {rooms.map((room) => (
              <Link className="room-card" key={room.roomId} to={`/rooms/${room.roomId}`}>
                <div className="room-card-head">
                  <strong>房號 {room.roomId}</strong>
                  <span>目標 {room.targetScore} 分</span>
                </div>

                <div className="room-card-matchup">
                  <strong>{room.leftTeamName}</strong>
                  <span>VS</span>
                  <strong>{room.rightTeamName}</strong>
                </div>

                <p className="room-card-updated">
                  最後更新 {new Date(room.updatedAt).toLocaleTimeString('zh-TW', { hour12: false })}
                </p>
              </Link>
            ))}
          </div>
        ) : null}
      </article>
    </section>
  )
}
