'use client';

import type { FormEvent } from 'react';
import { Suspense, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { AnimatedLoginCharacters, type LoginCharacterMood } from '@/components/login/AnimatedLoginCharacters';
import { OasisCanvas } from '@/components/login/OasisCanvas';

type LoginStatus = 'idle' | 'loading' | 'success';

function Icon({
  type,
  className = 'h-4 w-4',
}: {
  type: 'user' | 'lock' | 'eye' | 'eyeOff' | 'arrow' | 'check';
  className?: string;
}) {
  const common = {
    className,
    width: 16,
    height: 16,
    viewBox: '0 0 24 24',
    fill: 'none',
    stroke: 'currentColor',
    strokeWidth: 2.2,
    strokeLinecap: 'round' as const,
    strokeLinejoin: 'round' as const,
  };
  if (type === 'user') return <svg {...common}><path d="M20 21a8 8 0 0 0-16 0" /><circle cx="12" cy="7" r="4" /></svg>;
  if (type === 'lock') return <svg {...common}><rect x="5" y="11" width="14" height="10" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></svg>;
  if (type === 'eye') return <svg {...common}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" /><circle cx="12" cy="12" r="3" /></svg>;
  if (type === 'eyeOff') return <svg {...common}><path d="m3 3 18 18" /><path d="M10.6 10.6A3 3 0 0 0 13.4 13.4" /><path d="M9.9 5.2A10.7 10.7 0 0 1 12 5c6.5 0 10 7 10 7a18 18 0 0 1-3.2 4.3" /><path d="M6.4 6.5C3.5 8.3 2 12 2 12s3.5 7 10 7c1.3 0 2.5-.3 3.6-.7" /></svg>;
  if (type === 'check') return <svg {...common}><path d="M20 6 9 17l-5-5" /></svg>;
  return <svg {...common}><path d="M5 12h14" /><path d="m13 6 6 6-6 6" /></svg>;
}

function LoginInner() {
  const searchParams = useSearchParams();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [showPassword, setShowPassword] = useState(false);
  const [activeField, setActiveField] = useState<'username' | 'password' | null>(null);
  const [hasError, setHasError] = useState(false);
  const [status, setStatus] = useState<LoginStatus>('idle');
  const [eyeOffset, setEyeOffset] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const onPointerMove = (event: PointerEvent) => {
      const centerX = window.innerWidth / 2;
      const centerY = window.innerHeight / 2;
      const nextX = Math.max(-1, Math.min(1, (event.clientX - centerX) / centerX));
      const nextY = Math.max(-1, Math.min(1, (event.clientY - centerY) / centerY));
      setEyeOffset({ x: nextX * 8, y: nextY * 5.5 });
    };
    window.addEventListener('pointermove', onPointerMove);
    return () => window.removeEventListener('pointermove', onPointerMove);
  }, []);

  const disabled = status === 'loading' || status === 'success';
  const mood: LoginCharacterMood = useMemo(() => {
    if (status === 'success') return 'success';
    if (hasError) return 'error';
    if (showPassword && activeField === 'password') return 'peek';
    if (activeField || username || password) return 'typing';
    return 'idle';
  }, [activeField, hasError, password, showPassword, status, username]);

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setHasError(false);
    if (!username.trim() || !password) {
      setHasError(true);
      return;
    }

    setStatus('loading');
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password, remember }),
      });
      if (!res.ok) throw new Error();
      setStatus('success');
      const next = searchParams.get('next') || '/';
      window.setTimeout(() => { window.location.href = next.startsWith('/') ? next : '/'; }, 350);
    } catch {
      setStatus('idle');
      setHasError(true);
    }
  }

  return (
    <main className="login-page login-page--oasis login-page--source relative min-h-screen overflow-hidden text-white">
      <OasisCanvas />
      <div className="login-oasis-shade" />
      <div className="login-source-overlay">
        <section className="login-auth-panel login-source-auth-panel login-source-combo-panel rounded-[8px]">
          <div className="login-top-brand" aria-hidden="true">
            <span className="login-top-brand__logo login-top-brand__wordmark">AI Toy Patent</span>
            <span className="login-top-brand__system">玩具 IP 工作台</span>
          </div>
          <div className="login-source-character-strip" aria-hidden="true">
            <AnimatedLoginCharacters mood={mood} eyeOffset={eyeOffset} />
          </div>

          <form className="login-source-form-pane w-full" onSubmit={onSubmit}>
            <div className="space-y-3">
              <label className="block">
                <span className="flex h-11 items-center gap-3 rounded-[8px] border border-white/10 bg-black/25 px-3 text-white transition focus-within:border-[#d6b36a] focus-within:bg-black/35 focus-within:ring-2 focus-within:ring-[#d6b36a]/25">
                  <Icon type="user" className="h-4 w-4 text-white/45" />
                  <input
                    className="h-full min-w-0 flex-1 bg-transparent text-base text-white outline-none placeholder:text-white/30"
                    value={username}
                    disabled={disabled}
                    autoComplete="username"
                    aria-label="账号"
                    onFocus={() => setActiveField('username')}
                    onBlur={() => setActiveField(null)}
                    onChange={event => {
                      setUsername(event.target.value);
                      if (hasError) setHasError(false);
                    }}
                  />
                </span>
              </label>

              <label className="block">
                <span className="flex h-11 items-center gap-3 rounded-[8px] border border-white/10 bg-black/25 px-3 text-white transition focus-within:border-[#d6b36a] focus-within:bg-black/35 focus-within:ring-2 focus-within:ring-[#d6b36a]/25">
                  <Icon type="lock" className="h-4 w-4 text-white/45" />
                  <input
                    className="h-full min-w-0 flex-1 bg-transparent text-base text-white outline-none placeholder:text-white/30"
                    value={password}
                    disabled={disabled}
                    type={showPassword ? 'text' : 'password'}
                    autoComplete="current-password"
                    aria-label="密码"
                    onFocus={() => setActiveField('password')}
                    onBlur={() => setActiveField(null)}
                    onChange={event => {
                      setPassword(event.target.value);
                      if (hasError) setHasError(false);
                    }}
                  />
                  <button
                    className="grid h-9 w-9 place-items-center rounded-[8px] text-white/55 transition hover:bg-white/10 hover:text-white focus:outline-none focus:ring-2 focus:ring-[#d6b36a]/45 disabled:opacity-50"
                    type="button"
                    disabled={disabled}
                    onMouseDown={event => event.preventDefault()}
                    onClick={() => setShowPassword(value => !value)}
                    aria-label={showPassword ? '隐藏密码' : '显示密码'}
                  >
                    <Icon type={showPassword ? 'eyeOff' : 'eye'} className="h-4 w-4" />
                  </button>
                </span>
              </label>
            </div>

            <label className="mt-3 flex cursor-pointer items-center gap-2 text-sm text-white/60">
              <input
                className="h-4 w-4 rounded border-white/20 bg-black/30 accent-[#c89b3c]"
                type="checkbox"
                checked={remember}
                disabled={disabled}
                onChange={event => setRemember(event.target.checked)}
              />
              <span>保持登录</span>
            </label>

            {status === 'success' ? (
              <div className="mt-3">
                <div className="inline-flex h-9 w-9 items-center justify-center rounded-[8px] border border-emerald-300/30 bg-emerald-400/10 text-emerald-100">
                  <Icon type="check" className="h-4 w-4" />
                </div>
              </div>
            ) : null}

            <button
              className="mt-4 flex h-11 w-full items-center justify-center gap-2 rounded-[8px] bg-white px-4 text-base font-semibold text-black shadow-xl shadow-black/25 transition hover:bg-[#f5efe3] focus:outline-none focus:ring-2 focus:ring-[#d6b36a]/60 disabled:cursor-wait disabled:opacity-70"
              type="submit"
              disabled={disabled}
              aria-label={status === 'loading' ? '验证中' : '进入'}
            >
              <Icon type="arrow" className="h-4 w-4" />
            </button>
          </form>
        </section>
      </div>
    </main>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginInner />
    </Suspense>
  );
}
