'use client';

import Image from 'next/image';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useRef, useState } from 'react';

import { LanguageSwitcher } from '@/components/LanguageSwitcher';
import { buildFrontendHandoffUrl, login, withNext } from '@/lib/auth-client';
import { pickPortalText } from '@/lib/i18n/core';
import { usePortalI18n } from '@/lib/i18n/provider';

export default function LoginPage() {
  const { locale } = usePortalI18n();
  const searchParams = useSearchParams();
  const nextPath = searchParams?.get('next') || '/';

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const errorRef = useRef<HTMLDivElement>(null);

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLoading(true);
    setError('');

    try {
      const response = await login(username, password);
      window.location.replace(buildFrontendHandoffUrl(response, nextPath));
    } catch (err) {
      const rawMessage = err instanceof Error ? err.message : '';
      const friendlyMessage = /401|Invalid credentials|用户名或密码/.test(rawMessage)
        ? pickPortalText(locale, '用户名或密码错误，请检查后重试。', 'Username or password is incorrect. Please check and try again.')
        : pickPortalText(locale, '登录失败，请稍后重试。', 'Sign-in failed. Please try again.');
      setError(friendlyMessage);
      window.requestAnimationFrame(() => {
        errorRef.current?.focus();
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="portal-page">
      <div className="portal-toolbar">
        <LanguageSwitcher />
      </div>
      <section className="auth-page">
        <div className="portal-panel">
          <div className="auth-card login-card">
            <Image
              src="/boardware-logo.jpg"
              alt="Boardware logo"
              width={120}
              height={120}
              className="login-logo"
              priority
            />
            <h1>Beaver AgentSandbox</h1>

            <form className="auth-form" onSubmit={handleSubmit}>
              <div className="field login-field">
                <label className="login-field-label" htmlFor="username">{pickPortalText(locale, '用户名', 'Username')}</label>
                <UserIcon />
                <input
                  id="username"
                  value={username}
                  onChange={(event) => setUsername(event.target.value)}
                  autoComplete="username"
                  placeholder={pickPortalText(locale, '用户名', 'Username')}
                  required
                />
              </div>

              <div className="field login-field">
                <label className="login-field-label" htmlFor="password">{pickPortalText(locale, '密码', 'Password')}</label>
                <LockIcon />
                <input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(event) => setPassword(event.target.value)}
                  autoComplete="current-password"
                  placeholder={pickPortalText(locale, '输入密码', 'Enter password')}
                  required
                />
                <button
                  className="ghost-icon-button"
                  type="button"
                  onClick={() => setShowPassword((value) => !value)}
                  aria-label={pickPortalText(locale, showPassword ? '隐藏密码' : '显示密码', showPassword ? 'Hide password' : 'Show password')}
                >
                  <EyeIcon />
                </button>
              </div>

              <div
                ref={errorRef}
                className="error-text"
                role={error ? 'alert' : undefined}
                aria-live="polite"
                tabIndex={error ? -1 : undefined}
              >
                {error}
              </div>

              <button
                className="primary-button"
                type="submit"
                disabled={loading}
                aria-label={loading
                  ? pickPortalText(locale, '登录中', 'Signing in')
                  : pickPortalText(locale, '登录', 'Sign in')}
              >
                {loading
                  ? pickPortalText(locale, '登录中...', 'Signing in...')
                  : <ArrowRightIcon />}
              </button>
            </form>

            <div className="login-divider">
              <span>{pickPortalText(locale, '或', 'or')}</span>
            </div>

            <div className="auth-footer login-footer">
              <span>{pickPortalText(locale, '还没有账号？', "Don't have an account yet?")}</span>
              <Link href={withNext('/register', nextPath)}>{pickPortalText(locale, '注册', 'Create one')} <span aria-hidden="true">›</span></Link>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function UserIcon() {
  return (
    <svg className="field-icon" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M12 12.25a3.25 3.25 0 1 0 0-6.5 3.25 3.25 0 0 0 0 6.5Z" />
      <path d="M5.75 19.25a6.25 6.25 0 0 1 12.5 0" />
    </svg>
  );
}

function LockIcon() {
  return (
    <svg className="field-icon" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M7.25 10.25h9.5v8H7.25z" />
      <path d="M9 10.25V8a3 3 0 0 1 6 0v2.25" />
    </svg>
  );
}

function EyeIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path d="M3.75 12s2.8-5.25 8.25-5.25S20.25 12 20.25 12s-2.8 5.25-8.25 5.25S3.75 12 3.75 12Z" />
      <path d="m4.75 4.75 14.5 14.5" />
      <path d="M9.9 9.9a3 3 0 0 0 4.2 4.2" />
    </svg>
  );
}

function ArrowRightIcon() {
  return (
    <svg className="button-arrow" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M5 12h13" />
      <path d="m13 6 6 6-6 6" />
    </svg>
  );
}
