import { useState } from 'react';
import { Navigate, Route, Routes } from 'react-router-dom';
import { useAuth } from '../AuthContext';
import AdminLayout from '../admin/AdminLayout';
import AdminDashboard from '../admin/AdminDashboard';
import AdminCases from '../admin/AdminCases';
import AdminItems from '../admin/AdminItems';
import AdminCategories from '../admin/AdminCategories';
import AdminDrops from '../admin/AdminDrops';
import AdminPlayers from '../admin/AdminPlayers';
import AdminPrestigeServer from '../admin/AdminPrestigeServer';
import AdminShop from '../admin/AdminShop';

function AdminLogin() {
  const { adminLogin } = useAuth();
  const [username, setUsername] = useState('admin');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  const onSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setBusy(true);
    try {
      await adminLogin(username, password);
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="auth-page">
      <div className="auth-panel">
        <div className="brand">CaseOrion</div>
        <h1>Admin</h1>
        <p className="muted">Cases, items, categories, drops, players & overview.</p>
        <form className="form" onSubmit={onSubmit}>
          <label>
            Username
            <input value={username} onChange={(e) => setUsername(e.target.value)} required />
          </label>
          <label>
            Password
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </label>
          {error && <div className="error">{error}</div>}
          <button className="btn" type="submit" disabled={busy}>
            {busy ? 'Signing in…' : 'Admin login'}
          </button>
        </form>
      </div>
    </div>
  );
}

export default function Admin() {
  const { user, loading } = useAuth();

  if (loading) return <p className="muted" style={{ padding: '2rem' }}>Loading…</p>;
  if (!user || user.role !== 'admin') return <AdminLogin />;

  return (
    <Routes>
      <Route element={<AdminLayout />}>
        <Route index element={<AdminDashboard />} />
        <Route path="players" element={<AdminPlayers />} />
        <Route path="cases" element={<AdminCases />} />
        <Route path="items" element={<AdminItems />} />
        <Route path="categories" element={<AdminCategories />} />
        <Route path="drops" element={<AdminDrops />} />
        <Route path="prestige-server" element={<AdminPrestigeServer />} />
        <Route path="shop" element={<AdminShop />} />
        <Route path="*" element={<Navigate to="/admin" replace />} />
      </Route>
    </Routes>
  );
}
