"use client"

import { useState } from "react"

interface ScheduleGeneratorProps {
  tournamentId: number
  teamCount: number
}

export function ScheduleGenerator({ tournamentId, teamCount }: ScheduleGeneratorProps) {
  const [isGenerating, setIsGenerating] = useState(false)
  const [error, setError] = useState("")
  const [result, setResult] = useState<{
    roundsCreated: number
    matchupsCreated: number
  } | null>(null)

  const handleGenerate = async () => {
    setError("")
    setResult(null)
    setIsGenerating(true)

    try {
      const response = await fetch(`/api/tournaments/${tournamentId}/schedule`, {
        method: "POST",
      })

      // Check response status first before parsing JSON
      if (!response.ok) {
        try {
          const data = await response.json()
          setError(data.error || "Failed to generate schedule")
        } catch {
          setError(`Failed to generate schedule: ${response.status} ${response.statusText}`)
        }
        setIsGenerating(false)
        return
      }

      const data = await response.json()

      setResult({
        roundsCreated: data.roundsCreated,
        matchupsCreated: data.matchupsCreated,
      })
      setIsGenerating(false)

      // Reload to show the schedule
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    } catch {
      setError("An error occurred. Please try again.")
      setIsGenerating(false)
    }
  }

  const handleDelete = async () => {
    setError("")
    setIsGenerating(true)

    try {
      const response = await fetch(`/api/tournaments/${tournamentId}/schedule`, {
        method: "DELETE",
      })

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

      window.location.reload()
    } catch {
      setError("An error occurred. Please try again.")
      setIsGenerating(false)
    }
  }

  const expectedRounds = teamCount % 2 === 0 ? teamCount - 1 : teamCount
  const expectedMatchups = (teamCount * (teamCount - 1)) / 2

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

      {result && (
        <div className="rounded-md bg-green-50 p-4">
          <div className="text-sm text-green-700">
            Generated {result.roundsCreated} rounds with {result.matchupsCreated} matchups!
          </div>
        </div>
      )}

      <div className="bg-gray-50 rounded-lg p-4">
        <p className="text-sm text-gray-600 mb-2">
          Generate a round-robin schedule for <strong>{teamCount} teams</strong>.
        </p>
        <p className="text-sm text-gray-500">
          This will create {expectedRounds} rounds with {expectedMatchups} total matchups.
          Each team plays every other team exactly once.
        </p>
      </div>

      <div className="flex space-x-3">
        <button
          type="button"
          onClick={handleGenerate}
          disabled={isGenerating || teamCount < 2}
          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"
        >
          {isGenerating ? "Generating..." : "Generate Schedule"}
        </button>

        <button
          type="button"
          onClick={handleDelete}
          disabled={isGenerating}
          className="px-4 py-2 border border-red-300 rounded-md shadow-sm text-sm font-medium text-red-700 bg-white hover:bg-red-50 disabled:opacity-50"
        >
          Delete Schedule
        </button>
      </div>
    </div>
  )
}
