import { useState, type FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import * as authApi from '../../api/auth';
import { ApiError } from '../../api/http';
import { DEFAULT_TENANT } from '../../config';
import { useAuth } from '../../context/AuthContext';
import * as permApi from '../../api/permission';

export function LoginPage() {
  const navigate = useNavigate();
  const { syncSession, refreshRoles } = useAuth();
  const [tenant, setTenant] = useState(
    () => localStorage.getItem('tenant_slug') ?? DEFAULT_TENANT,
  );
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      localStorage.setItem('tenant_slug', tenant);
      await authApi.login(tenant, email, password);
      syncSession();
      await refreshRoles();
      const me = await permApi.getMyPermissions();
      const admin = permApi.isAdminRole(me.roles ?? []);
      navigate(admin ? '/admin' : '/app');
    } catch (err) {
      setError(err instanceof ApiError ? err.message : '登入失敗');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-card">
      <h1>登入</h1>
      <form onSubmit={submit} className="form">
        <label>
          租戶
          <input value={tenant} onChange={(e) => setTenant(e.target.value)} />
        </label>
        <label>
          Email
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </label>
        <label>
          密碼
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </label>
        {error && <p className="form-error">{error}</p>}
        <button type="submit" className="btn-primary" disabled={loading}>
          {loading ? '登入中…' : '登入'}
        </button>
      </form>
      <p className="auth-footer">
        還沒有帳號？ <Link to="/register">註冊</Link>
      </p>
    </div>
  );
}
