import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { authApi } from '../../api/endpoints';
import { ApiRequestError } from '../../api/client';
import { useAuthStore } from '../../store/authStore';
import { landingPathFor } from '../../lib/roleTrack';
import { Button } from '../../components/ui/Button';
import { LanguageSwitcher } from '../../components/ui/LanguageSwitcher';
import { InviteDialog } from './InviteDialog';
import { SignupDialog } from './SignupDialog';
import { ForgotPasswordDialog } from './ForgotPasswordDialog';
import { LoginSlides } from './LoginSlides';
import { OtpChallengePanel } from './OtpChallengePanel';
import type { LoginResponse } from '../../api/types';
import './login.css';

// v2.1.2 — 로그인 성공 시 메인 홈(SCR-HOME)으로 랜딩한다. 기존 '워크스페이스 선택' phase 는
// 제거하고 워크스페이스 선택은 SCR-HOME '내 행사' 섹션(WorkspaceGrid)으로 흡수했다.
type Phase = 'login' | 'otp';
type OtpMode = 'verify' | 'enroll';

// 아이디 기억 — 이메일만 저장(비번 저장 금지).
const REMEMBER_KEY = 'kintex_remember_email';

export function LoginPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const applyLogin = useAuthStore((s) => s.applyLogin);

  const [phase, setPhase] = useState<Phase>('login');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPw, setShowPw] = useState(false);
  const [remember, setRemember] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [signupOpen, setSignupOpen] = useState(false);
  const [forgotOpen, setForgotOpen] = useState(false);
  // 2FA 챌린지 — 1단계 성공 후 OTP 단계로 전환.
  const [otpChallenge, setOtpChallenge] = useState<{ token: string; mode: OtpMode } | null>(null);

  // 아이디 기억 프리필 — 저장된 이메일이 있으면 채우고 체크 유지.
  useEffect(() => {
    const saved = localStorage.getItem(REMEMBER_KEY);
    if (saved) {
      setEmail(saved);
      setRemember(true);
    }
  }, []);

  // 최종 로그인 확정(공통) — 토큰 적용 후 역할별 메인으로 랜딩(plan_role_routing §2-1).
  // ops·business=/home(회귀 0), admin→/admin, agency→/contractor/dashboard, visitor→/visitor.
  // 판정 불가 시 안전 폴백 /home. 회원가입 직후 흐름도 동일 경로를 공유한다.
  function completeLogin(res: LoginResponse) {
    if (remember) localStorage.setItem(REMEMBER_KEY, email.trim());
    else localStorage.removeItem(REMEMBER_KEY);
    applyLogin(res);
    setOtpChallenge(null);
    navigate(landingPathFor(res.user, res.workspaces));
  }

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      // 2FA/잠금 적용 1단계 — status 로 분기.
      const res = await authApi.secureLogin({ email, password });
      if (res.status === 'OK' && res.login) {
        completeLogin(res.login);
      } else if (res.challengeToken) {
        // OTP_REQUIRED(등록자 6자리) | OTP_ENROLL(미등록 등록 강제).
        setOtpChallenge({
          token: res.challengeToken,
          mode: res.status === 'OTP_ENROLL' ? 'enroll' : 'verify',
        });
        setPhase('otp');
      } else {
        setError(t('login.errResponse'));
      }
    } catch (err) {
      if (err instanceof ApiRequestError) {
        // 잠금·미구현·자격오류 등 코드별 안내(계정 존재 여부 미노출).
        if (err.code === 'ACCOUNT_LOCKED') {
          setError(t('login.errLocked'));
        } else if (err.code === 'NOT_IMPLEMENTED') {
          setError(t('login.errNotImpl'));
        } else {
          setError(err.message);
        }
      } else {
        setError(t('login.errGeneric'));
      }
    } finally {
      setSubmitting(false);
    }
  }

  if (phase === 'otp' && otpChallenge) {
    return (
      <div className="kx-login">
        <LoginSlides />
        <section className="kx-login__panel">
          <OtpChallengePanel
            challengeToken={otpChallenge.token}
            mode={otpChallenge.mode}
            onSuccess={completeLogin}
            onCancel={() => {
              setOtpChallenge(null);
              setPassword('');
              setError(null);
              setPhase('login');
            }}
          />
          <p className="kx-login__copy">{t('login.copyright')}</p>
        </section>
      </div>
    );
  }

  return (
    <div className="kx-login">
      {/* 좌측 55% 브랜드 패널 — 관리자 등록 슬라이드 캐러셀(페이드·5초·도트) */}
      <LoginSlides />

      {/* 우측 45% 로그인 카드 */}
      <section className="kx-login__panel">
        <div className="kx-login__topbar" style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <LanguageSwitcher variant="light" />
        </div>
        <div className="kx-login__card">
          <div className="kx-login__logo">
            <img
              className="kx-login__logo-img"
              src="/brand/kintex-wordmark.jpg"
              alt="KINTEX"
            />
            <span className="kx-login__logo-suffix">{t('common.appSuffix')}</span>
          </div>
          <p className="kx-login__prod">{t('login.prodTagline')}</p>
          <h2 className="kx-login__title">{t('login.title')}</h2>
          <p className="kx-login__title-sub">{t('login.sub')}</p>

          <form className="kx-login__form" onSubmit={handleLogin}>
            <div className="kx-field">
              <label htmlFor="email">{t('login.email')}</label>
              <input
                id="email"
                type="email"
                autoComplete="username"
                placeholder={t('login.emailPh')}
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>
            <div className="kx-field">
              <label htmlFor="password">{t('login.password')}</label>
              <div className="kx-field__pw">
                <input
                  id="password"
                  type={showPw ? 'text' : 'password'}
                  autoComplete="current-password"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                />
                <button
                  type="button"
                  className="kx-field__pw-toggle"
                  onClick={() => setShowPw((v) => !v)}
                  aria-label={showPw ? '비밀번호 숨기기' : '비밀번호 표시'}
                  aria-pressed={showPw}
                  tabIndex={-1}
                >
                  {showPw ? (
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                      <path d="M3 3l18 18" />
                      <path d="M10.6 10.6a2 2 0 0 0 2.8 2.8" />
                      <path d="M9.4 5.2A9.5 9.5 0 0 1 12 5c6 0 10 7 10 7a17.6 17.6 0 0 1-3 3.6" />
                      <path d="M6.1 6.7A17.4 17.4 0 0 0 2 12s4 7 10 7a9.3 9.3 0 0 0 3.6-.7" />
                    </svg>
                  ) : (
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                      <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z" />
                      <circle cx="12" cy="12" r="3" />
                    </svg>
                  )}
                </button>
              </div>
            </div>

            <div className="kx-login__row">
              <label className="kx-check" htmlFor="remember">
                <input
                  id="remember"
                  type="checkbox"
                  checked={remember}
                  onChange={(e) => setRemember(e.target.checked)}
                />
                <span>{t('login.remember')}</span>
              </label>
              <button
                type="button"
                className="kx-login__text-link"
                onClick={() => setForgotOpen(true)}
              >
                {t('login.forgot')}
              </button>
            </div>

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

            <Button type="submit" block disabled={submitting}>
              {submitting ? t('login.submitting') : t('login.submit')}
            </Button>
          </form>

          <p className="kx-login__signup-row">
            {t('login.signupPrompt')}{' '}
            <button
              type="button"
              className="kx-login__text-link"
              onClick={() => setSignupOpen(true)}
            >
              {t('login.signup')}
            </button>
          </p>

          <div className="kx-login__divider">
            <span>{t('login.or')}</span>
          </div>

          <Button variant="secondary" block leadingIcon="🪪" type="button">
            {t('login.internalLogin')}
          </Button>

          <button
            className="kx-login__invite-link"
            type="button"
            onClick={() => setInviteOpen(true)}
          >
            {t('login.inviteLink')}
          </button>
        </div>
        <p className="kx-login__copy">{t('login.copyright')}</p>
      </section>

      {inviteOpen && <InviteDialog onClose={() => setInviteOpen(false)} />}
      {signupOpen && (
        <SignupDialog
          defaultEmail={email}
          onClose={() => setSignupOpen(false)}
          onDone={(e) => {
            setSignupOpen(false);
            setEmail(e);
            setPassword('');
          }}
        />
      )}
      {forgotOpen && (
        <ForgotPasswordDialog
          defaultEmail={email}
          onClose={() => setForgotOpen(false)}
          onDone={(e) => {
            setForgotOpen(false);
            setEmail(e);
            setPassword('');
          }}
        />
      )}
    </div>
  );
}
