'use client';
// /login — 登录页，按角色跳转首页（admin→/config, supervisor→/review, operator→/tasks/new）
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/stores/authStore';
import { api } from '@/lib/api';
import { LoginRequest, LoginResponse, ApiError } from '@/types/index';
import { getErrorAction } from '@/types/errors';

const INPUT_CLS = 'w-full border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange transition-colors';

export default function LoginPage() {
  const router = useRouter();
  const { login, role } = useAuthStore();
  const [form, setForm] = useState<LoginRequest>({ username: '', password: '' });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.username || !form.password) {
      setError('请填写用户名和密码');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const data = await api.post<LoginResponse>('/api/v1/auth/login', form);
      login(data.token, data.user);
      // 按角色跳对应首页
      const dest =
        data.user.role === 'admin'
          ? '/config'
          : data.user.role === 'supervisor'
          ? '/review'
          : '/tasks/new';
      router.replace(dest);
    } catch (err) {
      const apiErr = err as ApiError;
      const action = getErrorAction(apiErr?.code);
      setError(apiErr?.message || action.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex items-center justify-center min-h-screen bg-brand-cream">
      <div className="w-96 bg-surface-primary rounded-2xl shadow-lg p-8">
        <div className="text-center mb-8">
          <div className="text-4xl mb-2" aria-hidden="true">🌿</div>
          <h1 className="text-xl font-bold text-text-primary">龙石内容生产平台</h1>
          <p className="text-text-secondary text-sm mt-1">小红书内容工具</p>
        </div>

        <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-4">
          <div>
            <label htmlFor="username" className="block text-sm font-medium text-text-primary mb-1">用户名</label>
            <input id="username" type="text" autoComplete="username" value={form.username}
              onChange={(e) => setForm((f) => ({ ...f, username: e.target.value }))}
              className={INPUT_CLS} aria-required="true" />
          </div>

          <div>
            <label htmlFor="password" className="block text-sm font-medium text-text-primary mb-1">密码</label>
            <input id="password" type="password" autoComplete="current-password" value={form.password}
              onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
              className={INPUT_CLS} aria-required="true" />
          </div>

          {error && (
            <div role="alert" className="text-status-error text-sm bg-red-50 px-3 py-2 rounded-lg">
              {error}
            </div>
          )}

          <button type="submit" disabled={loading} aria-label="登录"
            className="w-full bg-brand-orange text-white rounded-lg py-2.5 text-sm font-medium hover:bg-orange-600 disabled:opacity-50 transition-colors"
          >
            {loading ? '登录中…' : '登录'}
          </button>
        </form>
      </div>
    </div>
  );
}
