"use client"

import { useState, useEffect } from "react"
import Navigation from "@/components/Navigation"
import Link from "next/link"

interface Match {
  id: number
  playedAt: string | null
  team1Score: number
  team2Score: number
  status: string
  isCasual: boolean
  event?: {
    id: number
    name: string
  } | null
  player1P1: { id: number; name: string }
  player1P2: { id: number; name: string }
  player2P1: { id: number; name: string }
  player2P2: { id: number; name: string }
}

export default function AdminMatchesPage() {
  const [matches, setMatches] = useState<Match[]>([])
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(true)
  const [deletingId, setDeletingId] = useState<number | null>(null)

  useEffect(() => {
    fetchMatches()
  }, [])

  const fetchMatches = async () => {
    try {
      const response = await fetch("/api/matches")
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.error || "Failed to fetch matches")
      }
      const data = await response.json()
      setMatches(data)
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Unknown error")
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (matchId: number) => {
    if (!confirm("Are you sure you want to delete this match? This action cannot be undone.")) {
      return
    }

    setDeletingId(matchId)
    try {
      const response = await fetch(`/api/matches/${matchId}`, {
        method: "DELETE",
      })

      if (!response.ok) {
        try {
          const errorData = await response.json()
          alert(`Error: ${errorData.error || 'Failed to delete match'}`)
        } catch {
          alert(`Error: ${response.status} ${response.statusText}`)
        }
        return
      }

      const data = await response.json()

      if (data.success) {
        setMatches(matches.filter(m => m.id !== matchId))
      } else {
        alert(`Error: ${data.error}`)
      }
    } catch (err: unknown) {
      alert(`Error: ${err instanceof Error ? err.message : "Unknown error occurred"}`)
    } finally {
      setDeletingId(null)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Navigation />
        <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
          <div className="px-4 py-6 sm:px-0 text-center">
            <p>Loading matches...</p>
          </div>
        </main>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Navigation />

      <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <div className="px-4 py-6 sm:px-0">
          {/* Page Header */}
          <div className="flex justify-between items-center mb-6">
            <div>
              <h1 className="text-3xl font-bold text-gray-900">Match Management</h1>
              <p className="text-gray-500 mt-1">
                Manage {matches.length} match{matches.length !== 1 ? 'es' : ''} in the system
              </p>
            </div>
          </div>

          {error && (
            <div className="mb-4 p-4 bg-red-100 text-red-700 rounded">
              {error}
            </div>
          )}

          {/* Match Table */}
          <div className="bg-white shadow rounded-lg overflow-hidden">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Date
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Tournament
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Team 1
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Score
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Team 2
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Score
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {matches.map((match) => (
                  <tr key={match.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {match.playedAt
                        ? new Date(match.playedAt).toLocaleDateString()
                        : "N/A"}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {match.event ? (
                        <Link
                          href={`/admin/tournaments/${match.event.id}`}
                          className="text-blue-600 hover:text-blue-900"
                        >
                          {match.event.name}
                        </Link>
                      ) : (
                        <span className="text-gray-400 italic">Casual</span>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {match.player1P1?.name} & {match.player1P2?.name}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {match.team1Score}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {match.player2P1?.name} & {match.player2P2?.name}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {match.team2Score}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      <div className="flex gap-3">
                        <Link
                          href={`/matches/${match.id}`}
                          className="text-blue-600 hover:text-blue-900"
                        >
                          View
                        </Link>
                        <button
                          onClick={() => handleDelete(match.id)}
                          disabled={deletingId === match.id}
                          className="text-red-600 hover:text-red-900 disabled:opacity-50"
                        >
                          {deletingId === match.id ? "Deleting..." : "Delete"}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </main>
    </div>
  )
}
