import TreeSelectedGroup from '@/components/shared/TreeSelectedGroup';
import { HTTPSTATUS } from '@/constants';
import {
  apiCreateUsers,
  apiQueryUsers,
} from '@/services/master/UserController';
import { LockOutlined, PlusOutlined, UserOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button } from 'antd';
import { MessageInstance } from 'antd/es/message/interface';
import { useRef, useState } from 'react';
type CreateUserProps = {
  message: MessageInstance;
  onSuccess?: (isSuccess: boolean) => void;
};

type CreateUserFormValues = {
  full_name: string;
  phone_number: string;
  user_type: 'admin' | 'enduser' | 'sysadmin' | 'users';
  email: string;
  password: string;
  group_id?: string;
};

const RoleSelectForm = () => {
  const domain = process.env.DOMAIN_ENV;
  const intl = useIntl();
  switch (domain) {
    case 'sgw':
      return (
        <ProFormSelect
          name="user_type"
          label={intl.formatMessage({ id: 'master.users.role' })}
          options={[
            {
              label: intl.formatMessage({
                id: 'master.users.role.sgw.end_user',
              }),
              value: 'endusers',
            },
            {
              label: intl.formatMessage({ id: 'master.users.role.user' }),
              value: 'users',
            },
            {
              label: intl.formatMessage({ id: 'master.users.role.admin' }),
              value: 'admin',
            },
          ]}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'master.users.role.placeholder',
                defaultMessage: 'Please select a role',
              }),
            },
          ]}
        />
      );
    case 'spole':
      return (
        <ProFormSelect
          name="user_type"
          label={intl.formatMessage({ id: 'master.users.role' })}
          options={[
            {
              label: intl.formatMessage({ id: 'master.users.role.user' }),
              value: 'users',
            },
            {
              label: intl.formatMessage({ id: 'master.users.role.admin' }),
              value: 'admin',
            },
          ]}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'master.users.role.placeholder',
                defaultMessage: 'Please select a role',
              }),
            },
          ]}
        />
      );
    case 'gms':
    default:
      return (
        <ProFormSelect
          name="user_type"
          label={intl.formatMessage({ id: 'master.users.role' })}
          options={[
            {
              label: intl.formatMessage({ id: 'master.users.role.user' }),
              value: 'users',
            },
            {
              label: intl.formatMessage({ id: 'master.users.role.admin' }),
              value: 'admin',
            },
          ]}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'master.users.role.placeholder',
                defaultMessage: 'Please select a role',
              }),
            },
          ]}
        />
      );
  }
};

const CreateUser = ({ message, onSuccess }: CreateUserProps) => {
  const formRef = useRef<ProFormInstance<CreateUserFormValues>>();
  const intl = useIntl();
  const [group_id, setGroupId] = useState<string | string[] | null>(null);
  const handleGroupSelect = (group: string | string[] | null) => {
    setGroupId(group);
    // Đồng bộ giá trị vào form để validation hoạt động
    formRef.current?.setFieldsValue({
      group_id: Array.isArray(group) ? group.join(',') : group || undefined,
    });
  };
  return (
    <ModalForm<CreateUserFormValues>
      title={intl.formatMessage({
        id: 'master.users.register.title',
        defaultMessage: 'Register New User',
      })}
      formRef={formRef}
      trigger={
        <Button type="primary" key="primary" icon={<PlusOutlined />}>
          <FormattedMessage
            id="master.users.register"
            defaultMessage="Register"
          />
        </Button>
      }
      autoFocusFirstInput
      onFinish={async (values: CreateUserFormValues) => {
        const body: MasterModel.CreateUserBodyRequest = {
          email: values.email,
          password: values.password,
          metadata: {
            full_name: values.full_name,
            phone_number: values.phone_number,
            user_type: values.user_type || 'enduser',
            group_id: values.group_id,
          },
        };
        try {
          const resp = await apiCreateUsers(body);
          if (resp.status === HTTPSTATUS.HTTP_CREATED) {
            message.success(
              intl.formatMessage({
                id: 'master.users.create.success',
                defaultMessage: 'Create user successfully',
              }),
            );
            formRef.current?.resetFields();
            onSuccess?.(true);
            return true;
          } else {
            throw new Error('Create user failed');
          }
        } catch (error) {
          message.error(
            intl.formatMessage({
              id: 'master.users.create.error',
              defaultMessage: 'Failed to create user',
            }),
          );
          onSuccess?.(false);
          return false;
        }
      }}
    >
      <ProFormText
        name={'full_name'}
        label={intl.formatMessage({
          id: 'master.users.full_name',
          defaultMessage: 'Full name',
        })}
        placeholder={intl.formatMessage({
          id: 'master.users.full_name.placeholder',
        })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'master.users.full_name.required',
              defaultMessage: 'The full name is required',
            }),
          },
        ]}
      />

      <RoleSelectForm />

      <ProFormText
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="master.users.email.required"
                defaultMessage="The email is required"
              />
            ),
          },
          {
            type: 'email',
            message: (
              <FormattedMessage
                id="master.users.email.invalid"
                defaultMessage="Invalid email address"
              />
            ),
          },
          {
            validator: async (rule, value) => {
              if (value) {
                try {
                  const query: MasterModel.SearchUserPaginationBody = {
                    offset: 0,
                    limit: 1,
                    order: 'email',
                    email: value,
                    dir: 'asc',
                  };
                  const resp = await apiQueryUsers(query);
                  const { total } = resp;
                  if (total && total > 0) {
                    return Promise.reject(
                      new Error(
                        intl.formatMessage({
                          id: 'master.users.email.exists',
                          defaultMessage: 'The email is exists',
                        }),
                      ),
                    );
                  }
                } catch (error) {
                  return Promise.resolve();
                }
              }
              return Promise.resolve();
            },
          },
        ]}
        name="email"
        label={intl.formatMessage({
          id: 'master.users.email',
          defaultMessage: 'Email',
        })}
        fieldProps={{
          prefix: <UserOutlined />,
        }}
        placeholder={intl.formatMessage({
          id: 'master.users.email.placeholder',
          defaultMessage: 'Email',
        })}
        validateTrigger={['onBlur']}
      />
      <ProFormText
        name="phone_number"
        label={intl.formatMessage({
          id: 'master.users.phone_number',
          defaultMessage: 'Phone number',
        })}
        fieldProps={{
          autoComplete: 'phone-number',
        }}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'master.users.phone_number.required',
              defaultMessage: 'The phone number is required',
            }),
          },
          {
            pattern: /((09|03|07|08|05)+([0-9]{8})\b)/g,
            message: intl.formatMessage({
              id: 'master.users.phone_number.notvalid',
              defaultMessage: 'Invalid phone number',
            }),
          },
        ]}
      />
      <ProFormText.Password
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="master.users.password"
                defaultMessage="Password is required"
              />
            ),
          },
          {
            pattern: /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*.]{6,16}$/g,
            message: intl.formatMessage({
              id: 'master.profile.change-password.password.strong',
              defaultMessage:
                'A password contains at least 8 characters, including at least one number and includes both lower and uppercase letters and special characters, for example #, ?, !',
            }),
          },
          {
            validator: async (rule, value) => {
              if (value && value.length < 8) {
                return Promise.reject(
                  intl.formatMessage({
                    id: 'master.users.password.minimum',
                    defaultMessage: 'Minimum password length is 8',
                  }),
                );
              }
              return Promise.resolve();
            },
          },
        ]}
        name="password"
        label={intl.formatMessage({
          id: 'master.users.password',
          defaultMessage: 'Password',
        })}
        fieldProps={{
          prefix: <LockOutlined />,
          autoComplete: 'current-password',
        }}
        placeholder={intl.formatMessage({
          id: 'master.users.password.placeholder',
          defaultMessage: 'Password',
        })}
      />
      <ProForm.Item
        name="group_id"
        label={intl.formatMessage({
          id: 'master.users.groups',
          defaultMessage: 'Groups',
        })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'master.users.groups.required',
              defaultMessage: 'Please select groups!',
            }),
          },
        ]}
      >
        <TreeSelectedGroup groupIds={group_id} onSelected={handleGroupSelect} />
      </ProForm.Item>
    </ModalForm>
  );
};

export default CreateUser;
