import { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { Icons } from '../components/icons/Icons';

export default function LoginPage() {
  const { login } = useAuth();
  const [user, setUser] = useState('');
  const [pass, setPass] = useState('');
  const [err, setErr] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async () => {
    if (!user || !pass) return setErr('Please enter username and password');
    try {
      setLoading(true);
      await login(user, pass);
    } catch (e) {
      setErr(e.response?.data?.error || 'Invalid credentials');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-bg flex items-center justify-center font-sans">
      <div className="bg-s1 border border-bd rounded-[10px] p-10 w-[380px] text-center">
        <div className="w-14 h-14 rounded-[14px] bg-gradient-to-br from-ac to-purple-600 flex items-center justify-center mx-auto mb-4 text-2xl">⬡</div>
        <h1 className="text-[22px] font-bold text-t1 mb-1">PeptideOS</h1>
        <p className="text-t2 text-[13px] mb-6">Sign in to manage your business</p>
        {err && (
          <div className="bg-rd/10 border border-rd/20 rounded-md px-3 py-2 mb-3.5 text-xs text-rd">
            {err}
          </div>
        )}
        <div className="mb-3">
          <input
            className="w-full p-2 bg-s2 border border-bd rounded-md text-t1 text-[13px] text-center focus:border-ac outline-none"
            placeholder="Username"
            value={user}
            onChange={(e) => { setUser(e.target.value); setErr(''); }}
            onKeyDown={(e) => e.key === 'Enter' && submit()}
          />
        </div>
        <div className="mb-5">
          <input
            type="password"
            className="w-full p-2 bg-s2 border border-bd rounded-md text-t1 text-[13px] text-center focus:border-ac outline-none"
            placeholder="Password"
            value={pass}
            onChange={(e) => { setPass(e.target.value); setErr(''); }}
            onKeyDown={(e) => e.key === 'Enter' && submit()}
          />
        </div>
        <button
          className="bg-ac text-white w-full py-2.5 rounded-md text-sm font-semibold flex items-center justify-center gap-2 hover:bg-ac/90 disabled:opacity-50"
          onClick={submit}
          disabled={loading}
        >
          <Icons.Lock /> {loading ? 'Signing in...' : 'Sign In'}
        </button>
        <p className="text-t3 text-[10px] mt-4">Default: admin / admin</p>
      </div>
    </div>
  );
}
