'use client';

import { useEffect, useId, useRef, useState, type FormEvent } from 'react';
import { PASSWORD_MIN_LENGTH } from '@/app/config/app';
import type { AuthForm } from '@/app/hooks/useAuth';
import { useT } from './ContentProvider';
import { SpinnerIcon } from './icons';
import { cx } from './ui';

interface AuthDialogProps {
  initialMode: 'signin' | 'signup';
  /** Resolves to an error message to show, or null when it worked (the dialog is then closed by the parent). */
  onSubmit: (mode: 'signin' | 'signup', form: AuthForm) => Promise<string | null>;
  onClose: () => void;
}

const FIELD = 'h-10 w-full rounded-[10px] border border-edge-input bg-surface px-3 text-[15px] text-ink outline-none transition-[border-color] placeholder:text-placeholder focus:border-accent/60';

export function AuthDialog({ initialMode, onSubmit, onClose }: AuthDialogProps) {
  const t = useT();
  const [mode, setMode] = useState(initialMode);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [displayName, setDisplayName] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const firstField = useRef<HTMLInputElement>(null);
  const titleId = useId();
  const signup = mode === 'signup';

  useEffect(() => {
    firstField.current?.focus();
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    if (busy) return;
    setBusy(true);
    setError(null);
    const problem = await onSubmit(mode, { email, password, displayName });
    if (problem === null) onClose(); else { setError(problem); setBusy(false); }
  };

  const switchMode = (next: typeof mode) => { setMode(next); setError(null); };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink/40 p-4" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <form
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        onSubmit={submit}
        className="w-full max-w-[380px] rounded-2xl border border-edge-strong bg-surface p-6 [box-shadow:var(--shadow-input)]"
      >
        <h2 id={titleId} className="m-0 text-[20px] font-semibold text-ink">{signup ? t('copy.signUp') : t('copy.signIn')}</h2>
        <p className="mt-1 mb-4 text-[14px] text-muted">
          {signup ? t('auth.noteSignUp') : t('auth.noteSignIn')}
        </p>

        <div className="flex flex-col gap-2.5">
          {signup && (
            <input className={FIELD} type="text" placeholder={t('auth.namePlaceholder')} autoComplete="name" maxLength={100} value={displayName} onChange={e => setDisplayName(e.target.value)} />
          )}
          <input ref={firstField} className={FIELD} type="email" placeholder={t('auth.emailPlaceholder')} autoComplete="email" required value={email} onChange={e => setEmail(e.target.value)} />
          <input
            className={FIELD}
            type="password"
            placeholder={signup ? t('auth.newPasswordPlaceholder', { min: PASSWORD_MIN_LENGTH }) : t('auth.passwordPlaceholder')}
            autoComplete={signup ? 'new-password' : 'current-password'}
            required
            minLength={signup ? PASSWORD_MIN_LENGTH : undefined}
            value={password}
            onChange={e => setPassword(e.target.value)}
          />
        </div>

        <p role="alert" className={cx('mt-3 mb-0 min-h-[20px] text-[13px] text-danger', !error && 'invisible')}>{error ?? ' '}</p>

        <button
          type="submit"
          disabled={busy}
          className="mt-1 flex h-10 w-full cursor-pointer items-center justify-center gap-2 rounded-[10px] border-0 bg-brand text-[15px] font-semibold text-white transition-opacity disabled:cursor-wait disabled:opacity-60"
        >
          {busy && <SpinnerIcon size={14} />}
          {signup ? t('copy.signUp') : t('copy.signIn')}
        </button>

        <p className="mt-4 mb-0 text-center text-[14px] text-muted">
          {signup ? t('auth.haveAccount') : t('auth.newHere')}
          <button type="button" onClick={() => switchMode(signup ? 'signin' : 'signup')} className="cursor-pointer border-0 bg-transparent p-0 text-[14px] font-medium text-accent">
            {signup ? t('copy.signIn') : t('copy.signUp')}
          </button>
        </p>
      </form>
    </div>
  );
}
