import { Form, Input, Button, Card, Typography } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import { useAuthStore } from '../../stores/auth';
import { changePassword } from '../../api/auth';
import { useNavigate } from 'react-router-dom';
import { useApiRequest } from '../../hooks/useApiRequest';

export default function ChangePassword() {
  const { execute } = useApiRequest();
  const logout = useAuthStore((s) => s.logout);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const onFinish = async (values: {
    current_password: string;
    new_password: string;
    confirm_password: string;
  }) => {
    if (values.new_password !== values.confirm_password) {
      return;
    }
    await execute(async () => {
      await changePassword(values.current_password, values.new_password);
      await logout();
      navigate('/login');
    }, '密码修改成功，请重新登录', '密码修改失败');
  };

  return (
    <Card style={{ maxWidth: 480, margin: '0 auto' }}>
      <Typography.Title level={4} style={{ marginBottom: 24 }}>修改密码</Typography.Title>
      <Form form={form} layout="vertical" onFinish={onFinish}>
        <Form.Item name="current_password" label="当前密码" rules={[{ required: true, message: '请输入当前密码' }]}>
          <Input.Password prefix={<LockOutlined />} placeholder="请输入当前密码" />
        </Form.Item>
        <Form.Item
          name="new_password" label="新密码"
          rules={[
            { required: true, message: '请输入新密码' },
            { min: 8, message: '密码长度不能少于8位' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('current_password') !== value) return Promise.resolve();
                return Promise.reject(new Error('新密码不能与当前密码相同'));
              },
            }),
          ]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="请输入新密码（至少8位）" />
        </Form.Item>
        <Form.Item
          name="confirm_password" label="确认新密码"
          rules={[
            { required: true, message: '请确认新密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('new_password') === value) return Promise.resolve();
                return Promise.reject(new Error('两次输入的密码不一致'));
              },
            }),
          ]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="请再次输入新密码" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" block>确认修改</Button>
        </Form.Item>
      </Form>
    </Card>
  );
}
