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

const REFRESH_COOLDOWN_SECONDS = 5

export function RoomListPage() {
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [refreshCooldown, setRefreshCooldown] = useState(0)
  const [refreshMessage, setRefreshMessage] = useState('')
  const [rooms, setRooms] = useState<LiveRoomSummary[]>([])
  const loadingRef = useRef(false)

  useEffect(() => {
    let active = true

    const loadRooms = async () => {
      if (loadingRef.current) {
        return
      }

      loadingRef.current = true

      try {
        const nextRooms = await loadLiveRoomList()

        if (!active) {
          return
        }

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

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

        if (active) {
          setLoading(false)
        }
      }
    }

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

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

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

  useEffect(() => {
    if (refreshCooldown <= 0) {
      return
    }

    const timer = window.setTimeout(() => {
      setRefreshCooldown((current) => Math.max(0, current - 1))
    }, 1000)

    return () => window.clearTimeout(timer)
  }, [refreshCooldown])

  useEffect(() => {
    if (!refreshMessage) {
      return
    }

    const timer = window.setTimeout(() => {
      setRefreshMessage('')
    }, 2000)

    return () => window.clearTimeout(timer)
  }, [refreshMessage])

  const refreshRoomList = async () => {
    if (refreshCooldown > 0 || loadingRef.current) {
      return
    }

    loadingRef.current = true
    setRefreshing(true)
    setRefreshCooldown(REFRESH_COOLDOWN_SECONDS)

    try {
      const removedRoomIds = await reconcileLiveRooms()
      const nextRooms = await loadLiveRoomList()
      setRooms(nextRooms)
      setError('')
      setRefreshMessage(
        removedRoomIds.length > 0
          ? `已清掉 ${removedRoomIds.length} 個無主房間。`
          : '已檢查房間列表，沒有需要清理的房間。',
      )
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : '載入房間列表失敗。')
    } finally {
      loadingRef.current = false
      setRefreshing(false)
      setLoading(false)
    }
  }

  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">
        <div className="room-list-toolbar">
          <button
            className="secondary-button room-refresh-button"
            disabled={refreshCooldown > 0 || refreshing}
            onClick={() => void refreshRoomList()}
            type="button"
          >
            {refreshing
              ? '重新取得中...'
              : refreshCooldown > 0
                ? `${refreshCooldown} 秒後可重取`
                : '重新取得列表'}
          </button>
        </div>

        {refreshMessage ? <p className="selection-hint">{refreshMessage}</p> : null}
        {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>
  )
}
