import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth';
import { useAppStore } from '@/stores/app';
import { useI18n } from '@/i18n';

export default function LoginPage() {
  const navigate = useNavigate();
  const { t } = useI18n();
  const { login, mfaRequired, mfaSetup, totpUri, user } = useAuthStore();
  const { loadData } = useAppStore();

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [totp, setTotp] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  if (user) {
    navigate('/chat', { replace: true });
    return null;
  }

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const res = await login(username, password, totp || undefined);
      if (!res.mfa_required && res.token) {
        await loadData();
        navigate('/chat', { replace: true });
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : t('login.error'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex items-center justify-center h-screen" style={{ background: 'var(--bg)' }}>
      <div className="w-[380px] p-8 rounded-2xl" style={{ background: 'var(--bg1)', boxShadow: 'var(--sh3)', border: '1px solid var(--bd)' }}>

        {/* Logo */}
        <div className="flex flex-col items-center mb-6">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width={52} height={52}>
            <rect x="2" y="5" width="32" height="26" rx="13" ry="13" fill="rgba(199,70,52,0.08)" stroke="#C74634" strokeWidth="1.8" />
            <rect x="11" y="11" width="14" height="14" rx="4" fill="#fff" stroke="#C74634" strokeWidth="0.4" />
            <circle cx="15" cy="17" r="2" fill="#C74634" />
            <circle cx="21" cy="17" r="2" fill="#C74634" />
            <circle cx="15" cy="16.7" r="0.7" fill="#fff" />
            <circle cx="21" cy="16.7" r="0.7" fill="#fff" />
            <rect x="14" y="21" width="8" height="1.5" rx="0.75" fill="#C74634" opacity="0.6" />
          </svg>
          <h1 className="text-lg font-bold mt-3" style={{ color: 'var(--t1)' }}>AI Agent</h1>
          <p className="text-xs mt-1" style={{ color: 'var(--t3)' }}>{t('login.subtitle')}</p>
        </div>

        <form onSubmit={handleSubmit} className="flex flex-col gap-3">
          {!mfaRequired ? (
            <>
              <input
                type="text"
                placeholder={t('login.userPlaceholder')}
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                className="w-full px-3 py-2.5 rounded-lg text-sm outline-none"
                style={{ background: 'var(--bg2)', border: '1px solid var(--bd)', color: 'var(--t1)' }}
                autoFocus
              />
              <input
                type="password"
                placeholder={t('login.passPlaceholder')}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full px-3 py-2.5 rounded-lg text-sm outline-none"
                style={{ background: 'var(--bg2)', border: '1px solid var(--bd)', color: 'var(--t1)' }}
              />
            </>
          ) : (
            <>
              {mfaSetup && totpUri && (
                <div className="text-center mb-2">
                  <p className="text-xs mb-2" style={{ color: 'var(--t3)' }}>
                    {t('login.mfaScanQr')}
                  </p>
                  <img
                    src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(totpUri)}`}
                    alt="QR Code"
                    className="mx-auto rounded-lg"
                    width={180}
                    height={180}
                  />
                </div>
              )}
              <input
                type="text"
                placeholder={t('login.totpPlaceholder')}
                value={totp}
                onChange={(e) => setTotp(e.target.value)}
                className="w-full px-3 py-2.5 rounded-lg text-sm outline-none text-center tracking-[.3em]"
                style={{ background: 'var(--bg2)', border: '1px solid var(--bd)', color: 'var(--t1)', fontFamily: 'var(--fm)' }}
                maxLength={6}
                autoFocus
              />
            </>
          )}

          {error && (
            <div className="text-xs px-3 py-2 rounded-lg" style={{ background: 'var(--rdl)', color: 'var(--rd)' }}>
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            className="w-full py-2.5 rounded-lg text-sm font-semibold text-white transition-colors disabled:opacity-60"
            style={{ background: 'var(--ac)' }}
          >
            {loading ? t('login.loading') : mfaRequired ? t('login.verify') : t('login.submit')}
          </button>
        </form>
      </div>
    </div>
  );
}
