import { useEffect, useState } from 'react';
import { useUserStore } from '../stores/userStore';

export function SettingsPage() {
  const { users, activeUser, setActiveUser, fetchUsers, createUser, deleteUser } =
    useUserStore();
  const [newName, setNewName] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    const name = newName.trim();
    if (!name) return;
    setLoading(true);
    const user = await createUser(name);
    setLoading(false);
    if (user) setNewName('');
  }

  async function handleDelete(id: number) {
    await deleteUser(id);
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-gray-100">Einstellungen</h1>

      <section className="space-y-3">
        <h2 className="text-lg font-semibold text-gray-200">Nutzer</h2>

        <ul className="space-y-2">
          {users.map((user) => (
            <li
              key={user.id}
              className="flex items-center justify-between bg-gray-900 rounded-lg px-4 py-3"
            >
              <button
                onClick={() => setActiveUser(user)}
                className="flex items-center gap-3 flex-1 text-left"
              >
                <div
                  className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${
                    activeUser?.id === user.id
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-700 text-gray-300'
                  }`}
                >
                  {user.name.charAt(0).toUpperCase()}
                </div>
                <span className="text-gray-100">{user.name}</span>
                {activeUser?.id === user.id && (
                  <span className="text-xs text-blue-400 font-medium">Aktiv</span>
                )}
              </button>

              {users.length > 1 && (
                <button
                  onClick={() => handleDelete(user.id)}
                  className="p-2 text-gray-500 hover:text-red-400 transition-colors min-h-[44px] min-w-[44px] flex items-center justify-center"
                  title="Nutzer löschen"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </button>
              )}
            </li>
          ))}
        </ul>

        <form onSubmit={handleCreate} className="flex gap-2">
          <input
            type="text"
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            placeholder="Neuer Nutzername"
            maxLength={50}
            className="flex-1 bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-gray-100 placeholder-gray-500 focus:outline-none focus:border-blue-500 min-h-[44px]"
          />
          <button
            type="submit"
            disabled={loading || !newName.trim()}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white rounded-lg font-medium min-h-[44px] transition-colors"
          >
            Hinzufügen
          </button>
        </form>
      </section>
    </div>
  );
}
