import {
  apiCreateGroup,
  apiUpdateGroup,
} from '@/services/master/GroupController';
import {
  ModalForm,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useModel } from '@umijs/max';
import { MessageInstance } from 'antd/es/message/interface';
import { useEffect, useRef } from 'react';
type CreateOrUpdateGroupProps = {
  type: 'create-root' | 'create-child' | 'update';
  isOpen?: boolean;
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
  group?: MasterModel.GroupNode | null;
  message: MessageInstance;
};
type HandleGroupForm = {
  parent_id?: string;
  parent_name?: string;
  name: string;
  code: string;
  short_name: string;
  description?: string;
};
const CreateOrUpdateGroup = ({
  type,
  isOpen,
  setIsOpen,
  group,
  message,
}: CreateOrUpdateGroupProps) => {
  const formRef = useRef<ProFormInstance<HandleGroupForm>>();
  const intl = useIntl();
  const { groups, getGroups } = useModel('master.useGroups');

  // Sync form values when modal opens or group/type changes
  useEffect(() => {
    console.log(
      'useEffect trigger - isOpen:',
      isOpen,
      'group:',
      group,
      'type:',
      type,
    );
    if (isOpen && formRef.current) {
      if (type === 'update' && group) {
        formRef.current.setFieldsValue({
          parent_id: group?.id || '',
          parent_name: '',
          name: group?.name || '',
          code: group?.metadata?.code || '',
          short_name: group?.metadata?.short_name || '',
          description: group?.description || '',
        });
      } else if (type === 'create-child' && group) {
        formRef.current.setFieldsValue({
          parent_id: group?.id,
          parent_name: group?.name || '',
          name: '',
          code: '',
          short_name: '',
          description: '',
        });
      } else if (type === 'create-root') {
        formRef.current.setFieldsValue({
          parent_id: '',
          parent_name: '',
          name: '',
          code: '',
          short_name: '',
          description: '',
        });
      }
    }
  }, [isOpen, group, type]);

  const handleOpenChange = (open: boolean) => {
    setIsOpen(open);
  };
  return (
    <ModalForm<HandleGroupForm>
      open={isOpen}
      onOpenChange={handleOpenChange}
      layout="vertical"
      formRef={formRef}
      title={
        group === undefined ? (
          <FormattedMessage id="master.groups.root" />
        ) : (
          <FormattedMessage id="master.groups.add" />
        )
      }
      onFinish={async (values) => {
        const body: Partial<MasterModel.GroupBodyRequest> = {
          name: values.name,
          description: values.description,
          metadata: {
            code: values.code,
            short_name: values.short_name,
          },
        };
        switch (type) {
          case 'update': {
            body.id = group?.id;
            try {
              const response = await apiUpdateGroup(body);
              if (response.id) {
                message?.success(
                  intl.formatMessage({
                    id: 'master.groups.update.success',
                    defaultMessage: 'Updated successfully',
                  }),
                );
                getGroups();
                return true;
              }
            } catch (error) {
              console.log('Error when update group: ', error);
              message?.error(
                intl.formatMessage({
                  id: 'master.groups.update.failed',
                  defaultMessage: 'Update failed, please try again!',
                }),
              );
              return false;
            }
            break;
          }
          case 'create-child': {
            body.parent_id = group?.id;
            try {
              const response = await apiCreateGroup(body);
              if (response.id) {
                message?.success(
                  intl.formatMessage({
                    id: 'master.groups.create.success',
                    defaultMessage: 'Created group successfully',
                  }),
                );
                setIsOpen(false);
                getGroups();
                return true;
              }
            } catch (error) {
              console.log('Error when create group: ', error);
              message?.error(
                intl.formatMessage({
                  id: 'master.groups.create.failed',
                  defaultMessage: 'Create group failed, please try again!',
                }),
              );
              return false;
            }
            break;
          }
          case 'create-root': {
            try {
              const response = await apiCreateGroup(body);
              if (response.id) {
                message?.success(
                  intl.formatMessage({
                    id: 'master.groups.create.success',
                    defaultMessage: 'Created group successfully',
                  }),
                );
                setIsOpen(false);
                getGroups();
                return true;
              } else {
                throw new Error('Create group failed');
              }
            } catch (error) {
              console.log('Error when create group: ', error);
              message?.error(
                intl.formatMessage({
                  id: 'master.groups.create.failed',
                  defaultMessage: 'Create group failed, please try again!',
                }),
              );
              return false;
            }
          }
        }
      }}
    >
      <ProFormText name="parent_id" hidden />

      {type !== 'update' && (
        <ProFormText
          name="parent_name"
          disabled
          label={intl.formatMessage({
            id: 'master.groups.parent',
            defaultMessage: 'Parent',
          })}
        />
      )}

      <ProFormText
        name="name"
        label={intl.formatMessage({
          id: 'common.name',
          defaultMessage: 'Name',
        })}
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="common.name.required"
                defaultMessage="The name is required"
              />
            ),
          },
        ]}
      />

      <ProFormText
        name="code"
        label={intl.formatMessage({
          id: 'master.groups.code',
          defaultMessage: 'Code',
        })}
        rules={[
          { required: true },
          {
            validator: async (_, value) => {
              if (
                value &&
                groups!.some(
                  (g) => g?.metadata?.code === value && type !== 'update',
                )
              ) {
                throw new Error(
                  intl.formatMessage({
                    id: 'master.groups.code.exists',
                    defaultMessage: 'The code already exists',
                  }),
                );
              }
            },
          },
        ]}
      />

      <ProFormText
        name="short_name"
        label={intl.formatMessage({
          id: 'master.groups.short_name',
          defaultMessage: 'Short name',
        })}
        rules={[
          { required: true },
          {
            validator: async (_, value) => {
              if (
                value &&
                groups!.some(
                  (g) => g?.metadata?.short_name === value && type !== 'update',
                )
              ) {
                throw new Error(
                  intl.formatMessage({
                    id: 'master.groups.short_name.exists',
                    defaultMessage: 'The short name already exists',
                  }),
                );
              }
            },
          },
        ]}
      />

      <ProFormText
        name="description"
        label={intl.formatMessage({
          id: 'common.description',
          defaultMessage: 'Description',
        })}
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="common.description.required"
                defaultMessage="The description is required"
              />
            ),
          },
        ]}
      />
    </ModalForm>
  );
};

export default CreateOrUpdateGroup;
