import React, { useState } from 'react';
import axios from 'axios';

interface Team {
  name: string;
}

interface Group {
  name: string;
  teams: Team[];
}

export default function GroupsPage() {
  const [teamNames, setTeamNames] = useState<string[]>(Array(12).fill(""));
  const [groups, setGroups] = useState<Group[]>([]);

  const handleChange = (index: number, value: string) => {
    const newNames = [...teamNames];
    newNames[index] = value;
    setTeamNames(newNames);
  };

  const generateGroups = async () => {
    const response = await axios.post("http://localhost:8080/api/groups", teamNames.map(name => ({ name })));
    setGroups(response.data);
  };

  return (
    <div className="max-w-2xl mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">🏐 Volleyball Turnier</h1>

      <div className="grid grid-cols-2 gap-2">
        {teamNames.map((name, i) => (
          <input
            key={i}
            className="border p-2 rounded"
            placeholder={`Team ${i + 1}`}
            value={name}
            onChange={(e) => handleChange(i, e.target.value)}
          />
        ))}
      </div>

      <button
        className="bg-blue-600 text-white px-4 py-2 mt-4 rounded hover:bg-blue-700"
        onClick={generateGroups}
      >
        Gruppen erstellen
      </button>

      {groups.length > 0 && (
        <div className="mt-6">
          <h2 className="text-xl font-semibold mb-2">📦 Gruppeneinteilung</h2>
          {groups.map((group) => (
            <div key={group.name} className="mb-3">
              <h3 className="font-bold">Gruppe {group.name}</h3>
              <ul className="list-disc list-inside">
                {group.teams.map((team) => (
                  <li key={team.name}>{team.name}</li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
