"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import type { Player, Match } from "@prisma/client"

interface MatchEditorProps {
  tournamentId: number
  players: Player[]
  matches: Match[]
  targetScore: number | null
  allowTies: boolean
  // Optional pre-filled player IDs from URL params
  prefilledP1?: number
  prefilledP2?: number
  prefilledP3?: number
  prefilledP4?: number
  prefilledRound?: number
}

interface MatchData {
  team1P1Id: number | null
  team1P2Id: number | null
  team2P1Id: number | null
  team2P2Id: number | null
  team1Score: number
  team2Score: number
  round: number
  table: string
  isCasual: boolean
}

export default function MatchEditor({ 
  tournamentId, 
  players, 
  targetScore, 
  allowTies,
  prefilledP1,
  prefilledP2,
  prefilledP3,
  prefilledP4,
  prefilledRound,
}: MatchEditorProps) {
  const router = useRouter()
  // Check if players are prefilled from URL params
  const hasPrefilledPlayers = prefilledP1 && prefilledP2 && prefilledP3 && prefilledP4;
  
  const [formData, setFormData] = useState<MatchData>({
    team1P1Id: hasPrefilledPlayers ? prefilledP1 : null,
    team1P2Id: hasPrefilledPlayers ? prefilledP2 : null,
    team2P1Id: hasPrefilledPlayers ? prefilledP3 : null,
    team2P2Id: hasPrefilledPlayers ? prefilledP4 : null,
    team1Score: 0,
    team2Score: 0,
    round: prefilledRound || 1,
    table: "Clubs",
    isCasual: false,
  })
  const [error, setError] = useState("")
  const [success, setSuccess] = useState("")
  const [isLoading, setIsLoading] = useState(false)

  const tables = ["Clubs", "Hearts", "Diamonds", "Spades", "Stars"]

  const handleChange = (e: React.ChangeEvent<HTMLSelectElement | HTMLInputElement>) => {
    const { name, value, type } = e.target
    const checked = (e.target as HTMLInputElement).checked
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked :
              name.includes("Id") ? (value ? parseInt(value) : null) : 
              name === "round" ? parseInt(value) :
              name === "team1Score" || name === "team2Score" ? parseInt(value) :
              value,
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError("")
    setSuccess("")

    // Validate that all players are selected
    if (!formData.team1P1Id || !formData.team1P2Id || !formData.team2P1Id || !formData.team2P2Id) {
      setError("Please select all 4 players")
      return
    }

    // Validate that players are unique
    const playerIds = [formData.team1P1Id, formData.team1P2Id, formData.team2P1Id, formData.team2P2Id]
    if (new Set(playerIds).size !== 4) {
      setError("All players must be unique")
      return
    }

    // Validate scores (at least one team must have points)
    if (formData.team1Score === 0 && formData.team2Score === 0) {
      setError("At least one team must have points")
      return
    }

    // Validate target score if provided
    if (targetScore) {
      const team1ReachedTarget = formData.team1Score >= targetScore;
      const team2ReachedTarget = formData.team2Score >= targetScore;
      
      // Check if one team reached the target
      if (!team1ReachedTarget && !team2ReachedTarget) {
        setError(`Scores must reach the target score of ${targetScore}`)
        return
      }
      
      // Check if both teams reached the target (invalid unless ties are allowed and it's a tie)
      if (team1ReachedTarget && team2ReachedTarget && formData.team1Score !== formData.team2Score) {
        setError(`Only one team can reach the target score of ${targetScore}`)
        return
      }
    }

    // Validate ties
    if (!allowTies && formData.team1Score === formData.team2Score) {
      setError("Ties are not allowed in this tournament")
      return
    }

    setIsLoading(true)

    try {
      const response = await fetch("/api/matches", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          eventId: tournamentId,
          team1P1Id: formData.team1P1Id,
          team1P2Id: formData.team1P2Id,
          team2P1Id: formData.team2P1Id,
          team2P2Id: formData.team2P2Id,
          team1Score: formData.team1Score,
          team2Score: formData.team2Score,
          round: formData.round,
          table: formData.table,
          isCasual: formData.isCasual,
        }),
      })

      if (!response.ok) {
        try {
          const data = await response.json()
          setError(data.error || "Failed to record match")
        } catch {
          setError(`Failed to record match: ${response.status} ${response.statusText}`)
        }
        setIsLoading(false)
        return
      }

      setSuccess("Match recorded successfully!")
      setIsLoading(false)

      // Reset form
      setFormData({
        team1P1Id: null,
        team1P2Id: null,
        team2P1Id: null,
        team2P2Id: null,
        team1Score: 0,
        team2Score: 0,
        round: formData.round,
        table: formData.table,
        isCasual: false,
      })

      // Refresh the page to show updated matches
      setTimeout(() => {
        router.refresh()
      }, 1000)
    } catch {
      setError("An error occurred. Please try again.")
      setIsLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="rounded-md bg-red-50 p-4">
          <div className="text-sm text-red-700">{error}</div>
        </div>
      )}
      {success && (
        <div className="rounded-md bg-green-50 p-4">
          <div className="text-sm text-green-700">{success}</div>
        </div>
      )}

      {/* Round and Table Selection */}
      <div className="grid grid-cols-2 gap-6">
        <div>
          <label htmlFor="round" className="block text-sm font-medium text-gray-700">
            Round
          </label>
          <input
            type="number"
            id="round"
            name="round"
            min="1"
            value={formData.round}
            onChange={handleChange}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
          />
        </div>

        <div>
          <label htmlFor="table" className="block text-sm font-medium text-gray-700">
            Table
          </label>
          <select
            id="table"
            name="table"
            value={formData.table}
            onChange={handleChange}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
          >
            {tables.map((table) => (
              <option key={table} value={table}>{table}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Team 1 */}
      <div className="border border-gray-200 rounded-lg p-4">
        <h3 className="text-lg font-medium text-gray-900 mb-4">Team 1 (Odds)</h3>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="team1P1Id" className="block text-sm font-medium text-gray-700">
              Player 1
            </label>
            {hasPrefilledPlayers ? (
              <p className="mt-1 text-sm text-gray-600 bg-gray-50 px-3 py-2 rounded-md">
                {players.find(p => p.id === prefilledP1)?.name || "Unknown Player"}
              </p>
            ) : (
              <select
                id="team1P1Id"
                name="team1P1Id"
                value={formData.team1P1Id || ""}
                onChange={handleChange}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
              >
                <option value="">Select player...</option>
                {players.map((player) => (
                  <option key={player.id} value={player.id}>{player.name}</option>
                ))}
              </select>
            )}
          </div>
          <div>
            <label htmlFor="team1P2Id" className="block text-sm font-medium text-gray-700">
              Player 2
            </label>
            {hasPrefilledPlayers ? (
              <p className="mt-1 text-sm text-gray-600 bg-gray-50 px-3 py-2 rounded-md">
                {players.find(p => p.id === prefilledP2)?.name || "Unknown Player"}
              </p>
            ) : (
              <select
                id="team1P2Id"
                name="team1P2Id"
                value={formData.team1P2Id || ""}
                onChange={handleChange}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
              >
                <option value="">Select player...</option>
                {players.map((player) => (
                  <option key={player.id} value={player.id}>{player.name}</option>
                ))}
              </select>
            )}
          </div>
        </div>
        <div className="mt-4">
          <label htmlFor="team1Score" className="block text-sm font-medium text-gray-700">
            Score
          </label>
          <input
            type="number"
            id="team1Score"
            name="team1Score"
            min="0"
            max="10"
            value={formData.team1Score}
            onChange={handleChange}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
          />
        </div>
      </div>

      {/* Team 2 */}
      <div className="border border-gray-200 rounded-lg p-4">
        <h3 className="text-lg font-medium text-gray-900 mb-4">Team 2 (Evens)</h3>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="team2P1Id" className="block text-sm font-medium text-gray-700">
              Player 1
            </label>
            {hasPrefilledPlayers ? (
              <p className="mt-1 text-sm text-gray-600 bg-gray-50 px-3 py-2 rounded-md">
                {players.find(p => p.id === prefilledP3)?.name || "Unknown Player"}
              </p>
            ) : (
              <select
                id="team2P1Id"
                name="team2P1Id"
                value={formData.team2P1Id || ""}
                onChange={handleChange}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
              >
                <option value="">Select player...</option>
                {players.map((player) => (
                  <option key={player.id} value={player.id}>{player.name}</option>
                ))}
              </select>
            )}
          </div>
          <div>
            <label htmlFor="team2P2Id" className="block text-sm font-medium text-gray-700">
              Player 2
            </label>
            {hasPrefilledPlayers ? (
              <p className="mt-1 text-sm text-gray-600 bg-gray-50 px-3 py-2 rounded-md">
                {players.find(p => p.id === prefilledP4)?.name || "Unknown Player"}
              </p>
            ) : (
              <select
                id="team2P2Id"
                name="team2P2Id"
                value={formData.team2P2Id || ""}
                onChange={handleChange}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
              >
                <option value="">Select player...</option>
                {players.map((player) => (
                  <option key={player.id} value={player.id}>{player.name}</option>
                ))}
              </select>
            )}
          </div>
        </div>
        <div className="mt-4">
          <label htmlFor="team2Score" className="block text-sm font-medium text-gray-700">
            Score
          </label>
          <input
            type="number"
            id="team2Score"
            name="team2Score"
            min="0"
            max="10"
            value={formData.team2Score}
            onChange={handleChange}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
          />
        </div>
      </div>

      <div className="flex items-center justify-between">
        <label className="flex items-center">
          <input
            type="checkbox"
            name="isCasual"
            checked={formData.isCasual}
            onChange={handleChange}
            className="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded"
          />
          <span className="ml-2 text-sm text-gray-700">Casual Match</span>
        </label>

        <button
          type="submit"
          disabled={isLoading}
          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"
        >
          {isLoading ? "Recording..." : "Record Match"}
        </button>
      </div>
    </form>
  )
}
