import { useState } from 'react';
import { useTranslation, Trans } from 'react-i18next';
import { authApi } from '../../api/endpoints';
import { ApiRequestError } from '../../api/client';
import { Button } from '../../components/ui/Button';
import { evaluatePassword } from './passwordStrength';
import './login.css';

type Step = 'request' | 'reset' | 'done';

/**
 * 비밀번호 찾기/초기화 (SCR-01) — 2단계.
 *  ① 요청: 이메일 → POST /api/auth/password/forgot (사용자 열거 방지: 항상 성공 안내)
 *  ② 재설정: 이메일+인증코드+새 비밀번호 → POST /api/auth/password/reset
 * 스켈레톤(501/404)이면 "준비 중입니다" degraded 안내.
 */
export function ForgotPasswordDialog({
  onClose,
  onDone,
  defaultEmail = '',
}: {
  onClose: () => void;
  onDone: (email: string) => void;
  defaultEmail?: string;
}) {
  const { t } = useTranslation();
  const [step, setStep] = useState<Step>('request');
  const [email, setEmail] = useState(defaultEmail);
  const [code, setCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const hint = evaluatePassword(newPassword);

  function degradedMessage(err: ApiRequestError): string | null {
    if (err.code === 'NOT_IMPLEMENTED' || err.httpStatus === 404) {
      return t('forgot.errNotImpl');
    }
    return null;
  }

  async function requestCode(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      await authApi.forgotPassword({ email: email.trim() });
      setStep('reset');
    } catch (err) {
      if (err instanceof ApiRequestError) {
        setError(degradedMessage(err) ?? err.message);
      } else {
        setError(t('forgot.errRequest'));
      }
    } finally {
      setSubmitting(false);
    }
  }

  async function resetPassword(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      await authApi.resetPassword({
        email: email.trim(),
        code: code.trim(),
        newPassword,
      });
      setStep('done');
    } catch (err) {
      if (err instanceof ApiRequestError) {
        if (err.code === 'OTP_INVALID' || err.code === 'VALIDATION') {
          setError(t('forgot.errInvalid'));
        } else {
          setError(degradedMessage(err) ?? err.message);
        }
      } else {
        setError(t('forgot.errReset'));
      }
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="kx-modal" role="dialog" aria-modal="true" aria-labelledby="forgot-title">
      <div className="kx-modal__backdrop" onClick={onClose} />
      <div className="kx-modal__panel">
        {step === 'done' ? (
          <div className="kx-modal__blocked" role="status">
            <span className="kx-modal__blocked-icon kx-modal__ok-icon" aria-hidden="true">
              ✓
            </span>
            <h3 id="forgot-title">{t('forgot.doneTitle')}</h3>
            <p>{t('forgot.doneDesc')}</p>
            <div className="kx-modal__actions">
              <Button onClick={() => onDone(email.trim())}>{t('forgot.goLogin')}</Button>
            </div>
          </div>
        ) : step === 'request' ? (
          <form onSubmit={requestCode}>
            <h3 id="forgot-title" className="kx-modal__title">
              {t('forgot.requestTitle')}
            </h3>
            <p className="kx-modal__desc">{t('forgot.requestDesc')}</p>
            <div className="kx-field">
              <label htmlFor="fp-email">{t('forgot.email')}</label>
              <input
                id="fp-email"
                type="email"
                autoComplete="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={t('forgot.emailPh')}
                required
              />
            </div>
            {error && (
              <p className="kx-login__error" role="alert">
                {error}
              </p>
            )}
            <div className="kx-modal__actions">
              <Button variant="ghost" type="button" onClick={onClose}>
                {t('forgot.cancel')}
              </Button>
              <Button type="submit" disabled={submitting}>
                {submitting ? t('forgot.sending') : t('forgot.requestBtn')}
              </Button>
            </div>
          </form>
        ) : (
          <form onSubmit={resetPassword}>
            <h3 id="forgot-title" className="kx-modal__title">
              {t('forgot.resetTitle')}
            </h3>
            <p className="kx-modal__desc">
              <Trans i18nKey="forgot.resetDesc" values={{ email }} components={[<strong key="e" />]} />
            </p>
            <div className="kx-field">
              <label htmlFor="fp-code">{t('forgot.code')}</label>
              <input
                id="fp-code"
                inputMode="numeric"
                autoComplete="one-time-code"
                value={code}
                onChange={(e) => setCode(e.target.value)}
                placeholder={t('forgot.codePh')}
                required
              />
            </div>
            <div className="kx-field">
              <label htmlFor="fp-newpw">{t('forgot.newpw')}</label>
              <input
                id="fp-newpw"
                type="password"
                autoComplete="new-password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder={t('forgot.newpwPh')}
                aria-describedby="fp-pw-hint"
                required
              />
              <div className="kx-pw" id="fp-pw-hint" aria-live="polite">
                <div className={`kx-pw__bar kx-pw__bar--${hint.level}`}>
                  {[0, 1, 2].map((i) => (
                    <span key={i} className={i < hint.score ? 'is-on' : ''} />
                  ))}
                </div>
                {hint.label && <span className="kx-pw__label">{hint.label}</span>}
              </div>
            </div>
            {error && (
              <p className="kx-login__error" role="alert">
                {error}
              </p>
            )}
            <div className="kx-modal__actions">
              <Button variant="ghost" type="button" onClick={() => setStep('request')}>
                {t('forgot.prev')}
              </Button>
              <Button type="submit" disabled={submitting}>
                {submitting ? t('forgot.changing') : t('forgot.changeBtn')}
              </Button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
