import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Button, Input, Card, Alert } from '@dreamtree-org/twreact-ui';
import { useAppApi } from '@/lib/api';
import { setAuth } from '@rbac/permissions';

export default function Login() {
  const nav = useNavigate();
  const loc = useLocation();
  const { fetchApi, loading } = useAppApi();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [err, setErr] = useState('');

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    try {
      const res = await fetchApi('login', { email, password });
      setAuth((res && res.data) || res);
      nav((loc.state && loc.state.from) || '/', { replace: true });
    } catch (ex) {
      setErr((ex.response && ex.response.data && ex.response.data.error) || ex.message || 'Login failed');
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4 pt-safe pb-safe bg-[var(--app-bg)]">
      <Card className="w-full max-w-sm p-6 space-y-4">
        <h1 className="text-xl font-bold text-center text-primary-600">__APP_NAME__</h1>
        {err ? <Alert variant="error" title="Sign-in failed">{err}</Alert> : null}
        <form onSubmit={submit} className="space-y-4">
          <Input label="Email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
          <Input label="Password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
          <Button type="submit" fullWidth loading={loading}>Sign in</Button>
        </form>
      </Card>
    </div>
  );
}
