import {Button, Flex, Form, Input} from "antd";
import {useEffect} from "react";

type FormFieldType = {
    oldPassword: string;
    newPassword: string;
    confirmNewPassword: string;
}

export interface IPasswordChangeProps {
    handleConfirm(data: FormFieldType): void;
}

export default function PasswordChange(props: IPasswordChangeProps) {

    const [form] = Form.useForm<FormFieldType>();

    useEffect(() => {
        form.setFieldsValue({
            oldPassword: '',
            newPassword: '',
            confirmNewPassword: '',
        })
    }, [])

    return (
        <Form
            layout="vertical"
            form={form}
            onFinish={(data) => {
                props.handleConfirm(data);
            }}
        >
            <Form.Item label="旧密码"
                       name="oldPassword"
                       rules={[{required: true, message: '请输入旧密码'}]}
            >
                <Input.Password placeholder="请输入旧密码"/>
            </Form.Item>
            <Form.Item label="新密码"
                       name="newPassword"
                       rules={[{required: true, message: '请输入新密码'}]}
            >
                <Input.Password placeholder="请输入新密码"/>
            </Form.Item>
            <Form.Item label="确认密码"
                       name="confirmNewPassword"
                       rules={[{required: true, message: '请输入确认密码'}, ({getFieldValue}) => ({
                           validator(_, value) {
                               if (!value || getFieldValue('newPassword') === value) {
                                   return Promise.resolve();
                               }
                               return Promise.reject(new Error('密码需要一致'));
                           }
                       })]}
            >
                <Input.Password placeholder="请输入确认密码"/>
            </Form.Item>
            <Form.Item wrapperCol={{span: 24}}>
                <Flex align="center" justify="center" gap="large">
                    <Button type="primary"
                            htmlType="submit"
                            style={{backgroundColor: 'var(--color-primary)'}}>
                        保存
                    </Button>
                </Flex>
            </Form.Item>
        </Form>
    )
}