"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Navigation from "@/components/Navigation"

interface Player {
  id: number
  name: string
  currentElo: number
}

interface Team {
  id: number
  player1: Player
  player2: Player
}

interface BracketMatchup {
  id: number
  roundId: number
  team1Id: number | null
  team2Id: number | null
  tableNumber: number | null
  status: string
  team1: Team | null
  team2: Team | null
  matchId: number | null
}

interface TournamentRound {
  id: number
  roundNumber: number
  status: string
  matchups: BracketMatchup[]
}

interface Schedule {
  rounds: TournamentRound[]
}

interface Match {
  id: number
  player1P1Id: number
  player1P2Id: number
  player2P1Id: number
  player2P2Id: number
  team1Score: number
  team2Score: number
  status: string
}

interface Tournament {
  id: number
  name: string
  eventDate: string | null
  format: string
  tournamentType: string
  participants: { player: Player }[]
}

export default function TournamentEntryPage({ params }: { params: Promise<{ id: string }> }) {
  const router = useRouter()
  const [tournament, setTournament] = useState<Tournament | null>(null)
  const [tournamentId, setTournamentId] = useState<number | null>(null)
  const [schedule, setSchedule] = useState<Schedule | null>(null)
  const [matches, setMatches] = useState<Match[]>([])
  const [error, setError] = useState("")
  const [success, setSuccess] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [selectedRoundId, setSelectedRoundId] = useState<number | null>(null)
  const [selectedMatchupId, setSelectedMatchupId] = useState<number | null>(null)
  const [team1Score, setTeam1Score] = useState("")
  const [team2Score, setTeam2Score] = useState("")

  // Parse params and validate tournamentId, check for matchup query param
  useEffect(() => {
    async function parseParams() {
      const { id } = await params
      const parsedId = parseInt(id, 10)
      if (isNaN(parsedId)) {
        router.push('/admin/tournaments')
      } else {
        setTournamentId(parsedId)
      }
    }
    parseParams()
  }, [params, router])

  // Handle pre-selection of matchup from query param
  useEffect(() => {
    if (schedule && selectedMatchupId === null) {
      const searchParams = new URLSearchParams(window.location.search)
      const matchupIdParam = searchParams.get('matchup')
      if (matchupIdParam) {
        const matchupId = parseInt(matchupIdParam, 10)
        // Find which round contains this matchup
        for (const round of schedule.rounds) {
          const matchup = round.matchups.find(m => m.id === matchupId)
          if (matchup) {
            setSelectedRoundId(round.id)
            setSelectedMatchupId(matchupId)
            break
          }
        }
      }
    }
  }, [schedule, selectedMatchupId])

  // Load tournament, schedule, and matches
  useEffect(() => {
    if (tournamentId) {
      loadTournament()
      loadSchedule()
      loadMatches()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tournamentId])

  const loadTournament = async () => {
    try {
      const response = await fetch(`/api/tournaments/${tournamentId}`)
      if (response.ok) {
        const data = await response.json()
        setTournament(data.tournament)
      }
    } catch (err) {
      console.error("Failed to load tournament:", err)
    }
  }

  const loadSchedule = async () => {
    try {
      const response = await fetch(`/api/tournaments/${tournamentId}/schedule`)
      if (response.ok) {
        const data = await response.json()
        // API returns { rounds: [...] }, wrap in schedule object
        const rounds = data.rounds || []
        setSchedule({ rounds })
        if (rounds.length > 0) {
          setSelectedRoundId(rounds[0].id)
        }
      }
    } catch (err) {
      console.error("Failed to load schedule:", err)
    }
  }

  const loadMatches = async () => {
    try {
      const response = await fetch(`/api/tournaments/${tournamentId}/matches`)
      if (response.ok) {
        const data = await response.json()
        setMatches(data.matches || [])
      }
    } catch (err) {
      console.error("Failed to load matches:", err)
    }
  }

  const selectedRound = schedule?.rounds.find(r => r.id === selectedRoundId)
  const selectedMatchup = selectedRound?.matchups.find(m => m.id === selectedMatchupId)

  const getMatchupMatch = (matchup: BracketMatchup): Match | undefined => {
    if (!matchup.matchId) return undefined
    return matches.find(m => m.id === matchup.matchId)
  }

  const isMatchupCompleted = (matchup: BracketMatchup): boolean => {
    return getMatchupMatch(matchup) !== undefined
  }

  const handleSelectMatchup = (matchup: BracketMatchup) => {
    setSelectedMatchupId(matchup.id)
    setTeam1Score("")
    setTeam2Score("")
  }

  const handleSubmitScore = async () => {
    if (!selectedMatchup || !tournamentId) return

    const score1 = parseInt(team1Score)
    const score2 = parseInt(team2Score)

    if (isNaN(score1) || isNaN(score2)) {
      setError("Please enter valid scores for both teams")
      return
    }

    setError("")
    setSuccess("")
    setIsLoading(true)

    try {
      // Get team player IDs
      const team1 = selectedMatchup.team1
      const team2 = selectedMatchup.team2

      if (!team1 || !team2) {
        throw new Error("Teams not found for this matchup")
      }

      // Create match via bulk API
      const matchData = {
        round: selectedRound?.roundNumber || 1,
        table: selectedMatchup.tableNumber || 1,
        player1: team1.player1.name,
        player2: team1.player2.name,
        score1: score1,
        player3: team2.player1.name,
        player4: team2.player2.name,
        score2: score2,
      }

      const response = await fetch(`/api/tournaments/${tournamentId}/games/bulk`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          games: [matchData],
        }),
      })

      if (!response.ok) {
        try {
          const errorData = await response.json()
          throw new Error(errorData.error || "Failed to submit score")
        } catch (jsonError) {
          if (jsonError instanceof Error && jsonError.message !== "Failed to submit score") {
            throw jsonError
          }
          throw new Error(`Failed to submit score: ${response.status} ${response.statusText}`)
        }
      }

      const data = await response.json()

      setSuccess(`Score recorded: ${team1.player1.name} & ${team1.player2.name} ${score1} - ${score2} ${team2.player1.name} & ${team2.player2.name}`)
      setTeam1Score("")
      setTeam2Score("")
      setSelectedMatchupId(null)
      loadMatches() // Refresh matches
    } catch (err) {
      if (err instanceof Error) {
        setError(err.message)
      } else {
        setError("An unknown error occurred")
      }
    } finally {
      setIsLoading(false)
    }
  }

  if (!tournament) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Navigation />
        <main className="max-w-4xl mx-auto py-6 sm:px-6 lg:px-8">
          <div className="px-4 py-6 sm:px-0 text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600 mx-auto"></div>
          </div>
        </main>
      </div>
    )
  }

  const completedMatchups = schedule?.rounds.flatMap(r => r.matchups).filter(m => isMatchupCompleted(m)).length || 0
  const totalMatchups = schedule?.rounds.flatMap(r => r.matchups).length || 0

  return (
    <div className="min-h-screen bg-gray-50">
      <Navigation />
      
      <main className="max-w-6xl mx-auto py-6 sm:px-6 lg:px-8">
        <div className="px-4 py-6 sm:px-0">
          <div className="mb-6">
            <button
              onClick={() => router.push(`/admin/tournaments/${tournamentId}`)}
              className="text-green-600 hover:text-green-800 mb-4"
            >
              ← Back to Tournament
            </button>
            <h1 className="text-3xl font-bold text-gray-900">
              {tournament.name}
            </h1>
            {tournament.eventDate && (
              <p className="text-gray-600">
                {new Date(tournament.eventDate).toLocaleDateString()}
              </p>
            )}
          </div>

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

          {success && (
            <div className="rounded-md bg-green-50 p-4 mb-4">
              <div className="text-sm text-green-700">{success}</div>
            </div>
          )}

          {/* Progress Summary */}
          {schedule && (
            <div className="bg-white shadow rounded-lg p-4 mb-6">
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-lg font-medium text-gray-900">Tournament Progress</h2>
                  <p className="text-sm text-gray-500">
                    {completedMatchups} of {totalMatchups} games completed
                  </p>
                </div>
                <div className="text-right">
                  <div className="text-2xl font-bold text-green-600">
                    {totalMatchups > 0 ? Math.round((completedMatchups / totalMatchups) * 100) : 0}%
                  </div>
                  <p className="text-sm text-gray-500">complete</p>
                </div>
              </div>
              <div className="mt-3 bg-gray-200 rounded-full h-2">
                <div 
                  className="bg-green-600 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${totalMatchups > 0 ? (completedMatchups / totalMatchups) * 100 : 0}%` }}
                />
              </div>
            </div>
          )}

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Rounds Panel */}
            <div className="lg:col-span-1">
              <div className="bg-white shadow rounded-lg p-4">
                <h2 className="text-lg font-medium text-gray-900 mb-3">Rounds</h2>
                {schedule?.rounds ? (
                  <div className="space-y-2">
                    {schedule.rounds.map(round => {
                      const roundCompleted = round.matchups.every(m => isMatchupCompleted(m))
                      const roundInProgress = round.matchups.some(m => isMatchupCompleted(m)) && !roundCompleted
                      return (
                        <button
                          key={round.id}
                          onClick={() => setSelectedRoundId(round.id)}
                          className={`w-full text-left px-3 py-2 rounded-md border transition-colors ${
                            selectedRoundId === round.id
                              ? 'border-green-500 bg-green-50'
                              : 'border-gray-200 hover:bg-gray-50'
                          }`}
                        >
                          <div className="flex items-center justify-between">
                            <span className="font-medium">Round {round.roundNumber}</span>
                            <span className={`text-xs px-2 py-1 rounded-full ${
                              roundCompleted 
                                ? 'bg-green-100 text-green-800' 
                                : roundInProgress
                                ? 'bg-yellow-100 text-yellow-800'
                                : 'bg-gray-100 text-gray-600'
                            }`}>
                              {roundCompleted ? 'Completed' : roundInProgress ? 'In Progress' : 'Not Started'}
                            </span>
                          </div>
                          <p className="text-xs text-gray-500 mt-1">
                            {round.matchups.length} matchup{round.matchups.length !== 1 ? 's' : ''}
                          </p>
                        </button>
                      )
                    })}
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <p className="text-gray-500">No schedule generated yet.</p>
                    <button
                      onClick={() => router.push(`/admin/tournaments/${tournamentId}`)}
                      className="mt-2 text-green-600 hover:text-green-800 text-sm"
                    >
                      Generate schedule from tournament page →
                    </button>
                  </div>
                )}
              </div>

              {/* Participants Panel */}
              <div className="bg-white shadow rounded-lg p-4 mt-4">
                <h2 className="text-lg font-medium text-gray-900 mb-3">
                  Participants ({tournament.participants.length})
                </h2>
                <div className="max-h-48 overflow-y-auto">
                  {tournament.participants.map(({ player }) => (
                    <div key={player.id} className="py-1 text-sm text-gray-700">
                      {player.name}
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Round Detail Panel */}
            <div className="lg:col-span-2">
              <div className="bg-white shadow rounded-lg p-4">
                <h2 className="text-lg font-medium text-gray-900 mb-3">
                  {selectedRound ? `Round ${selectedRound.roundNumber} Matchups` : 'Select a Round'}
                </h2>

                {selectedRound ? (
                  <div className="space-y-3">
                    {selectedRound.matchups.map((matchup, index) => {
                      const completed = isMatchupCompleted(matchup)
                      const match = getMatchupMatch(matchup)
                      const isSelected = selectedMatchupId === matchup.id

                      return (
                        <div 
                          key={matchup.id}
                          className={`border rounded-md p-4 transition-colors ${
                            completed 
                              ? 'bg-green-50 border-green-200' 
                              : isSelected 
                              ? 'border-blue-500 bg-blue-50' 
                              : 'border-gray-200 hover:border-gray-300 cursor-pointer'
                          }`}
                          onClick={() => !completed && handleSelectMatchup(matchup)}
                        >
                          <div className="flex items-center justify-between mb-2">
                            <span className="text-sm font-medium text-gray-500">
                              Match {index + 1}
                              {matchup.tableNumber && ` • Table ${matchup.tableNumber}`}
                            </span>
                            {completed && (
                              <span className="text-xs px-2 py-1 rounded-full bg-green-100 text-green-800">
                                Completed
                              </span>
                            )}
                          </div>

                          {matchup.team1 && matchup.team2 ? (
                            <div className="grid grid-cols-7 gap-2 items-center">
                              <div className="col-span-3">
                                <p className="font-medium text-gray-900">
                                  {matchup.team1.player1.name} & {matchup.team1.player2.name}
                                </p>
                                <p className="text-xs text-gray-500">
                                  Team {matchup.team1.id}
                                </p>
                              </div>
                              <div className="col-span-1 text-center">
                                {completed && match ? (
                                  <div className="flex items-center justify-center gap-1">
                                    <span className={`text-lg font-bold ${match.team1Score > match.team2Score ? 'text-green-600' : 'text-gray-600'}`}>
                                      {match.team1Score}
                                    </span>
                                    <span className="text-gray-400">-</span>
                                    <span className={`text-lg font-bold ${match.team2Score > match.team1Score ? 'text-green-600' : 'text-gray-600'}`}>
                                      {match.team2Score}
                                    </span>
                                  </div>
                                ) : (
                                  <span className="text-gray-400 text-sm">vs</span>
                                )}
                              </div>
                              <div className="col-span-3 text-right">
                                <p className="font-medium text-gray-900">
                                  {matchup.team2.player1.name} & {matchup.team2.player2.name}
                                </p>
                                <p className="text-xs text-gray-500">
                                  Team {matchup.team2.id}
                                </p>
                              </div>
                            </div>
                          ) : (
                            <p className="text-gray-400 text-sm">Teams not assigned</p>
                          )}

                          {/* Score Entry Form */}
                          {isSelected && !completed && matchup.team1 && matchup.team2 && (
                            <div className="mt-4 pt-4 border-t border-gray-200">
                              <p className="text-sm font-medium text-gray-700 mb-3">Enter Score</p>
                              <div className="grid grid-cols-9 gap-2 items-end">
                                <div className="col-span-4">
                                  <label className="block text-xs text-gray-500 mb-1">
                                    {matchup.team1.player1.name} & {matchup.team1.player2.name}
                                  </label>
                                  <input
                                    type="number"
                                    min="0"
                                    max="10"
                                    className="w-full border border-gray-300 rounded-md py-2 px-3 text-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
                                    value={team1Score}
                                    onChange={(e) => setTeam1Score(e.target.value)}
                                    placeholder="0"
                                  />
                                </div>
                                <div className="col-span-1 flex items-center justify-center pb-2">
                                  <span className="text-gray-400">-</span>
                                </div>
                                <div className="col-span-4">
                                  <label className="block text-xs text-gray-500 mb-1">
                                    {matchup.team2.player1.name} & {matchup.team2.player2.name}
                                  </label>
                                  <input
                                    type="number"
                                    min="0"
                                    max="10"
                                    className="w-full border border-gray-300 rounded-md py-2 px-3 text-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
                                    value={team2Score}
                                    onChange={(e) => setTeam2Score(e.target.value)}
                                    placeholder="0"
                                  />
                                </div>
                              </div>
                              <div className="mt-3 flex justify-end space-x-2">
                                <button
                                  type="button"
                                  onClick={() => {
                                    setSelectedMatchupId(null)
                                    setTeam1Score("")
                                    setTeam2Score("")
                                  }}
                                  className="px-3 py-1.5 text-sm text-gray-600 hover:text-gray-800"
                                >
                                  Cancel
                                </button>
                                <button
                                  type="button"
                                  onClick={handleSubmitScore}
                                  disabled={isLoading || !team1Score || !team2Score}
                                  className="px-3 py-1.5 text-sm bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50"
                                >
                                  {isLoading ? "Saving..." : "Save Score"}
                                </button>
                              </div>
                            </div>
                          )}
                        </div>
                      )
                    })}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    Select a round to view matchups
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}
