import React, { useState } from 'react';
import api from './api_client';

function Login({ onLoggedIn }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const res = await api.post('/api/auth/login', { email, password });
      const { token, user } = res.data;
      if (user.role !== 'SUPERADMIN') {
        setError('Only SUPERADMIN can use this panel.');
      } else {
        localStorage.setItem('gca_admin_token', token);
        localStorage.setItem('gca_admin_user', JSON.stringify(user));
        onLoggedIn();
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Login failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="layout-main" style={{ maxWidth: 420, margin: '40px auto' }}>
      <h1 className="page-title">SuperAdmin Login</h1>
      <p className="page-sub">Golden / Royal Control Panel</p>
      <form onSubmit={submit} style={{ marginTop: 16 }}>
        <div style={{ marginBottom: 10 }}>
          <label style={{ fontSize: 12 }}>Email</label>
          <input
            style={{ width: '100%', padding: 8, borderRadius: 999, border: '1px solid #444', marginTop: 4 }}
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </div>
        <div style={{ marginBottom: 10 }}>
          <label style={{ fontSize: 12 }}>Password</label>
          <input
            style={{ width: '100%', padding: 8, borderRadius: 999, border: '1px solid #444', marginTop: 4 }}
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </div>
        {error && <p style={{ color: '#ff4b6e', fontSize: 12 }}>{error}</p>}
        <button
          type="submit"
          style={{
            marginTop: 10,
            width: '100%',
            padding: 10,
            borderRadius: 999,
            border: 'none',
            background: 'linear-gradient(135deg,#f6d676,#c6a858,#a67c2d)',
            color: '#1a1206',
            fontWeight: 600,
            cursor: 'pointer',
          }}
        >
          {loading ? 'Logging in…' : 'Enter Royal Panel'}
        </button>
      </form>
      <p style={{ marginTop: 12, fontSize: 11, color: '#a39ac4' }}>
        Tip: call <code>/api/auth/bootstrap-superadmin</code> once to create your first SUPERADMIN.
      </p>
    </div>
  );
}

export default Login;
