import { Link, useLocation } from 'react-router-dom';
import {  use, useEffect, useState } from 'react';
import { fetchTournaments, fetchTournament } from './api'; // Importiere die API-Funktion
import type { Tournament } from '../components/interfaces/types';

function useQuery() {
  return new URLSearchParams(useLocation().search);
}

export default function Tournament() {
  const query = useQuery();
  const type = query.get("type");
  const location = query.get("location");
  const [tournaments, setTournaments] = useState<Tournament[]>([]);
  const userId = localStorage.getItem('userId') || ''; 
  
  useEffect(() => {
    async function loadTournaments() {
      try {
        const tournaments = await fetchTournaments();
        setTournaments(tournaments);	
        console.log("Geladene Turniere:", tournaments);
      } catch (error) {
        console.error("Fehler beim Laden der Turniere:", error);
      }
    }

    loadTournaments();
  }, []);

  // Replace this with however you get the current user's id

  return (
    <div className="p-6">
      <h1 className="text-3xl font-bold mb-6">Meine Tourniere</h1>
      <div className="max-h-64 overflow-y-auto mb-6 border rounded p-4 bg-white shadow">
        <div className="flex justify-between items-center mb-4">
          <span className="font-semibold text-lg">Meine Turniere</span>
          <Link to="/tournament/new" className="px-3 py-1 border rounded bg-green-500 text-white">Neues Tournier erstellen</Link>

        </div>
        {tournaments.filter(t => t.organizerId === userId).length === 0 ? (
          <p className="text-gray-500">Du bist aktuell kein Organisator eines Turniers.</p>
        ) : (
          tournaments
            .filter(t => t.organizerId === userId)
            .map(t => (
              <div key={t.id} className="mb-4 last:mb-0 border-b pb-2">
          <div className="font-semibold">{t.name}</div>
          <div className="text-sm text-gray-600">{t.date instanceof Date ? t.date.toLocaleDateString() : t.date} – {t.location}</div>
              </div>
            ))
        )}
      </div>
      
      <h2 className="text-2xl font-bold mb-4">Turniere</h2>
      {type && <p>Gefiltert nach: <strong>{type}</strong></p>}
      {location && <p>Standort: <strong>{location}</strong></p>}
    </div>
  );
}
