import TreeSelectedGroup from '@/components/shared/TreeSelectedGroup';
import { ModalForm, ProFormItem } from '@ant-design/pro-form';
import { useIntl } from '@umijs/max';
import { Alert, Form } from 'antd';

interface ModalTreeSelectGroupProps {
  visible: boolean;
  onModalVisible: (visible: boolean) => void;
  onSubmit: (groupId: string) => Promise<boolean | void>;
}

interface FormValues {
  group_id?: string;
}

const ModalTreeSelectGroup: React.FC<ModalTreeSelectGroupProps> = ({
  visible,
  onSubmit,
  onModalVisible,
}) => {
  const intl = useIntl();
  const [form] = Form.useForm<FormValues>();

  return (
    <ModalForm<FormValues>
      form={form}
      title={intl.formatMessage({
        id: 'pages.groups.setgroup.title',
        defaultMessage: 'Set group',
      })}
      width="480px"
      open={visible} // ⚠️ dùng open, không dùng visible (antd mới)
      onOpenChange={onModalVisible} // ⚠️ thay cho onVisibleChange
      onFinish={async (values) => {
        const groupId = values.group_id;

        if (!groupId) {
          return false; // không cho submit nếu chưa chọn
        }

        await onSubmit(groupId);
        return true;
      }}
    >
      <Alert
        type="warning"
        message={intl.formatMessage({
          id: 'pages.groups.select.alert',
          defaultMessage: 'The thing is only added to the leaf group',
        })}
      />

      <br />

      <ProFormItem
        name="group_id"
        rules={[{ required: true, message: 'Please select a group' }]}
      >
        <TreeSelectedGroup
          groupIds={form.getFieldValue('group_id')}
          onSelected={(value) => {
            form.setFieldsValue({
              group_id: value as string,
            });
          }}
        />
      </ProFormItem>
    </ModalForm>
  );
};

export default ModalTreeSelectGroup;
