import TreeSelectedGroup from '@/components/shared/TreeSelectedGroup';
import { PlusOutlined } 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 CreateDeviceProps = {
  message: MessageInstance;
  onSuccess?: (isSuccess: boolean) => void;
};

type CreateDeviceFormValues = {
  name: string;
  external_id: string;
  type: string;
  address?: string;
  group_id?: string;
};

const CreateDevice = ({ message, onSuccess }: CreateDeviceProps) => {
  const formRef = useRef<ProFormInstance<CreateDeviceFormValues>>();
  const intl = useIntl();
  const [group_id, setGroupId] = useState<string | string[] | null>(null);

  const handleGroupSelect = (group: string | string[] | null) => {
    setGroupId(group);
    formRef.current?.setFieldsValue({
      group_id: Array.isArray(group) ? group.join(',') : group || undefined,
    });
  };

  return (
    <ModalForm<CreateDeviceFormValues>
      title={intl.formatMessage({
        id: 'master.devices.register.title',
        defaultMessage: 'Register New Device',
      })}
      formRef={formRef}
      trigger={
        <Button type="primary" key="primary" icon={<PlusOutlined />}>
          <FormattedMessage
            id="master.devices.register"
            defaultMessage="Register"
          />
        </Button>
      }
      autoFocusFirstInput
      onFinish={async (values: CreateDeviceFormValues) => {
        // TODO: Implement API call to create device
        console.log('Create device with values:', values);

        try {
          // Placeholder for API call
          // const body = {
          //   name: values.name,
          //   metadata: {
          //     external_id: values.external_id,
          //     type: values.type,
          //     address: values.address,
          //     group_id: values.group_id,
          //   },
          // };
          // const resp = await apiCreateDevice(body);

          message.success(
            intl.formatMessage({
              id: 'master.devices.create.success',
              defaultMessage: 'Create device successfully',
            }),
          );
          formRef.current?.resetFields();
          onSuccess?.(true);
          return true;
        } catch (error) {
          message.error(
            intl.formatMessage({
              id: 'master.devices.create.error',
              defaultMessage: 'Failed to create device',
            }),
          );
          onSuccess?.(false);
          return false;
        }
      }}
    >
      <ProFormText
        name={'name'}
        label={intl.formatMessage({
          id: 'master.devices.name',
          defaultMessage: 'Name',
        })}
        placeholder={intl.formatMessage({
          id: 'master.devices.name.placeholder',
          defaultMessage: 'Enter device name',
        })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'master.devices.name.required',
              defaultMessage: 'The device name is required',
            }),
          },
        ]}
      />

      <ProFormText
        name={'external_id'}
        label={intl.formatMessage({
          id: 'master.devices.external_id',
          defaultMessage: 'External ID',
        })}
        placeholder={intl.formatMessage({
          id: 'master.devices.external_id.placeholder',
          defaultMessage: 'Enter external ID',
        })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'master.devices.external_id.required',
              defaultMessage: 'The external ID is required',
            }),
          },
        ]}
      />

      <ProFormSelect
        name="type"
        label={intl.formatMessage({
          id: 'master.devices.type',
          defaultMessage: 'Type',
        })}
        options={[
          {
            label: intl.formatMessage({
              id: 'master.devices.type.gms',
              defaultMessage: 'GMS',
            }),
            value: 'gms',
          },
          {
            label: intl.formatMessage({
              id: 'master.devices.type.sgw',
              defaultMessage: 'SGW',
            }),
            value: 'sgw',
          },
          {
            label: intl.formatMessage({
              id: 'master.devices.type.spole',
              defaultMessage: 'SPOLE',
            }),
            value: 'spole',
          },
        ]}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'master.devices.type.required',
              defaultMessage: 'Please select a device type',
            }),
          },
        ]}
      />

      <ProFormText
        name={'address'}
        label={intl.formatMessage({
          id: 'master.devices.address',
          defaultMessage: 'Address',
        })}
        placeholder={intl.formatMessage({
          id: 'master.devices.address.placeholder',
          defaultMessage: 'Enter device address',
        })}
      />

      <ProForm.Item
        name="group_id"
        label={intl.formatMessage({
          id: 'master.devices.groups',
          defaultMessage: 'Groups',
        })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({
              id: 'master.devices.groups.required',
              defaultMessage: 'Please select groups!',
            }),
          },
        ]}
      >
        <TreeSelectedGroup groupIds={group_id} onSelected={handleGroupSelect} />
      </ProForm.Item>
    </ModalForm>
  );
};

export default CreateDevice;
