import React, { useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import {
  Box,
  Cell,
  Checkbox,
  Collapse,
  Divider,
  FloatingNotification,
  FormField,
  InfoIcon,
  Input,
  Layout,
  Text,
  TextButton,
} from '@wix/design-system';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { CustomFieldModalState } from '@wix/bex-core';
import { CustomFieldTypeDropdown } from './CustomFieldTypeDropdown';
import { ChevronDown, ChevronUp, InfoCircle } from '@wix/wix-ui-icons-common';
import { Trans } from '../Trans';
import { runInAction } from 'mobx';
import { PiiFormFields } from './CustomFieldFormPiiFields';

export interface CustomFieldFormProps {
  state: CustomFieldModalState;
}

export const _CustomFieldForm = (props: CustomFieldFormProps) => {
  const { state } = props;
  const {
    form: {
      $: {
        key,
        type,
        name,
        readApps,
        readUsers,
        writeApps,
        writeUsers,
        containsPii,
      },
    },
    errorToastConfig,
    disabledFields: { permissions },
    mode,
    settings,
    customFieldModalBiReporter,
    generateUniqueKey,
    setKeyFieldIfNotDirty,
  } = state;
  const defaultPermissions = state.fieldManagement.permissions;
  const { reportAdvancedSettingsClick, reportKeyFormFieldChange } =
    customFieldModalBiReporter;

  const {
    translate: t,
    environment: { language },
  } = useWixPatternsContainer();

  useEffect(() => customFieldModalBiReporter.init(), []);

  return (
    <Box width={552} direction="vertical">
      {errorToastConfig && (
        <Box
          position="absolute"
          top="24px"
          left="49%"
          transform="translateX(-50%)"
        >
          <FloatingNotification
            dataHook="custom-field-modal-error-state"
            type="destructive"
            prefixIcon={<InfoCircle />}
            text={errorToastConfig.message}
            textButtonProps={
              errorToastConfig?.action && {
                label: errorToastConfig.action.text,
                onClick: () => errorToastConfig?.action?.onClick?.(),
              }
            }
            onClose={() => {
              runInAction(() => {
                state.errorToastConfig = undefined;
              });
            }}
          />
        </Box>
      )}
      <Box paddingLeft="SP1" paddingRight="SP1" direction="vertical">
        <Layout>
          <Cell span={6}>
            <FormField
              dataHook="custom-field-modal-field-type"
              required
              label={t('cairo.customFields.addCustomField.modal.fieldType')}
              status={type.hasError ? 'error' : undefined}
              statusMessage={type.error}
            >
              <CustomFieldTypeDropdown state={state} />
              {mode === 'edit' && (
                <Box marginTop="SP1">
                  <Text size="tiny" secondary>
                    {t('cairo.customFields.editCustomField.fieldType.tooltip')}
                  </Text>
                </Box>
              )}
            </FormField>
          </Cell>
          <Cell span={6}>
            <FormField
              dataHook="custom-field-modal-field-name"
              required
              label={t('cairo.customFields.addCustomField.modal.fieldName')}
              status={name.hasError ? 'error' : undefined}
              statusMessage={name.error}
            >
              <Input
                dataHook="custom-field-modal-name"
                onChange={(e) => {
                  name.onChange(e.target.value);
                  setKeyFieldIfNotDirty(generateUniqueKey(e.target.value));
                }}
                value={name.value}
                maxLength={64}
                placeholder={state.namePlaceholder}
              />
            </FormField>
          </Cell>
          {state.fieldManagement.supportsPii && (
            <PiiFormFields
              containsPii={{
                value: containsPii.value,
                onChange: containsPii.onChange,
              }}
              mode={mode}
              language={language}
            />
          )}
        </Layout>
        <Box marginTop="SP4">
          <TextButton
            dataHook="custom-field-modal-settings-button"
            size="small"
            suffixIcon={settings.isOn ? <ChevronUp /> : <ChevronDown />}
            onClick={() => settings.toggle()}
          >
            {t('cairo.customFields.addCustomField.modal.advancedSettings')}
          </TextButton>
        </Box>
        <Collapse
          open={settings.isOn}
          onExpandAnimationEnd={() => {
            reportAdvancedSettingsClick('Open');
          }}
          onCollapseAnimationEnd={() => {
            reportAdvancedSettingsClick('Close');
          }}
        >
          {(!defaultPermissions?.installedApps?.hide ||
            !defaultPermissions?.siteVisitors?.hide) && (
            <Box marginTop="SP4" direction="vertical" width="320px">
              <Text size="small">
                {t(
                  'cairo.customFields.addCustomField.modal.advancedSettings.readPermissions',
                )}
              </Text>
              <Text size="tiny" light secondary>
                {t(
                  'cairo.customFields.addCustomField.modal.advancedSettings.readPermissions.tooltip',
                )}
              </Text>
            </Box>
          )}
          {!defaultPermissions?.installedApps?.hide && (
            <Box marginTop="SP3" dataHook="custom-field-modal-apps-section">
              <Layout>
                <Cell span={4}>
                  <Box verticalAlign="middle" gap="SP1">
                    <Text size="small">
                      {t(
                        'cairo.customFields.addCustomField.modal.advancedSettings.externalApps',
                      )}
                    </Text>
                    <InfoIcon
                      size="small"
                      content={
                        <Trans i18nKey="cairo.customFields.addCustomField.modal.advancedSettings.externalApps.tooltip" />
                      }
                    />
                  </Box>
                </Cell>
                <Cell span={2}>
                  <Checkbox
                    dataHook="custom-field-modal-read-apps"
                    disabled={mode === 'edit' && permissions.read.apps}
                    size="small"
                    onChange={() => {
                      readApps.onChange(!readApps.value);
                    }}
                    checked={readApps.value}
                  >
                    {t(
                      'cairo.customFields.addCustomField.modal.advancedSettings.read',
                    )}
                  </Checkbox>
                </Cell>
                <Cell span={2}>
                  <Checkbox
                    dataHook="custom-field-modal-write-apps"
                    disabled={mode === 'edit' && permissions.write.apps}
                    size="small"
                    onChange={() => {
                      writeApps.onChange(!writeApps.value);
                    }}
                    checked={writeApps.value}
                  >
                    {t(
                      'cairo.customFields.addCustomField.modal.advancedSettings.write',
                    )}
                  </Checkbox>
                </Cell>
              </Layout>
            </Box>
          )}
          {!defaultPermissions?.siteVisitors?.hide && (
            <>
              <Box marginTop="SP2" dataHook="custom-field-modal-users-section">
                <Layout>
                  <Cell span={4}>
                    <Box verticalAlign="middle" gap="SP1">
                      <Text size="small">
                        {t(
                          'cairo.customFields.addCustomField.modal.advancedSettings.siteVisitors',
                        )}
                      </Text>
                      <InfoIcon
                        size="small"
                        content={
                          <Trans
                            i18nKey="cairo.customFields.addCustomField.modal.advancedSettings.siteVisitors.tooltip"
                            components={{
                              learnMore: (
                                <TextButton
                                  underline="always"
                                  skin="light"
                                  size="small"
                                  as="a"
                                  rel="noopener"
                                  target="_blank"
                                  href={`https://support.wix.com/${language}/article/cms-about-datasets`}
                                />
                              ),
                            }}
                          />
                        }
                      />
                    </Box>
                  </Cell>
                  <Cell span={2}>
                    <Checkbox
                      dataHook="custom-field-modal-read-users"
                      disabled={mode === 'edit' && permissions.read.users}
                      size="small"
                      onChange={() => {
                        readUsers.onChange(!readUsers.value);
                      }}
                      checked={readUsers.value}
                    >
                      {t(
                        'cairo.customFields.addCustomField.modal.advancedSettings.read',
                      )}
                    </Checkbox>
                  </Cell>
                  <Cell span={2}>
                    <Checkbox
                      dataHook="custom-field-modal-write-users"
                      disabled={mode === 'edit' && permissions.write.users}
                      size="small"
                      onChange={() => {
                        writeUsers.onChange(!writeUsers.value);
                      }}
                      checked={writeUsers.value}
                    >
                      {t(
                        'cairo.customFields.addCustomField.modal.advancedSettings.write',
                      )}
                    </Checkbox>
                  </Cell>
                </Layout>
              </Box>
              <Box>
                <Text size="tiny" light secondary dataHook="permissions-note">
                  <Trans
                    i18nKey="cairo.customFields.addCustomField.modal.advancedSettings.siteVisitors.note"
                    components={{
                      learnMore: (
                        <TextButton
                          size="tiny"
                          as="a"
                          rel="noopener"
                          target="_blank"
                          href={`https://support.wix.com/${language}/article/content-manager-connecting-elements-to-a-collection-using-a-dataset`}
                        />
                      ),
                    }}
                  />
                </Text>
              </Box>
            </>
          )}
          <Box direction="vertical">
            <Box marginTop="SP3" marginBottom="SP3">
              <Divider />
            </Box>

            <FormField
              dataHook="custom-field-modal-field-key"
              required
              label={t(
                'cairo.customFields.addCustomField.modal.advancedSettings.key.title',
              )}
              status={key.hasError ? 'error' : undefined}
              statusMessage={key.error}
            >
              <Layout>
                <Cell span={6}>
                  <Input
                    dataHook="custom-field-modal-key"
                    disabled={mode === 'edit'}
                    value={key.value}
                    onChange={(e) => {
                      key.onChange(e.target.value.toLowerCase());
                      reportKeyFormFieldChange();
                    }}
                    placeholder={t(
                      'cairo.customFields.addCustomField.modal.advancedSettings.key.placeholder',
                    )}
                  />
                </Cell>
              </Layout>
            </FormField>

            {!key.hasError && (
              <Box marginTop="SP1">
                <Text
                  size="tiny"
                  secondary
                  dataHook="custom-field-modal-fieldKey-tooltip"
                >
                  {mode === 'new'
                    ? t(
                        'cairo.customFields.addCustomField.modal.advancedSettings.key.tooltip',
                      )
                    : t('cairo.customFields.editCustomField.fieldKey.tooltip')}
                </Text>
              </Box>
            )}
          </Box>
        </Collapse>
      </Box>
    </Box>
  );
};

export const CustomFieldForm = observer(_CustomFieldForm);
