// ============================================================
// ChangePasswordModal — 修改密码弹窗（已登录用户）
//
// 场景：已登录用户通过旧密码验证后设置新密码
// 复用：可在设置页"修改密码"入口使用，也可在其他位置独立调用
//
// API：
//   - AuthAPI.changePassword({ current_password, new_password })
// ============================================================

import { useState, useCallback } from 'react';
import { logger } from '@/shared/utils/bus';
import { Modal, Input, Button, Typography, App } from 'antd';
import { LockOutlined, KeyOutlined, SafetyOutlined } from '@ant-design/icons';

import { useTheme } from '@/app/providers/ThemeProvider';
import { AuthAPI } from '@/modules/auth/controllers/auth-api';
import { validatePassword, validateConfirmPassword, runFieldChecks } from '../../settings/validators';

const { Text, Title } = Typography;

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

export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) {
   const { isDark } = useTheme();
   const { message } = App.useApp();

   // ---- 表单字段 ----
   const [currentPassword, setCurrentPassword] = useState('');
   const [newPassword, setNewPassword] = useState('');
   const [confirmPassword, setConfirmPassword] = useState('');

   // ---- 错误信息 ----
   const [errors, setErrors] = useState<Record<string, string>>({});

   // ---- 提交状态 ----
   const [submitting, setSubmitting] = useState(false);

   // ---- 清除单个字段错误 ----
   const clearError = useCallback((name: string) => {
      setErrors((p) => {
         if (!(name in p)) return p;
         const n = { ...p };
         delete n[name];
         return n;
      });
   }, []);

   // ---- 提交 ----
   const handleSubmit = useCallback(async () => {
      if (runFieldChecks(setErrors,
         { field: 'currentPassword', error: !currentPassword ? '请输入当前密码' : null },
         { field: 'newPassword',     error: validatePassword(newPassword) },
         { field: 'confirmPassword', error: validateConfirmPassword(confirmPassword, newPassword) },
      )) return;

      setSubmitting(true);
      try {
         await AuthAPI.changePassword({
            current_password: currentPassword,
            new_password: newPassword,
         });
         message.success('密码修改成功');
         // 重置表单
         setCurrentPassword('');
         setNewPassword('');
         setConfirmPassword('');
         onClose();
      } catch (err) {
         logger.warn('auth', '密码修改失败', err instanceof Error ? err : undefined);
         message.error((err as Error).message || '密码修改失败');
      } finally {
         setSubmitting(false);
      }
   }, [currentPassword, newPassword, confirmPassword, onClose, message]);

   // ---- 关闭时重置错误 ----
   const handleClose = useCallback(() => {
      setErrors({});
      onClose();
   }, [onClose]);

   return (
      <Modal
         open={open}
         onCancel={handleClose}
         footer={null}
         width={440}
         centered
         destroyOnHidden={true}
         mask={{ closable: false }}
         styles={{
            body: {
               padding: '24px 32px 16px',
               background: isDark ? '#1A1730' : '#FFFFFF',
            },
         }}
      >
         {/* 标题 */}
         <div className="text-center mb-5">
            <Title level={5} className="!mb-1 gradient-primary-text">
               修改密码
            </Title>
            <Text type="secondary" className="text-xs">
               请输入当前密码并设置新密码
            </Text>
         </div>

         {/* 表单 */}
         <div className="space-y-4">
            {/* 当前密码 */}
            <div>
               <Input.Password
                  size="large"
                  prefix={<SafetyOutlined className="opacity-40" />}
                  placeholder="当前密码"
                  value={currentPassword}
                  onChange={(e) => {
                     setCurrentPassword(e.target.value);
                     clearError('currentPassword');
                  }}
                  status={errors.currentPassword ? 'error' : undefined}
                  allowClear
               />
               {errors.currentPassword && (
                  <Text type="danger" className="text-xs ml-1">
                     {errors.currentPassword}
                  </Text>
               )}
            </div>

            {/* 新密码 */}
            <div>
               <Input.Password
                  size="large"
                  prefix={<LockOutlined className="opacity-40" />}
                  placeholder="新密码（6~128位）"
                  value={newPassword}
                  onChange={(e) => {
                     setNewPassword(e.target.value);
                     clearError('newPassword');
                  }}
                  status={errors.newPassword ? 'error' : undefined}
                  allowClear
               />
               {errors.newPassword && (
                  <Text type="danger" className="text-xs ml-1">
                     {errors.newPassword}
                  </Text>
               )}
            </div>

            {/* 确认新密码 */}
            <div>
               <Input.Password
                  size="large"
                  prefix={<KeyOutlined className="opacity-40" />}
                  placeholder="请再次输入新密码"
                  value={confirmPassword}
                  onChange={(e) => {
                     setConfirmPassword(e.target.value);
                     clearError('confirmPassword');
                  }}
                  status={errors.confirmPassword ? 'error' : undefined}
                  allowClear
               />
               {errors.confirmPassword && (
                  <Text type="danger" className="text-xs ml-1">
                     {errors.confirmPassword}
                  </Text>
               )}
            </div>

            {/* 提交按钮 */}
            <Button
               type="primary"
               block
               size="large"
               loading={submitting}
               onClick={handleSubmit}
               className="h-11! text-base! font-medium! mt-2!"
            >
               确认修改
            </Button>
         </div>
      </Modal>
   );
}
