import { useEffect, useState } from 'react'
import { deleteHistoryItem, loadHistoryList } from '../lib/api'
import type { HistoryListItem } from '../types'

const HISTORY_PAGE_SIZE = 20

export function HistoryPage() {
  const [history, setHistory] = useState<HistoryListItem[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [selectedItem, setSelectedItem] = useState<HistoryListItem | null>(null)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [totalPages, setTotalPages] = useState(1)
  // 刪除後遞增，讓目前頁面重新讀取一次。
  const [reloadSignal, setReloadSignal] = useState(0)

  useEffect(() => {
    let active = true

    const run = async () => {
      setLoading(true)
      setError('')

      try {
        const result = await loadHistoryList(page, HISTORY_PAGE_SIZE)

        if (!active) {
          return
        }

        // 刪除或資料變動後，目前頁碼可能超出範圍，往回跳到最後一頁。
        if (result.items.length === 0 && result.total > 0 && page > result.totalPages) {
          setPage(result.totalPages)
          return
        }

        setHistory(result.items)
        setTotal(result.total)
        setTotalPages(result.totalPages)
      } catch (fetchError) {
        if (!active) {
          return
        }

        setError(fetchError instanceof Error ? fetchError.message : '讀取歷史戰績失敗。')
      } finally {
        if (active) {
          setLoading(false)
        }
      }
    }

    void run()

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

  const handleDelete = async (item: HistoryListItem) => {
    const confirmed = window.confirm(
      `確定要刪除此筆戰績嗎？\n${item.leftTeamName} vs ${item.rightTeamName}`,
    )

    if (!confirmed) {
      return
    }

    setDeletingId(item.id)
    setError('')

    try {
      await deleteHistoryItem(item.id)
      setSelectedItem((current) => (current?.id === item.id ? null : current))
      setReloadSignal((current) => current + 1)
    } catch (deleteError) {
      setError(deleteError instanceof Error ? deleteError.message : '刪除戰績失敗。')
    } finally {
      setDeletingId(null)
    }
  }

  const goToPage = (nextPage: number) => {
    if (nextPage < 1 || nextPage > totalPages || nextPage === page || loading) {
      return
    }

    setPage(nextPage)
  }

  return (
    <>
      <section className="page-grid">
        <article className="panel panel-hero">
          <p className="panel-kicker">History</p>
          <h2>歷史戰績</h2>
          <p className="panel-copy">
            這裡會直接從資料庫的 `history` 表讀取比賽紀錄，點開後可查看每一分的得分過程，也能刪除單筆資料。
          </p>
        </article>

        <article className="panel full-span">
          {loading ? (
            <div className="empty-state">
              <h3>正在讀取戰績</h3>
              <p>請稍候，系統正在載入歷史紀錄。</p>
            </div>
          ) : error ? (
            <div className="empty-state">
              <h3>讀取失敗</h3>
              <p>{error}</p>
            </div>
          ) : history.length === 0 ? (
            <div className="empty-state">
              <h3>目前沒有歷史戰績</h3>
              <p>資料庫 `history` 表目前還沒有可顯示的資料。</p>
            </div>
          ) : (
            <>
            <div className="history-list">
              {history.map((item) => (
                <article className="history-card history-card-shell" key={item.id}>
                  <button
                    className="history-card-button history-card-content"
                    type="button"
                    onClick={() => setSelectedItem(item)}
                  >
                    <div className="history-head">
                      <div>
                        <p className="panel-kicker">
                          {item.playedAt} / {item.dayLabel}
                        </p>
                        <h3>
                          {item.leftTeamName} vs {item.rightTeamName}
                        </h3>
                      </div>
                      <span className="winner-badge">勝方：{item.winnerTeamName}</span>
                    </div>

                    <div className="history-meta">
                      <span>
                        比分：{item.score[0]} - {item.score[1]}
                      </span>
                      <span>模式：{item.typeLabel}</span>
                      <span>獲勝分數：{item.winScore}</span>
                    </div>
                  </button>

                  <button
                    className="history-delete-button"
                    disabled={deletingId === item.id}
                    type="button"
                    onClick={() => void handleDelete(item)}
                  >
                    {deletingId === item.id ? '刪除中...' : '刪除此筆'}
                  </button>
                </article>
              ))}
            </div>

            <nav className="history-pagination" aria-label="歷史戰績分頁">
              <button
                className="secondary-button pagination-button"
                disabled={page <= 1 || loading}
                type="button"
                onClick={() => goToPage(page - 1)}
              >
                上一頁
              </button>

              <div className="pagination-pages">
                {getPageItems(page, totalPages).map((item, index) =>
                  item === 'ellipsis' ? (
                    <span className="pagination-ellipsis" key={`ellipsis-${index}`}>
                      …
                    </span>
                  ) : (
                    <button
                      className={
                        item === page
                          ? 'secondary-button pagination-button pagination-button-active'
                          : 'secondary-button pagination-button'
                      }
                      disabled={loading}
                      key={item}
                      type="button"
                      onClick={() => goToPage(item)}
                    >
                      {item}
                    </button>
                  ),
                )}
              </div>

              <button
                className="secondary-button pagination-button"
                disabled={page >= totalPages || loading}
                type="button"
                onClick={() => goToPage(page + 1)}
              >
                下一頁
              </button>

              <span className="pagination-summary">共 {total} 筆</span>
            </nav>
            </>
          )}
        </article>
      </section>

      {selectedItem ? (
        <HistoryReplayModal item={selectedItem} onClose={() => setSelectedItem(null)} />
      ) : null}
    </>
  )
}

type HistoryReplayModalProps = {
  item: HistoryListItem
  onClose: () => void
}

function HistoryReplayModal({ item, onClose }: HistoryReplayModalProps) {
  return (
    <div className="history-modal-overlay" role="presentation" onClick={onClose}>
      <div
        aria-modal="true"
        className="history-modal"
        role="dialog"
        onClick={(event) => event.stopPropagation()}
      >
        <button
          aria-label="關閉戰績紀錄"
          className="history-modal-close"
          type="button"
          onClick={onClose}
        >
          ×
        </button>

        <p className="panel-kicker">得分紀錄</p>
        <h3>
          {item.leftTeamName} vs {item.rightTeamName}
        </h3>

        <div className="history-modal-score">
          <div>
            <strong>{item.score[0]}</strong>
            <span>{item.leftTeamName}</span>
          </div>
          <div className="history-modal-score-divider">:</div>
          <div>
            <strong>{item.score[1]}</strong>
            <span>{item.rightTeamName}</span>
          </div>
        </div>

        <div className="history-modal-summary">
          <span>{item.playedAt}</span>
          <span>{item.typeLabel}</span>
          <span>勝方：{item.winnerTeamName}</span>
        </div>

        <div className="history-replay-list">
          {item.scoreList.length === 0 ? (
            <p className="history-replay-empty">這筆戰績沒有可顯示的得分紀錄。</p>
          ) : (
            item.scoreList.map(([round, starter, winCount, winner]) => (
              <div className="history-replay-row" key={`${item.id}-${round}`}>
                <span>第 {round + 1} 球</span>
                <span>發球：{getStarterName(item, starter)}</span>
                <span>連勝 {winCount + 1}</span>
                <strong>{winner === 0 ? item.leftTeamName : item.rightTeamName}</strong>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  )
}

function getStarterName(item: HistoryListItem, starter: number) {
  return item.players[starter] ?? '未知球員'
}

// 產生分頁按鈕：固定顯示第一頁與最後一頁，目前頁前後各一頁，其餘收成省略號。
function getPageItems(currentPage: number, totalPages: number) {
  const pages = new Set<number>([1, totalPages])

  for (let offset = -1; offset <= 1; offset += 1) {
    const candidate = currentPage + offset

    if (candidate >= 1 && candidate <= totalPages) {
      pages.add(candidate)
    }
  }

  const sorted = Array.from(pages).sort((left, right) => left - right)
  const items: Array<number | 'ellipsis'> = []

  sorted.forEach((pageNumber, index) => {
    if (index > 0 && pageNumber - sorted[index - 1] > 1) {
      items.push('ellipsis')
    }

    items.push(pageNumber)
  })

  return items
}
