import { useState, useEffect, useCallback } from 'react';
import { useAuthStore } from '../../store';
import { toast } from '../../store/uiStore';
import { client } from '../../api/client';
import TermsModal from '../../components/Modal/TermsModal';
import './Login.css';

/**
 * 登录页面
 *
 * 改进：
 * - 使用全局 authStore 替代局部的 onLoginSuccess 回调
 * - 使用新的 uiStore toast 方法
 */
export default function Login() {
  const { login, isLoading } = useAuthStore();
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [agreed, setAgreed] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [sending, setSending] = useState(false);
  const [logging, setLogging] = useState(false);
  const [termsOpen, setTermsOpen] = useState(false);
  const [termsTab, setTermsTab] = useState<'terms' | 'privacy'>('terms');

  // 倒计时逻辑（必须放在所有条件返回之前，遵循 Hooks 规则）
  useEffect(() => {
    if (countdown <= 0) {
      return;
    }
    const timer = setTimeout(() => setCountdown(c => c - 1), 1000);
    return () => clearTimeout(timer);
  }, [countdown]);

  // 手机号格式验证
  const isPhoneValid = /^1[3-9]\d{9}$/.test(phone);
  const isCodeValid = /^\d{4,6}$/.test(code);
  const canLogin = isPhoneValid && isCodeValid && agreed && !logging;

  // 发送验证码
  const handleSendCode = useCallback(async () => {
    if (!isPhoneValid || countdown > 0 || sending) {
      return;
    }
    setSending(true);
    try {
      await client.post('/auth/send-code', { mobile: phone });
      setCountdown(60);
      toast.success('验证码已发送');
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : '发送失败，请重试');
    } finally {
      setSending(false);
    }
  }, [isPhoneValid, countdown, sending, phone]);

  // 登录
  const handleLogin = async () => {
    if (!canLogin) {
      return;
    }

    setLogging(true);
    try {
      await login(phone, code);
      // 登录成功后 authStore 会自动更新全局状态
      // App.tsx 会检测到 isAuthenticated 变化并切换界面
      toast.success('登录成功');
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : '登录失败，请重试');
    } finally {
      setLogging(false);
    }
  };

  // 回车键登录
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && canLogin) {
      handleLogin();
    }
  };

  return (
    <div className="login-page">
      <div className="login-container">
        {/* 品牌 */}
        <div className="login-brand">
          <div className="login-logo">
            <img
              src="/assets/logo.png"
              alt="美家卡智影"
              style={{ width: 42, height: 36, objectFit: 'contain' }}
            />
            <span className="login-logo-text">美家卡智影</span>
          </div>
          <p className="login-subtitle">AI 驱动的智能视频创作平台</p>
        </div>

        {/* 登录卡片 */}
        <div className="login-card">
          <h2>欢迎登录</h2>
          <p className="login-card-desc">使用手机号验证码快速登录</p>

          {/* 加载状态 */}
          {isLoading ? (
            <div className="loading-state" style={{ padding: '40px 0', textAlign: 'center' }}>
              <svg
                width="32"
                height="32"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                style={{ animation: 'spin 1s linear infinite', marginBottom: 16 }}
              >
                <path d="M21 12a9 9 0 11-6.219-8.56" />
              </svg>
              <p>加载中...</p>
            </div>
          ) : (
            <div className="login-form" onKeyDown={handleKeyDown}>
            {/* 手机号 */}
            <div className="form-field">
              <label className="form-label">手机号</label>
              <div className="phone-input-group">
                <span className="phone-prefix">+86</span>
                <input
                  type="tel"
                  placeholder="请输入手机号"
                  value={phone}
                  onChange={e => {
                    const v = e.target.value.replace(/\D/g, '').slice(0, 11);
                    setPhone(v);
                  }}
                  maxLength={11}
                  autoFocus
                />
              </div>
            </div>

            {/* 验证码 */}
            <div className="form-field">
              <label className="form-label">验证码</label>
              <div className="code-input-group">
                <input
                  type="text"
                  placeholder="请输入验证码"
                  value={code}
                  onChange={e => {
                    const v = e.target.value.replace(/\D/g, '').slice(0, 6);
                    setCode(v);
                  }}
                  maxLength={6}
                />
                <button
                  className="send-code-btn"
                  onClick={handleSendCode}
                  disabled={!isPhoneValid || countdown > 0 || sending}
                >
                  {sending ? '发送中...' : countdown > 0 ? `${countdown}s 后重发` : '获取验证码'}
                </button>
              </div>
            </div>

            {/* 登录按钮 */}
            <button className="login-btn" onClick={handleLogin} disabled={!canLogin}>
              {logging ? (
                <span className="login-btn-loading">
                  <svg
                    width="18"
                    height="18"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    style={{ animation: 'spin 1s linear infinite' }}
                  >
                    <path d="M21 12a9 9 0 11-6.219-8.56" />
                  </svg>
                  登录中...
                </span>
              ) : (
                '登录'
              )}
            </button>

            {/* 协议 */}
            <div className="login-agreement">
              <input
                type="checkbox"
                id="agree-checkbox"
                checked={agreed}
                onChange={e => setAgreed(e.target.checked)}
              />
              <label htmlFor="agree-checkbox">
                我已阅读并同意
                <a href="#" onClick={e => { e.preventDefault(); setTermsTab('terms'); setTermsOpen(true); }}>
                  《用户服务协议》
                </a>
                和
                <a href="#" onClick={e => { e.preventDefault(); setTermsTab('privacy'); setTermsOpen(true); }}>
                  《隐私政策》
                </a>
              </label>
            </div>
          </div>
          )}
        </div>

        <div className="login-footer">meijiaka.cn</div>
      </div>

      <TermsModal
        open={termsOpen}
        defaultTab={termsTab}
        onClose={() => setTermsOpen(false)}
      />
    </div>
  );
}
