import { useEffect, useState } from 'react';
import { Outlet } from 'react-router-dom';
import { BottomNav, Sidebar } from './BottomNav';
import { ToastContainer } from './Toast';
import { useUserStore } from '../../stores/userStore';

function UserGate({ children }: { children: React.ReactNode }) {
  const { users, activeUser, setActiveUser, fetchUsers, createUser } = useUserStore();
  const [newName, setNewName] = useState('');
  const [loading, setLoading] = useState(false);
  const [fetched, setFetched] = useState(false);

  useEffect(() => {
    fetchUsers().then(() => setFetched(true));
  }, [fetchUsers]);

  if (!fetched) {
    return (
      <div className="min-h-screen bg-gray-950 flex items-center justify-center">
        <div className="text-gray-400">Laden…</div>
      </div>
    );
  }

  if (!activeUser) {
    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) setActiveUser(user);
    }

    return (
      <div className="min-h-screen bg-gray-950 flex items-center justify-center px-4">
        <div className="w-full max-w-sm space-y-6">
          <div className="text-center">
            <h1 className="text-3xl font-bold text-blue-500 mb-1">Krafttrainer</h1>
            <p className="text-gray-400">Wer trainiert heute?</p>
          </div>

          {users.length > 0 && (
            <ul className="space-y-2">
              {users.map((user) => (
                <li key={user.id}>
                  <button
                    onClick={() => setActiveUser(user)}
                    className="w-full flex items-center gap-3 bg-gray-900 hover:bg-gray-800 rounded-lg px-4 py-3 min-h-[56px] transition-colors text-left"
                  >
                    <div className="w-9 h-9 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-sm flex-shrink-0">
                      {user.name.charAt(0).toUpperCase()}
                    </div>
                    <span className="text-gray-100 font-medium">{user.name}</span>
                  </button>
                </li>
              ))}
            </ul>
          )}

          <form onSubmit={handleCreate} className="space-y-3">
            <p className="text-sm text-gray-400">
              {users.length === 0 ? 'Ersten Nutzer anlegen:' : 'Oder neuen Nutzer anlegen:'}
            </p>
            <div className="flex gap-2">
              <input
                type="text"
                value={newName}
                onChange={(e) => setNewName(e.target.value)}
                placeholder="Name"
                maxLength={50}
                autoFocus
                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"
              >
                Los
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}

export function PageShell() {
  return (
    <UserGate>
      <div className="flex min-h-screen">
        <Sidebar />
        <main className="flex-1 pb-20 md:pb-0">
          <div className="max-w-2xl mx-auto px-4 py-6">
            <Outlet />
          </div>
        </main>
        <BottomNav />
        <ToastContainer />
      </div>
    </UserGate>
  );
}
