import { useEffect, useState } from 'react';
import { Form, Input, Modal, message } from 'antd';
import type { UpdateMyHqCredentialsRequest } from '@dukang/shared-types';
import { request, type HqProfile } from '../lib/api';

type Props = {
  open: boolean;
  profile: HqProfile | null;
  onClose: () => void;
  onUpdated: (profile: HqProfile) => void;
};

export function HqAccountSettingsModal({ open, profile, onClose, onUpdated }: Props) {
  const [form] = Form.useForm<UpdateMyHqCredentialsRequest & { confirmPassword?: string }>();
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open) return;
    form.setFieldsValue({
      loginName: profile?.loginName ?? '',
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    });
  }, [open, profile, form]);

  async function submit() {
    const values = await form.validateFields();
    if (values.newPassword && values.newPassword !== values.confirmPassword) {
      message.error('两次输入的新密码不一致');
      return;
    }
    const body: UpdateMyHqCredentialsRequest = {};
    const nextLogin = values.loginName?.trim();
    if (nextLogin && nextLogin !== (profile?.loginName ?? '')) {
      body.loginName = nextLogin;
    }
    if (values.newPassword?.trim()) {
      body.newPassword = values.newPassword.trim();
      if (values.oldPassword?.trim()) body.oldPassword = values.oldPassword.trim();
    }
    if (!body.loginName && !body.newPassword) {
      message.warning('请填写要修改的内容');
      return;
    }
    setSaving(true);
    try {
      await request('/admin/me/credentials', {
        method: 'PUT',
        body: JSON.stringify(body),
      });
      const updated = await request<HqProfile>('/admin/auth/me');
      message.success('账号信息已更新');
      onUpdated(updated);
      onClose();
    } catch (e) {
      message.error(e instanceof Error ? e.message : '保存失败');
    } finally {
      setSaving(false);
    }
  }

  return (
    <Modal
      title="账号设置"
      open={open}
      onCancel={onClose}
      onOk={() => void submit()}
      confirmLoading={saving}
      destroyOnClose
    >
      <Form form={form} layout="vertical">
        <Form.Item name="loginName" label="登录用户名" rules={[{ required: true, message: '请输入用户名' }]}>
          <Input autoComplete="username" placeholder="用于密码登录" />
        </Form.Item>
        <Form.Item name="oldPassword" label="当前密码" extra="已设置过密码时，修改密码必填">
          <Input.Password autoComplete="current-password" placeholder="不修改密码请留空" />
        </Form.Item>
        <Form.Item name="newPassword" label="新密码" rules={[{ min: 6, message: '至少 6 位' }]}>
          <Input.Password autoComplete="new-password" placeholder="不修改请留空" />
        </Form.Item>
        <Form.Item name="confirmPassword" label="确认新密码">
          <Input.Password autoComplete="new-password" placeholder="不修改请留空" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
