"use client"

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

// Interface for a single manual match entry
interface ManualMatchEntry {
  id: number
  round: string
  table: string
  team1P1: string
  team1P2: string
  team2P1: string
  team2P2: string
  team1Score: string
  team2Score: string
  isCasual: boolean
}

export default function UploadMatchesPage() {
  const router = useRouter()
  const [activeTab, setActiveTab] = useState<"csv" | "manual">("csv")
  
  // CSV Upload state
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [selectedTournament, setSelectedTournament] = useState<string>("")
  const [csvError, setCsvError] = useState("")
  const [csvSuccess, setCsvSuccess] = useState("")
  const [isCsvLoading, setIsCsvLoading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  
  // Manual Entry state
  const [manualTournament, setManualTournament] = useState<string>("")
  const [manualMatches, setManualMatches] = useState<ManualMatchEntry[]>([
    {
      id: Date.now(),
      round: "",
      table: "",
      team1P1: "",
      team1P2: "",
      team2P1: "",
      team2P2: "",
      team1Score: "",
      team2Score: "",
      isCasual: false,
    },
  ])
  const [manualError, setManualError] = useState("")
  const [manualSuccess, setManualSuccess] = useState("")
  const [isManualLoading, setIsManualLoading] = useState(false)
  
  // Player list for autocomplete
  const [players, setPlayers] = useState<{ id: number; name: string }[]>([])
  const [tournaments, setTournaments] = useState<{ id: number; name: string }[]>([])

  // Fetch tournaments and players on mount
  useEffect(() => {
    // Fetch tournaments
    fetch(`${window.location.origin}/api/tournaments`)
      .then((res) => res.json())
      .then((data) => {
        if (data.tournaments) {
          setTournaments(data.tournaments)
          if (data.tournaments.length > 0) {
            const recentId = data.tournaments[0].id.toString()
            setSelectedTournament(recentId)
            setManualTournament(recentId)
          }
        }
      })
      .catch((err) => console.error("Failed to fetch tournaments:", err))

    // Fetch players
    fetch(`${window.location.origin}/api/players`)
      .then((res) => res.json())
      .then((data) => {
        if (data.players) {
          setPlayers(data.players)
        }
      })
      .catch((err) => console.error("Failed to fetch players:", err))
  }, [])

  const createDefaultTournament = async (): Promise<{ id: number; name: string } | null> => {
    try {
      const response = await fetch(`${window.location.origin}/api/tournaments`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: `Tournament ${new Date().toLocaleDateString()}`,
          format: "round_robin",
          eventDate: new Date().toISOString(),
        }),
      })
      if (response.ok) {
        const data = await response.json()
        if (data.tournament) {
          const newTournaments = [data.tournament]
          setTournaments(newTournaments)
          setSelectedTournament(data.tournament.id.toString())
          setManualTournament(data.tournament.id.toString())
          return data.tournament
        }
      }
      return null
    } catch (err) {
      console.error("Failed to create default tournament:", err)
      return null
    }
  }

  // CSV Upload handlers
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      if (!file.name.endsWith(".csv")) {
        setCsvError("Please upload a CSV file")
        return
      }
      setSelectedFile(file)
      setCsvError("")
    }
  }

  const handleCsvSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setCsvError("")
    setCsvSuccess("")

    if (!selectedFile) {
      setCsvError("Please select a CSV file to upload")
      return
    }

    setIsCsvLoading(true)

    try {
      let tournamentId = selectedTournament
      
      // If no tournament is selected, create a default one
      if (!tournamentId) {
        const newTournament = await createDefaultTournament()
        if (newTournament) {
          tournamentId = newTournament.id.toString()
        } else {
          throw new Error("Failed to create default tournament")
        }
      }

      const formData = new FormData()
      formData.append("csvFile", selectedFile)
      formData.append("eventId", tournamentId)

      const response = await fetch(`${window.location.origin}/api/matches/upload`, {
        method: "POST",
        body: formData,
      })

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

      const data = await response.json()

      setCsvSuccess(
        `Successfully imported ${data.importedCount} matches. ` +
        `${data.errorCount || 0} errors occurred.` +
        (data.errors ? `\n\nErrors:\n${data.errors.join("\n")}` : "")
      )

      // Reset form
      setSelectedFile(null)
      if (fileInputRef.current) {
        fileInputRef.current.value = ""
      }
    } catch (err) {
      if (err instanceof Error) {
        setCsvError(err.message)
      } else {
        setCsvError("An unknown error occurred")
      }
    } finally {
      setIsCsvLoading(false)
    }
  }

  // Manual Entry handlers
  const addMatchEntry = () => {
    const newEntry: ManualMatchEntry = {
      id: Date.now(),
      round: "",
      table: "",
      team1P1: "",
      team1P2: "",
      team2P1: "",
      team2P2: "",
      team1Score: "",
      team2Score: "",
      isCasual: false,
    }
    setManualMatches([...manualMatches, newEntry])
  }

  const removeMatchEntry = (id: number) => {
    if (manualMatches.length > 1) {
      setManualMatches(manualMatches.filter((m) => m.id !== id))
    }
  }

  const updateMatchEntry = (id: number, field: keyof ManualMatchEntry, value: string | boolean) => {
    setManualMatches(
      manualMatches.map((m) => (m.id === id ? { ...m, [field]: value } : m))
    )
  }

  const handleManualSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setManualError("")
    setManualSuccess("")

    // Validate at least one match has required data
    const validMatches = manualMatches.filter(
      (m) =>
        m.team1P1 && m.team1P2 && m.team2P1 && m.team2P2 && m.team1Score && m.team2Score
    )

    if (validMatches.length === 0) {
      setManualError("Please enter at least one match with all player names and scores")
      return
    }

    setIsManualLoading(true)

    try {
      let tournamentId = manualTournament
      
      // If no tournament is selected, create a default one
      if (!tournamentId) {
        const newTournament = await createDefaultTournament()
        if (newTournament) {
          tournamentId = newTournament.id.toString()
        } else {
          throw new Error("Failed to create default tournament")
        }
      }

      const matchesData = validMatches.map((m) => ({
        eventId: parseInt(tournamentId),
        round: m.round ? parseInt(m.round) : undefined,
        table: m.table || undefined,
        team1P1Name: m.team1P1,
        team1P2Name: m.team1P2,
        team2P1Name: m.team2P1,
        team2P2Name: m.team2P2,
        team1Score: parseInt(m.team1Score),
        team2Score: parseInt(m.team2Score),
        isCasual: m.isCasual,
      }))

      const response = await fetch(`${window.location.origin}/api/matches/bulk`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ matches: matchesData }),
      })

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

      const data = await response.json()

      setManualSuccess(
        `Successfully created ${data.importedCount} matches. ` +
        `${data.errorCount || 0} errors occurred.` +
        (data.errors ? `\n\nErrors:\n${data.errors.join("\n")}` : "")
      )

      // Reset form
      setManualMatches([
        {
          id: Date.now(),
          round: "",
          table: "",
          team1P1: "",
          team1P2: "",
          team2P1: "",
          team2P2: "",
          team1Score: "",
          team2Score: "",
          isCasual: false,
        },
      ])
    } catch (err) {
      if (err instanceof Error) {
        setManualError(err.message)
      } else {
        setManualError("An unknown error occurred")
      }
    } finally {
      setIsManualLoading(false)
    }
  }

  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">
          <h1 className="text-3xl font-bold text-gray-900 mb-6">
            Upload Match Results
          </h1>

          {/* Tab Navigation */}
          <div className="border-b border-gray-200 mb-6">
            <nav className="-mb-px flex space-x-8">
              <button
                onClick={() => setActiveTab("csv")}
                className={`${
                  activeTab === "csv"
                    ? "border-green-500 text-green-600"
                    : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm`}
              >
                CSV Upload
              </button>
              <button
                onClick={() => setActiveTab("manual")}
                className={`${
                  activeTab === "manual"
                    ? "border-green-500 text-green-600"
                    : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm`}
              >
                Manual Entry
              </button>
            </nav>
          </div>

          <div className="bg-white shadow rounded-lg p-6">
            {/* CSV Upload Tab */}
            {activeTab === "csv" && (
              <form onSubmit={handleCsvSubmit} className="space-y-6">
                {csvError && (
                  <div className="rounded-md bg-red-50 p-4">
                    <div className="text-sm text-red-700 whitespace-pre-wrap">
                      {csvError}
                    </div>
                  </div>
                )}
                
                {csvSuccess && (
                  <div className="rounded-md bg-green-50 p-4">
                    <div className="text-sm text-green-700 whitespace-pre-wrap">
                      {csvSuccess}
                    </div>
                  </div>
                )}

                {/* Tournament Selection */}
                <div>
                  <label htmlFor="tournament" className="block text-sm font-medium text-gray-700">
                    Select Tournament *
                  </label>
                  <div className="mt-1 flex gap-2">
                    <select
                      id="tournament"
                      value={selectedTournament}
                      onChange={(e) => setSelectedTournament(e.target.value)}
                      className="flex-1 block border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
                    >
                      <option value="">Choose a tournament...</option>
                      {tournaments.map((tournament) => (
                        <option key={tournament.id} value={tournament.id}>
                          {tournament.name}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* File Upload */}
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    CSV File *
                  </label>
                  <div className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                    <div className="space-y-1 text-center">
                      <svg
                        className="mx-auto h-12 w-12 text-gray-400"
                        stroke="currentColor"
                        fill="none"
                        viewBox="0 0 48 48"
                        aria-hidden="true"
                      >
                        <path
                          d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                          strokeWidth={2}
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                      </svg>
                      <div className="flex text-sm text-gray-600">
                        <label
                          htmlFor="file-upload"
                          className="relative cursor-pointer bg-white rounded-md font-medium text-green-600 hover:text-green-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-green-500"
                        >
                          <span>Upload a file</span>
                          <input
                            id="file-upload"
                            name="file-upload"
                            type="file"
                            className="sr-only"
                            accept=".csv"
                            onChange={handleFileChange}
                            ref={fileInputRef}
                          />
                        </label>
                        <p className="pl-1">or drag and drop</p>
                      </div>
                      <p className="text-xs text-gray-500">
                        CSV file with match results
                      </p>
                      {selectedFile && (
                        <p className="text-sm text-green-600 mt-2">
                          Selected: {selectedFile.name}
                        </p>
                      )}
                    </div>
                  </div>
                </div>

                {/* CSV Format Guide */}
                <div className="bg-blue-50 rounded-md p-4">
                  <h3 className="text-sm font-medium text-blue-800 mb-2">
                    CSV Format Requirements
                  </h3>
                  <ul className="text-sm text-blue-700 space-y-1">
                    <li><strong>Event #:</strong> Tournament ID (optional if selected above)</li>
                    <li><strong>Round:</strong> Round number (1, 2, 3...)</li>
                    <li><strong>Table:</strong> Table name</li>
                    <li><strong>Seat 1:</strong> Player 1 name (Team 1)</li>
                    <li><strong>Seat 3:</strong> Player 2 name (Team 1)</li>
                    <li><strong>Odds Points:</strong> Score for Team 1</li>
                    <li><strong>Seat 2:</strong> Player 1 name (Team 2)</li>
                    <li><strong>Seat 4:</strong> Player 2 name (Team 2)</li>
                    <li><strong>Evens Points:</strong> Score for Team 2</li>
                  </ul>
                </div>

                {/* Submit Button */}
                <div className="flex justify-end">
                  <button
                    type="submit"
                    disabled={isCsvLoading}
                    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 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
                  >
                    {isCsvLoading ? "Uploading..." : "Upload CSV"}
                  </button>
                </div>
              </form>
            )}

            {/* Manual Entry Tab */}
            {activeTab === "manual" && (
              <form onSubmit={handleManualSubmit} className="space-y-6">
                {manualError && (
                  <div className="rounded-md bg-red-50 p-4">
                    <div className="text-sm text-red-700 whitespace-pre-wrap">
                      {manualError}
                    </div>
                  </div>
                )}
                
                {manualSuccess && (
                  <div className="rounded-md bg-green-50 p-4">
                    <div className="text-sm text-green-700 whitespace-pre-wrap">
                      {manualSuccess}
                    </div>
                  </div>
                )}

                {/* Tournament Selection */}
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Select Tournament *
                  </label>
                  <div className="mt-1 flex gap-2">
                    <select
                      value={manualTournament}
                      onChange={(e) => setManualTournament(e.target.value)}
                      className="flex-1 block border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
                    >
                      <option value="">Choose a tournament...</option>
                      {tournaments.map((tournament) => (
                        <option key={tournament.id} value={tournament.id}>
                          {tournament.name}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* Manual Match Entries */}
                <div className="space-y-6">
                  <div className="flex items-center justify-between">
                    <h3 className="text-lg font-medium text-gray-900">
                      Match Entries ({manualMatches.length})
                    </h3>
                    <button
                      type="button"
                      onClick={addMatchEntry}
                      className="px-3 py-1 text-sm bg-green-100 text-green-700 rounded-md hover:bg-green-200"
                    >
                      + Add Match
                    </button>
                  </div>

                  {manualMatches.map((match, index) => (
                    <div key={match.id} className="border border-gray-200 rounded-md p-4 space-y-4">
                      <div className="flex items-center justify-between">
                        <span className="font-medium text-gray-700">Match {index + 1}</span>
                        {manualMatches.length > 1 && (
                          <button
                            type="button"
                            onClick={() => removeMatchEntry(match.id)}
                            className="text-red-600 hover:text-red-800 text-sm"
                          >
                            Remove
                          </button>
                        )}
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        {/* Round and Table */}
                        <div>
                          <label className="block text-xs font-medium text-gray-500">
                            Round
                          </label>
                          <input
                            type="text"
                            value={match.round}
                            onChange={(e) => updateMatchEntry(match.id, "round", e.target.value)}
                            className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
                            placeholder="1"
                          />
                        </div>
                        <div>
                          <label className="block text-xs font-medium text-gray-500">
                            Table
                          </label>
                          <input
                            type="text"
                            value={match.table}
                            onChange={(e) => updateMatchEntry(match.id, "table", e.target.value)}
                            className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
                            placeholder="Table 1"
                          />
                        </div>
                      </div>

                      {/* Team 1 */}
                      <div className="bg-blue-50 rounded-md p-3 space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-xs font-medium text-blue-800">Team 1</span>
                          <input
                            type="number"
                            value={match.team1Score}
                            onChange={(e) => updateMatchEntry(match.id, "team1Score", e.target.value)}
                            className="w-16 text-center border border-blue-300 rounded py-1 px-2 text-sm"
                            placeholder="Score"
                            min="0"
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                          <input
                            type="text"
                            value={match.team1P1}
                            onChange={(e) => updateMatchEntry(match.id, "team1P1", e.target.value)}
                            list="players-list"
                            className="block w-full border border-blue-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                            placeholder="Player 1"
                          />
                          <input
                            type="text"
                            value={match.team1P2}
                            onChange={(e) => updateMatchEntry(match.id, "team1P2", e.target.value)}
                            list="players-list"
                            className="block w-full border border-blue-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                            placeholder="Player 2"
                          />
                        </div>
                      </div>

                      {/* Team 2 */}
                      <div className="bg-red-50 rounded-md p-3 space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-xs font-medium text-red-800">Team 2</span>
                          <input
                            type="number"
                            value={match.team2Score}
                            onChange={(e) => updateMatchEntry(match.id, "team2Score", e.target.value)}
                            className="w-16 text-center border border-red-300 rounded py-1 px-2 text-sm"
                            placeholder="Score"
                            min="0"
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                          <input
                            type="text"
                            value={match.team2P1}
                            onChange={(e) => updateMatchEntry(match.id, "team2P1", e.target.value)}
                            list="players-list"
                            className="block w-full border border-red-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-red-500 focus:border-red-500"
                            placeholder="Player 1"
                          />
                          <input
                            type="text"
                            value={match.team2P2}
                            onChange={(e) => updateMatchEntry(match.id, "team2P2", e.target.value)}
                            list="players-list"
                            className="block w-full border border-red-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-red-500 focus:border-red-500"
                            placeholder="Player 2"
                          />
                        </div>
                      </div>

                      {/* Casual Match Checkbox */}
                      <div className="flex items-center">
                        <input
                          id={`casual-${match.id}`}
                          type="checkbox"
                          checked={match.isCasual}
                          onChange={(e) => updateMatchEntry(match.id, "isCasual", e.target.checked)}
                          className="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded"
                        />
                        <label
                          htmlFor={`casual-${match.id}`}
                          className="ml-2 block text-sm text-gray-900"
                        >
                          Casual match (not part of a tournament)
                        </label>
                      </div>
                    </div>
                  ))}
                </div>

                {/* Player autocomplete datalist */}
                <datalist id="players-list">
                  {players.map((player) => (
                    <option key={player.id} value={player.name} />
                  ))}
                </datalist>

                {/* Submit Button */}
                <div className="flex justify-end pt-4 border-t">
                  <button
                    type="submit"
                    disabled={isManualLoading}
                    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 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
                  >
                    {isManualLoading ? "Creating Matches..." : "Create Matches"}
                  </button>
                </div>
              </form>
            )}

            {/* Back Button */}
            <div className="mt-4 flex justify-end">
              <button
                onClick={() => router.back()}
                className="text-green-600 hover:text-green-900"
              >
                ← Back
              </button>
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}
