"use client"

import { useState } from "react"

interface ScheduleGeneratorProps {
  tournamentId: number
  teamCount: number
  existingRounds?: number
}

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

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

    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 handleGenerateClick = () => {
    if (existingRounds && existingRounds > 0) {
      setShowOverwriteConfirm(true)
    } else {
      handleGenerate()
    }
  }

  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>

      {/* Overwrite Confirmation */}
      {showOverwriteConfirm && (
        <div className="rounded-md bg-yellow-50 p-4 mb-4">
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <svg className="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
                <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3 flex-1">
              <h3 className="text-sm font-medium text-yellow-800">
                Overwrite existing schedule?
              </h3>
              <div className="mt-2 text-sm text-yellow-700">
                <p>A schedule with {existingRounds} round(s) already exists. This will delete the existing schedule and create a new one.</p>
              </div>
              <div className="mt-4 flex space-x-3">
                <button
                  type="button"
                  onClick={handleGenerate}
                  disabled={isGenerating}
                  className="px-3 py-1.5 bg-yellow-600 text-white text-sm rounded-md hover:bg-yellow-700 disabled:opacity-50"
                >
                  {isGenerating ? "Overwriting..." : "Yes, Overwrite"}
                </button>
                <button
                  type="button"
                  onClick={() => setShowOverwriteConfirm(false)}
                  disabled={isGenerating}
                  className="px-3 py-1.5 bg-gray-300 text-gray-700 text-sm rounded-md hover:bg-gray-400 disabled:opacity-50"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="flex space-x-3">
        <button
          type="button"
          onClick={handleGenerateClick}
          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..." : (existingRounds && existingRounds > 0 ? "Regenerate Schedule" : "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>
  )
}
