import { Modal, Form, Button, Toast } from '@douyinfe/semi-ui';
import { useAuthStore } from '../../stores/useAuthStore';
import { useUIStore } from '../../stores/useUIStore';
import authService from '../../services/auth.service';

export default function PasswordModal() {
  const { updatePasswordModalVisible, setUpdatePasswordModalVisible } = useUIStore();
  const user = useAuthStore((s) => s.user);

  const handleSubmit = (values: {
    username: string;
    oldpassword: string;
    newpassword: string;
  }) => {
    authService
      .updatePassword(values.username, values.oldpassword, values.newpassword)
      .then(
        () => {
          Toast.success('密码修改成功');
          setUpdatePasswordModalVisible(false);
        },
        (error: unknown) => {
          const msg =
            error instanceof Error ? error.message : '修改失败，请重试';
          Toast.error(msg);
        },
      );
  };

  return (
    <Modal
      title="修改密码"
      visible={updatePasswordModalVisible}
      size="large"
      footer={null}
      onCancel={() => setUpdatePasswordModalVisible(false)}
      closeOnEsc
    >
      <div style={{ padding: 12, border: '1px solid var(--semi-color-border)', margin: 12 }}>
        <Form
          onSubmit={(values) =>
            handleSubmit(
              values as { username: string; oldpassword: string; newpassword: string },
            )
          }
          style={{ textAlign: 'center', width: 400 }}
          initValues={{ username: user?.username ?? '' }}
        >
          <Form.Input
            field="username"
            label="用户名"
            style={{ width: '100%' }}
            placeholder="请输入用户名"
          />
          <Form.Input
            mode="password"
            field="oldpassword"
            label="旧密码"
            style={{ width: '100%' }}
            placeholder="请输入旧密码"
          />
          <Form.Input
            mode="password"
            field="newpassword"
            label="新密码"
            style={{ width: '100%' }}
            placeholder="请输入新密码"
          />
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
            <Button htmlType="submit" type="tertiary">
              确认修改
            </Button>
          </div>
        </Form>
      </div>
    </Modal>
  );
}
