import { useState } from 'react';
import { useTranslation } 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';

/**
 * 회원가입 (SCR-01) — 이메일·이름·비밀번호(+확인)·회사명(선택)·초대코드(선택).
 * POST /api/auth/register → 성공 시 상태 안내(활성/승인대기) 후 로그인 유도.
 * 스켈레톤(501/404)이면 "준비 중입니다" degraded 안내.
 */
export function SignupDialog({
  onClose,
  onDone,
  defaultEmail = '',
}: {
  onClose: () => void;
  /** 회원가입 성공 후 로그인 화면으로 되돌아가며 이메일 프리필 */
  onDone: (email: string) => void;
  defaultEmail?: string;
}) {
  const { t } = useTranslation();
  const [email, setEmail] = useState(defaultEmail);
  const [displayName, setDisplayName] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [companyName, setCompanyName] = useState('');
  const [inviteCode, setInviteCode] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const hint = evaluatePassword(password);
  const mismatch = confirm.length > 0 && password !== confirm;

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (password !== confirm) {
      setError(t('signup.mismatch'));
      return;
    }
    setSubmitting(true);
    try {
      const res = await authApi.register({
        email: email.trim(),
        displayName: displayName.trim(),
        password,
        companyName: companyName.trim() || undefined,
        inviteCode: inviteCode.trim() || undefined,
      });
      const pending = res?.status && res.status !== 'ACTIVE';
      setNotice(
        res?.message ?? (pending ? t('signup.noticePending') : t('signup.noticeActive')),
      );
    } catch (err) {
      if (err instanceof ApiRequestError) {
        if (err.code === 'NOT_IMPLEMENTED' || err.httpStatus === 404) {
          setError(t('signup.errNotImpl'));
        } else if (err.code === 'CONFLICT') {
          setError(t('signup.errConflict'));
        } else {
          setError(err.message);
        }
      } else {
        setError(t('signup.errGeneric'));
      }
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="kx-modal" role="dialog" aria-modal="true" aria-labelledby="signup-title">
      <div className="kx-modal__backdrop" onClick={onClose} />
      <div className="kx-modal__panel">
        {notice ? (
          <div className="kx-modal__blocked" role="status">
            <span className="kx-modal__blocked-icon kx-modal__ok-icon" aria-hidden="true">
              ✓
            </span>
            <h3 id="signup-title">{t('signup.doneTitle')}</h3>
            <p>{notice}</p>
            <div className="kx-modal__actions">
              <Button onClick={() => onDone(email.trim())}>{t('signup.goLogin')}</Button>
            </div>
          </div>
        ) : (
          <form onSubmit={submit}>
            <h3 id="signup-title" className="kx-modal__title">
              {t('signup.title')}
            </h3>
            <p className="kx-modal__desc">{t('signup.desc')}</p>

            <div className="kx-field">
              <label htmlFor="su-email">{t('signup.email')}</label>
              <input
                id="su-email"
                type="email"
                autoComplete="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={t('signup.emailPh')}
                required
              />
            </div>
            <div className="kx-field">
              <label htmlFor="su-name">{t('signup.name')}</label>
              <input
                id="su-name"
                autoComplete="name"
                value={displayName}
                onChange={(e) => setDisplayName(e.target.value)}
                placeholder={t('signup.namePh')}
                required
              />
            </div>
            <div className="kx-field">
              <label htmlFor="su-pw">{t('signup.password')}</label>
              <input
                id="su-pw"
                type="password"
                autoComplete="new-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={t('signup.passwordPh')}
                aria-describedby="su-pw-hint"
                required
              />
              <div className="kx-pw" id="su-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>
            <div className="kx-field">
              <label htmlFor="su-pw2">{t('signup.password2')}</label>
              <input
                id="su-pw2"
                type="password"
                autoComplete="new-password"
                value={confirm}
                onChange={(e) => setConfirm(e.target.value)}
                placeholder={t('signup.password2Ph')}
                aria-invalid={mismatch}
                required
              />
              {mismatch && (
                <span className="kx-pw__label kx-pw__label--error">{t('signup.mismatch')}</span>
              )}
            </div>
            <div className="kx-field">
              <label htmlFor="su-company">{t('signup.company')}</label>
              <input
                id="su-company"
                autoComplete="organization"
                value={companyName}
                onChange={(e) => setCompanyName(e.target.value)}
                placeholder={t('signup.companyPh')}
              />
            </div>
            <div className="kx-field">
              <label htmlFor="su-invite">{t('signup.invite')}</label>
              <input
                id="su-invite"
                value={inviteCode}
                onChange={(e) => setInviteCode(e.target.value)}
                placeholder={t('signup.invitePh')}
              />
            </div>

            {error && (
              <p className="kx-login__error" role="alert">
                {error}
              </p>
            )}

            <div className="kx-modal__actions">
              <Button variant="ghost" type="button" onClick={onClose}>
                {t('signup.cancel')}
              </Button>
              <Button type="submit" disabled={submitting || mismatch}>
                {submitting ? t('signup.submitting') : t('signup.submit')}
              </Button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
