import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import toast from 'react-hot-toast';

export default function Login() {
  const { login } = useAuth();
  const navigate = useNavigate();
  const [form, setForm] = useState({ username: '', password: '' });
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    if (!form.username || !form.password) return toast.error('Username dan password wajib diisi');
    setLoading(true);
    try {
      await login(form.username, form.password);
      toast.success('Login berhasil!');
      navigate('/');
    } catch {
      // error toast handled by api interceptor
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 via-orange-950 to-gray-900 flex items-center justify-center p-4">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <span className="text-6xl">🔧</span>
          <h1 className="mt-3 text-2xl font-bold text-white">Antang Garage Oli</h1>
          <p className="text-gray-400 text-sm mt-1">Point of Sale System</p>
        </div>

        <form onSubmit={handleSubmit} className="card p-6 space-y-4">
          <div>
            <label className="label text-gray-700">Username</label>
            <input
              className="input"
              placeholder="Masukkan username"
              value={form.username}
              onChange={e => setForm(p => ({ ...p, username: e.target.value }))}
              autoFocus
            />
          </div>
          <div>
            <label className="label text-gray-700">Password</label>
            <input
              type="password"
              className="input"
              placeholder="Masukkan password"
              value={form.password}
              onChange={e => setForm(p => ({ ...p, password: e.target.value }))}
            />
          </div>
          <button type="submit" disabled={loading} className="btn-primary w-full justify-center py-2.5">
            {loading ? 'Masuk...' : 'Masuk'}
          </button>
        </form>

        <p className="text-center text-gray-600 text-xs mt-4">© CV. Gurita Gemilang</p>
      </div>
    </div>
  );
}
