/**
 * 设置/修改密码弹窗
 * ================
 *
 * 首次设置密码：只需输入新密码 + 确认密码
 * 修改密码：需要输入旧密码 + 新密码 + 确认密码
 */

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

interface SetPasswordModalProps {
  open: boolean;
  hasPassword: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export default function SetPasswordModal({
  open,
  hasPassword,
  onClose,
  onSuccess,
}: SetPasswordModalProps) {
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [showOld, setShowOld] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  if (!open) {return null;}

  const canSubmit = () => {
    if (hasPassword && oldPassword.length < 6) {return false;}
    if (newPassword.length < 6) {return false;}
    if (newPassword !== confirmPassword) {return false;}
    if (submitting) {return false;}
    return true;
  };

  const handleSubmit = async () => {
    if (!canSubmit()) {return;}

    setSubmitting(true);
    try {
      const payload: { old_password?: string; new_password: string } = {
        new_password: newPassword,
      };
      if (hasPassword && oldPassword) {
        payload.old_password = oldPassword;
      }
      await client.post('/auth/set-password', payload);
      toast.success(hasPassword ? '密码修改成功' : '密码设置成功');
      // 清空表单
      setOldPassword('');
      setNewPassword('');
      setConfirmPassword('');
      onSuccess();
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : '操作失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };

  const handleClose = () => {
    setOldPassword('');
    setNewPassword('');
    setConfirmPassword('');
    setShowOld(false);
    setShowNew(false);
    setShowConfirm(false);
    onClose();
  };

  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 rowStyle: React.CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
  };

  const rowLabelStyle: React.CSSProperties = {
    fontSize: '13px',
    fontWeight: 500,
    color: 'var(--text-secondary)',
    width: '60px',
    flexShrink: 0,
    textAlign: 'right',
  };

  const rowInputWrapStyle: React.CSSProperties = {
    flex: 1,
    position: 'relative',
  };

  const errorStyle: React.CSSProperties = {
    fontSize: '12px',
    color: '#e74c3c',
    marginTop: '4px',
    height: '18px',
    lineHeight: '18px',
    overflow: 'hidden',
  };

  const pwdMismatch = confirmPassword.length > 0 && newPassword !== confirmPassword;
  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' }}>
            {hasPassword ? '修改密码' : '设置登录密码'}
          </h3>
          <p style={{ fontSize: '12px', color: 'var(--text-tertiary)', margin: 0 }}>
            {hasPassword ? '请输入旧密码和新密码' : '设置密码后可用密码登录'}
          </p>
        </div>

        {/* 表单 */}
        <div>
          {hasPassword && (
            <div style={fieldStyle}>
              <div style={rowStyle}>
                <label style={rowLabelStyle}>旧密码</label>
                <div style={rowInputWrapStyle}>
                  <input
                    type={showOld ? 'text' : 'password'}
                    placeholder="请输入旧密码"
                    value={oldPassword}
                    onChange={e => setOldPassword(e.target.value)}
                    style={inputStyle}
                    onKeyDown={e => { if (e.key === 'Enter') handleSubmit(); }}
                  />
                  <button
                    onClick={() => setShowOld(!showOld)}
                    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',
                    }}
                  >
                    {showOld ? (
                      <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>
              <div style={{ ...errorStyle, paddingLeft: '72px' }} />
            </div>
          )}

          <div style={fieldStyle}>
            <div style={rowStyle}>
              <label style={rowLabelStyle}>新密码</label>
              <div style={rowInputWrapStyle}>
                <input
                  type={showNew ? 'text' : 'password'}
                  placeholder="至少6位字符"
                  value={newPassword}
                  onChange={e => setNewPassword(e.target.value)}
                  style={inputStyle}
                  onKeyDown={e => { if (e.key === 'Enter') handleSubmit(); }}
                />
                <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>
            <div style={{ ...errorStyle, paddingLeft: '72px' }}>{pwdTooShort ? '密码至少需要6位' : ''}</div>
          </div>

          <div style={fieldStyle}>
            <div style={rowStyle}>
              <label style={rowLabelStyle}>确认密码</label>
              <div style={rowInputWrapStyle}>
                <input
                  type={showConfirm ? 'text' : 'password'}
                  placeholder="再次输入新密码"
                  value={confirmPassword}
                  onChange={e => setConfirmPassword(e.target.value)}
                  style={inputStyle}
                  onKeyDown={e => { if (e.key === 'Enter') handleSubmit(); }}
                />
                <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>
            <div style={{ ...errorStyle, paddingLeft: '72px' }}>{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>
  );
}
