import { useState } from 'react';
import { useNavigate, useLocation, Navigate } from 'react-router-dom';
import { Network } from 'lucide-react';
import { useAuth } from '../auth';
import { Btn, Field, inputCls } from '../components/ui';

export default function Login() {
  const { user, login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  if (user) {
    const from = location.state?.from?.pathname || '/';
    return <Navigate to={from} replace />;
  }

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      await login(username, password);
      navigate('/', { replace: true });
    } catch (err) {
      setError(err.message || 'Inloggen mislukt');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-full flex items-center justify-center p-4 bg-bg">
      <div className="w-full max-w-sm">
        <div className="flex flex-col items-center mb-8">
          <div className="w-14 h-14 rounded-2xl bg-accent-soft flex items-center justify-center glow-accent mb-4">
            <Network className="w-7 h-7 text-accent" />
          </div>
          <h1 className="text-xl font-bold tracking-tight">Mek-Tech</h1>
          <p className="text-[13px] text-muted mt-1">AI Consultancy & Data Engineering</p>
        </div>

        <form onSubmit={submit} className="bg-card border border-border-soft rounded-xl p-6 space-y-4">
          {error && (
            <div className="bg-red/10 border border-red/30 rounded-lg px-3 py-2 text-[13px] text-red">
              {error}
            </div>
          )}
          <Field label="Gebruikersnaam">
            <input
              className={inputCls}
              value={username}
              onChange={e => setUsername(e.target.value)}
              autoComplete="username"
              autoFocus
              required
            />
          </Field>
          <Field label="Wachtwoord">
            <input
              type="password"
              className={inputCls}
              value={password}
              onChange={e => setPassword(e.target.value)}
              autoComplete="current-password"
              required
            />
          </Field>
          <Btn type="submit" loading={loading} className="w-full" size="lg">
            Inloggen
          </Btn>
        </form>

        <p className="text-center text-[11px] text-muted mt-6">Mek-Tech v3.0 — React Edition</p>
      </div>
    </div>
  );
}
