'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useEffect, useState } from 'react';
import { safeReturnPath } from '@/lib/navigation/safe-return';
import { useAuthStore } from '@/stores/auth-store';

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const accessToken = useAuthStore((s) => s.accessToken);
  const login = useAuthStore((s) => s.login);
  const [mounted, setMounted] = useState(false);
  const [user, setUser] = useState('');
  const [pass, setPass] = useState('');
  const [tenant, setTenant] = useState('');
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted || !accessToken) {
      return;
    }
    const next = safeReturnPath(searchParams.get('from'), '/dashboard');
    router.replace(next);
  }, [mounted, accessToken, router, searchParams]);

  if (!mounted) {
    return (
      <main className="flex min-h-screen items-center justify-center text-sm text-neutral-500">
        加载中…
      </main>
    );
  }

  if (accessToken) {
    return (
      <main className="flex min-h-screen items-center justify-center text-sm text-neutral-500">
        正在进入后台…
      </main>
    );
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setErr(null);
    setLoading(true);
    try {
      await login(user, pass, tenant || undefined);
      const next = safeReturnPath(searchParams.get('from'), '/dashboard');
      router.replace(next);
    } catch (ex) {
      setErr(ex instanceof Error ? ex.message : String(ex));
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-6">
      <form
        onSubmit={onSubmit}
        className="w-full max-w-sm rounded-lg border border-neutral-200 bg-white p-6 shadow-sm"
      >
        <h1 className="text-lg font-medium">登录</h1>
        <label className="mt-4 block text-sm">
          <span className="text-neutral-600">用户名</span>
          <input
            className="mt-1 w-full rounded border border-neutral-300 px-2 py-1"
            value={user}
            onChange={(e) => setUser(e.target.value)}
            autoComplete="username"
            required
          />
        </label>
        <label className="mt-3 block text-sm">
          <span className="text-neutral-600">密码</span>
          <input
            type="password"
            className="mt-1 w-full rounded border border-neutral-300 px-2 py-1"
            value={pass}
            onChange={(e) => setPass(e.target.value)}
            autoComplete="current-password"
            required
          />
        </label>
        <label className="mt-3 block text-sm">
          <span className="text-neutral-600">租户 ID（可空）</span>
          <input
            className="mt-1 w-full rounded border border-neutral-300 px-2 py-1"
            value={tenant}
            onChange={(e) => setTenant(e.target.value)}
          />
        </label>
        {err ? <p className="mt-3 text-sm text-red-600">{err}</p> : null}
        <button
          type="submit"
          disabled={loading}
          className="mt-4 w-full rounded bg-neutral-900 py-2 text-white disabled:opacity-50"
        >
          {loading ? '提交中…' : '登录'}
        </button>
      </form>
      <Link href="/" className="text-sm text-blue-600">
        返回首页
      </Link>
    </main>
  );
}

export default function LoginPage() {
  return (
    <Suspense
      fallback={
        <main className="flex min-h-screen items-center justify-center text-sm text-neutral-500">
          加载中…
        </main>
      }
    >
      <LoginForm />
    </Suspense>
  );
}
