/**
 * 忘记密码弹窗 - 短信验证码重置密码
 * =================================
 *
 * 流程：手机号 → 验证码 → 新密码 → 确认密码
 */

import { useState, useEffect, useCallback } from 'react';
import './ConfirmModal.css';
import { client } from '../../api/client';
import { toast } from '../../store/uiStore';

interface ResetPasswordModalProps {
  open: boolean;
  onClose: () => void;
}

export default function ResetPasswordModal({ open, onClose }: ResetPasswordModalProps) {
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [countdown, setCountdown] = useState(0);
  const [sending, setSending] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  // 倒计时
  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 pwdMatch = newPassword === confirmPassword;
  const canSubmit = isPhoneValid && isCodeValid && newPassword.length >= 6 && pwdMatch && !submitting;

  // 发送验证码
  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 handleSubmit = async () => {
    if (!canSubmit) { return; }

    setSubmitting(true);
    try {
      await client.post('/auth/reset-password', {
        mobile: phone,
        code,
        new_password: newPassword,
      });
      toast.success('密码重置成功，请使用新密码登录');
      handleClose();
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : '重置失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };

  const handleClose = () => {
    setPhone('');
    setCode('');
    setNewPassword('');
    setConfirmPassword('');
    setCountdown(0);
    setShowNew(false);
    setShowConfirm(false);
    onClose();
  };

  if (!open) { return null; }

  const inputStyle: React.CSSProperties = {
    width: '100%',
    height: '44px',
    borderRadius: '8px',
    border: '1px solid var(--border-light)',
    padding: '0 12px',
    fontSize: '14px',
    background: 'var(--bg-input)',
    color: 'var(--text-primary)',
    outline: 'none',
    boxSizing: 'border-box',
    transition: 'border-color 0.15s ease',
  };

  const fieldStyle: React.CSSProperties = { marginBottom: '16px' };
  const labelStyle: React.CSSProperties = {
    display: 'block',
    fontSize: '13px',
    fontWeight: 500,
    color: 'var(--text-secondary)',
    marginBottom: '6px',
  };
  const errorStyle: React.CSSProperties = {
    fontSize: '12px',
    color: '#e74c3c',
    marginTop: '4px',
    height: '18px',
    lineHeight: '18px',
    overflow: 'hidden',
  };

  const pwdMismatch = confirmPassword.length > 0 && !pwdMatch;
  const pwdTooShort = newPassword.length > 0 && newPassword.length < 6;

  return (
    <div className="confirm-modal-overlay" onClick={handleClose}>
      <div
        className="confirm-modal-container"
        style={{ width: '100%', maxWidth: '380px', padding: '24px' }}
        onClick={e => e.stopPropagation()}
      >
        {/* 关闭按钮 */}
        <button className="confirm-modal-close" onClick={handleClose}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <line x1="18" y1="6" x2="6" y2="18" />
            <line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        </button>

        {/* 标题 */}
        <div style={{ textAlign: 'center', marginBottom: '20px' }}>
          <div
            className="confirm-modal-icon"
            style={{ color: 'var(--text-tertiary)', margin: '0 auto 12px' }}
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
              <path d="M7 11V7a5 5 0 0 1 10 0v4" />
            </svg>
          </div>
          <h3 className="confirm-modal-title" style={{ marginBottom: '4px' }}>重置密码</h3>
          <p style={{ fontSize: '12px', color: 'var(--text-tertiary)', margin: 0 }}>
            通过短信验证码重置登录密码
          </p>
        </div>

        {/* 表单 */}
        <div>
          {/* 手机号 */}
          <div style={fieldStyle}>
            <label style={labelStyle}>手机号</label>
            <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--border-light)', borderRadius: '8px', overflow: 'hidden', background: 'var(--bg-input)' }}>
              <span style={{ padding: '0 12px', fontSize: '14px', fontWeight: 600, color: 'var(--text-primary)', borderRight: '1px solid var(--border-light)', height: '44px', display: 'flex', alignItems: 'center', flexShrink: 0 }}>+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}
                style={{ border: 'none', background: 'transparent', flex: 1, height: '44px', padding: '0 12px', fontSize: '14px', fontWeight: 600, letterSpacing: '2px', outline: 'none', color: 'var(--text-primary)' }}
              />
            </div>
          </div>

          {/* 验证码 */}
          <div style={fieldStyle}>
            <label style={labelStyle}>验证码</label>
            <div style={{ display: 'flex', gap: '8px' }}>
              <input
                type="text"
                placeholder="请输入验证码"
                value={code}
                onChange={e => { const v = e.target.value.replace(/\D/g, '').slice(0, 6); setCode(v); }}
                maxLength={6}
                style={{ ...inputStyle, flex: 1, letterSpacing: '4px' }}
              />
              <button
                onClick={handleSendCode}
                disabled={!isPhoneValid || countdown > 0 || sending}
                style={{
                  flexShrink: 0,
                  height: '44px',
                  padding: '0 16px',
                  border: '1px solid var(--primary)',
                  borderRadius: '8px',
                  background: 'transparent',
                  color: (!isPhoneValid || countdown > 0 || sending) ? 'var(--text-tertiary)' : 'var(--primary)',
                  fontSize: '13px',
                  fontWeight: 500,
                  fontFamily: 'var(--font-family)',
                  cursor: (!isPhoneValid || countdown > 0 || sending) ? 'default' : 'pointer',
                  whiteSpace: 'nowrap',
                }}
              >
                {sending ? '发送中...' : countdown > 0 ? `${countdown}s 后重发` : '获取验证码'}
              </button>
            </div>
          </div>

          {/* 新密码 */}
          <div style={fieldStyle}>
            <label style={labelStyle}>新密码</label>
            <div style={{ position: 'relative' }}>
              <input
                type={showNew ? 'text' : 'password'}
                placeholder="至少6位字符"
                value={newPassword}
                onChange={e => setNewPassword(e.target.value)}
                style={inputStyle}
              />
              <button
                onClick={() => setShowNew(!showNew)}
                style={{
                  position: 'absolute',
                  right: '10px',
                  top: '50%',
                  transform: 'translateY(-50%)',
                  background: 'none',
                  border: 'none',
                  cursor: 'pointer',
                  color: 'var(--text-tertiary)',
                  padding: '4px',
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                {showNew ? (
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                    <circle cx="12" cy="12" r="3" />
                  </svg>
                ) : (
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                    <line x1="1" y1="1" x2="23" y2="23" />
                  </svg>
                )}
              </button>
            </div>
            <div style={errorStyle}>{pwdTooShort ? '密码至少需要6位' : ''}</div>
          </div>

          {/* 确认密码 */}
          <div style={fieldStyle}>
            <label style={labelStyle}>确认密码</label>
            <div style={{ position: 'relative' }}>
              <input
                type={showConfirm ? 'text' : 'password'}
                placeholder="再次输入新密码"
                value={confirmPassword}
                onChange={e => setConfirmPassword(e.target.value)}
                style={inputStyle}
              />
              <button
                onClick={() => setShowConfirm(!showConfirm)}
                style={{
                  position: 'absolute',
                  right: '10px',
                  top: '50%',
                  transform: 'translateY(-50%)',
                  background: 'none',
                  border: 'none',
                  cursor: 'pointer',
                  color: 'var(--text-tertiary)',
                  padding: '4px',
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                {showConfirm ? (
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                    <circle cx="12" cy="12" r="3" />
                  </svg>
                ) : (
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                    <line x1="1" y1="1" x2="23" y2="23" />
                  </svg>
                )}
              </button>
            </div>
            <div style={errorStyle}>{pwdMismatch ? '两次输入的密码不一致' : ''}</div>
          </div>
        </div>

        {/* 按钮 */}
        <div className="confirm-modal-actions" style={{ marginTop: '4px' }}>
          <button className="confirm-modal-btn cancel" onClick={handleClose}>
            取消
          </button>
          <button
            className="confirm-modal-btn primary"
            onClick={handleSubmit}
            disabled={!canSubmit}
          >
            {submitting ? (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: '6px' }}>
                <svg width="14" height="14" 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>
      </div>
    </div>
  );
}
