"use client"

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

interface Player {
  id: number
  name: string
  currentElo: number
  gamesPlayed: number
  wins: number
  losses: number
  user?: {
    email: string
  } | null
}

export default function AdminPlayersPage() {
  const [players, setPlayers] = useState<Player[]>([])
  const [error, setError] = useState("")
  const [editingPlayer, setEditingPlayer] = useState<Player | null>(null)
  const [newName, setNewName] = useState("")
  const [isSaving, setIsSaving] = useState(false)
  
  // Merge player state
  const [mergeMode, setMergeMode] = useState(false)
  const [selectedPlayers, setSelectedPlayers] = useState<number[]>([])
  const [isMerging, setIsMerging] = useState(false)
  const [deletingId, setDeletingId] = useState<number | null>(null)

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

  const fetchPlayers = async () => {
    try {
      const response = await fetch("/api/players")
      if (!response.ok) {
        throw new Error("Failed to fetch players")
      }
      const data = await response.json()
      setPlayers(data)
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Unknown error")
    }
  }

  const handleEditClick = (player: Player) => {
    setEditingPlayer(player)
    setNewName(player.name)
  }

  const handleSaveName = async () => {
    if (!editingPlayer || !newName.trim()) return

    setIsSaving(true)
    try {
      const response = await fetch(`/api/admin/players/${editingPlayer.id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ name: newName.trim() }),
      })

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

      const data = await response.json()

      if (data.success) {
        setPlayers(players.map(p =>
          p.id === editingPlayer.id ? { ...p, name: data.player.name } : p
        ))
        setEditingPlayer(null)
        setNewName("")
      } else {
        alert(`Error: ${data.error}`)
      }
    } catch (err: unknown) {
      alert(`Error: ${err instanceof Error ? err.message : "Unknown error"}`)
    } finally {
      setIsSaving(false)
    }
  }

  const togglePlayerSelection = (playerId: number) => {
    setSelectedPlayers(prev =>
      prev.includes(playerId)
        ? prev.filter(id => id !== playerId)
        : [...prev, playerId]
    )
  }

  const handleMerge = async () => {
    if (selectedPlayers.length < 2) return

    setIsMerging(true)
    try {
      const response = await fetch('/api/admin/players/merge', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          playerIds: selectedPlayers,
        }),
      })

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

      const data = await response.json()

      if (data.success) {
        alert(`Successfully merged ${selectedPlayers.length} players! Elo ratings have been recalculated.`)
        // Refresh the player list
        fetchPlayers()
        setSelectedPlayers([])
        setMergeMode(false)
      } else {
        alert(`Error: ${data.error}`)
      }
    } catch (err: unknown) {
      alert(`Error: ${err instanceof Error ? err.message : "Unknown error occurred"}`)
    } finally {
      setIsMerging(false)
    }
  }

  const handleDelete = async (playerId: number) => {
    if (!confirm("Are you sure you want to delete this player? This action cannot be undone and the player must not have any match history.")) {
      return
    }

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

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

      const data = await response.json()

      if (data.success) {
        setPlayers(players.filter(p => p.id !== playerId))
      } else {
        alert(`Error: ${data.error}`)
      }
    } catch (err: unknown) {
      alert(`Error: ${err instanceof Error ? err.message : 'Unknown error occurred'}`)
    } finally {
      setDeletingId(null)
    }
  }

  const playerCount = players.length

  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">Player Management</h1>
              <p className="text-gray-500 mt-1">
                Manage {playerCount} player{playerCount !== 1 ? 's' : ''} in the system
              </p>
            </div>
            <div className="flex space-x-2">
              <button
                onClick={() => setMergeMode(!mergeMode)}
                className={`px-4 py-2 rounded-md shadow-sm text-sm font-medium ${
                  mergeMode
                    ? 'bg-purple-600 text-white hover:bg-purple-700'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                {mergeMode ? 'Cancel Merge' : 'Merge Players'}
              </button>
            </div>
          </div>

          {mergeMode && selectedPlayers.length > 0 && (
            <div className="mb-4 p-4 bg-purple-50 rounded-lg">
              <div className="flex items-center justify-between">
                <span className="text-purple-700">
                  {selectedPlayers.length} player{selectedPlayers.length !== 1 ? 's' : ''} selected for merging
                </span>
                <button
                  onClick={handleMerge}
                  disabled={isMerging || selectedPlayers.length < 2}
                  className="px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 disabled:opacity-50"
                >
                  {isMerging ? 'Merging...' : `Merge ${selectedPlayers.length} Players`}
                </button>
              </div>
            </div>
          )}

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

          {/* Player 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">
                    Player Name
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Current Elo
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Games
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Record
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Win Rate
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    User Account
                  </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">
                {players.map((player) => {
                  const isSelected = selectedPlayers.includes(player.id)
                  return (
                    <tr
                      key={player.id}
                      className={`${isSelected ? 'bg-purple-50' : 'hover:bg-gray-50'} ${
                        mergeMode ? 'cursor-pointer' : ''
                      }`}
                      onClick={() => mergeMode && togglePlayerSelection(player.id)}
                    >
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="flex items-center">
                          {mergeMode && (
                            <input
                              type="checkbox"
                              checked={isSelected}
                              onChange={() => togglePlayerSelection(player.id)}
                              className="mr-3 h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded"
                            />
                          )}
                          <div className="flex-shrink-0 h-10 w-10 bg-gray-200 rounded-full flex items-center justify-center">
                            <span className="text-sm font-medium text-gray-600">
                              {player.name.charAt(0).toUpperCase()}
                            </span>
                          </div>
                          <div className="ml-4">
                            <div className="text-sm font-medium text-gray-900">
                              {player.name}
                            </div>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                        {player.currentElo}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {player.gamesPlayed}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {player.wins}-{player.losses}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {player.gamesPlayed > 0
                          ? ((player.wins / player.gamesPlayed) * 100).toFixed(1) + '%'
                          : 'N/A'}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {player.user ? (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            {player.user.email}
                          </span>
                        ) : (
                          <span className="text-gray-400 italic">No account</span>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        <div className="flex space-x-2">
                          <Link
                            href={`/players/${player.id}/profile`}
                            className="text-green-600 hover:text-green-900"
                          >
                            View
                          </Link>
                          {!mergeMode && (
                            <>
                              <button
                                onClick={(e) => {
                                  e.stopPropagation()
                                  handleEditClick(player)
                                }}
                                className="text-blue-600 hover:text-blue-900"
                              >
                                Edit
                              </button>
                              <button
                                onClick={(e) => {
                                  e.stopPropagation()
                                  handleDelete(player.id)
                                }}
                                disabled={deletingId === player.id}
                                className="text-red-600 hover:text-red-900 disabled:opacity-50"
                              >
                                {deletingId === player.id ? "Deleting..." : "Delete"}
                              </button>
                            </>
                          )}
                        </div>
                      </td>
                    </tr>
                  )
                 })}
              </tbody>
            </table>
          </div>
        </div>
      </main>

      {/* Edit Player Modal */}
      {editingPlayer && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 flex items-center justify-center">
          <div className="bg-white rounded-lg shadow-xl p-6 m-4 max-w-md w-full">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              Edit Player Name
            </h3>
            
            <p className="text-sm text-gray-600 mb-4">
              Current name: {editingPlayer.name}
            </p>

            <div className="mb-6">
              <label htmlFor="playerName" className="block text-sm font-medium text-gray-700 mb-2">
                New Name
              </label>
              <input
                type="text"
                id="playerName"
                value={newName}
                onChange={(e) => setNewName(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
                placeholder="Enter new player name"
              />
            </div>

            <div className="flex justify-end space-x-3">
              <button
                type="button"
                onClick={() => {
                  setEditingPlayer(null)
                  setNewName("")
                }}
                className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={handleSaveName}
                disabled={isSaving || !newName.trim()}
                className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 disabled:opacity-50"
              >
                {isSaving ? 'Saving...' : 'Save'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
