import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ContentCopyRounded } from '@mui/icons-material';

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';
import {
  DEMAND_TAG_HB_GAM_PLATFORMS,
  DEMAND_TAG_PAGE_BUSINESS_MODEL_HB_NOT_GAM,
  DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE,
  DEMAND_TAG_SUPPLY_CHAIN_VALUE,
  FLOOR_PRICE,
} from '@/modules/marketplace/account/constants';
import { HB_FORMATS } from '@/modules/marketplace/hbConnectors/constants';

import * as selectors from '../../../../../../redux/selectors';
import * as actions from '../../../../../../redux/slices';
import { getRequiredInputProps } from '@/modules/@common/Form/helpers';
import copyToClipboard from '@/modules/@common/helpers/copy';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import { FormRow } from '@/modules/@common/Form';
import BidMappingFileButton from '../BidMappingFileButton';
import {
  Autocomplete,
  IconButton,
  InputAdornment,
  Link,
  Switch,
  TextField,
  ToggleButton,
  ToggleButtonGroup,
} from '@/mui/components';

const floorRegex = /^\d+(\.\d{0,2})?$/;
const maxFloorRegex = /^\d+$/;
const chainNode = '1.0,1!exchange1.com,1234,1,,,!exchange2.com,abcd,1,,,';

const useRenderFields = (platformParam) => {
  const dispatch = useDispatch();
  const settings = useSelector(selectors.settingsSelector);

  const { platform, errors } = settings;

  if (!platform?.connectorId?.length) {
    return null;
  }

  if (!platformParam || !platformParam?.params?.length) {
    return null;
  }

  return platformParam.params?.map((param) => {
    if (param.allowedValues?.length) {
      return (
        <FormRow key={param.label} label={param.label}>
          <Autocomplete
            id={param.name}
            value={param.allowedValues.find((item) => item.value === platform[param.name]) ?? {}}
            options={param.allowedValues}
            onChange={(e, option) => {
              const { [param.name]: error, ...restErrors } = errors;
              dispatch(
                actions.setSettingsTabAction({
                  platform: {
                    ...platform,
                    [param.name]: option?.value ?? null,
                  },
                  errors: restErrors,
                }),
              );
            }}
            size="small"
            renderInput={(params) => (
              <TextField
                {...params}
                data-id={param.name}
                placeholder={['Select', param.label].join(' ')}
                {...getRequiredInputProps({
                  fieldName: param.name,
                  label: param.required ? 'Required' : '',
                  error: !!errors?.[param.name]?.length,
                })}
                variant="outlined"
                size="small"
              />
            )}
          />
        </FormRow>
      );
    }
    if (DEMAND_TAG_HB_GAM_PLATFORMS.includes(platform.code)) {
      return (
        <FormRow key={param.name} label={param.label}>
          <TextField
            data-id={param.name}
            value={platform[param.name] ?? ''}
            size="small"
            multiline
            rows={4}
            placeholder={['Enter', param.label].join(' ')}
            {...getRequiredInputProps({
              fieldName: param.name,
              label: param.required ? 'Required' : '',
              error: !!errors?.[param.name]?.length,
            })}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={() => copyToClipboard(platform[param.name])}>
                    <ContentCopyRounded />
                  </IconButton>
                </InputAdornment>
              ),
            }}
            onChange={({ target }) => {
              const { [param.name]: error, ...restErrors } = errors;
              dispatch(
                actions.setSettingsTabAction({
                  platform: {
                    ...platform,
                    [param.name]: target.value.replace(/\s/g, ''),
                  },
                  errors: restErrors,
                }),
              );
            }}
            helperText={
              <>
                {'For supported macros, please see our '}
                <Link
                  target="_blank"
                  rel="noreferrer"
                  href="https://docs.anyclip.com/en/articles/9638792-marketplace-supported-macros"
                >
                  online help
                </Link>
              </>
            }
          />
        </FormRow>
      );
    }

    if (param?.type === 'ARRAY') {
      return (
        <FormRow key={`${param.name}${param.label}`} label={param.label}>
          <TextField
            value={platform[param.name] ?? ''}
            size="small"
            placeholder={['Enter', param.label].join(' ')}
            {...getRequiredInputProps({
              fieldName: param.name,
              label: errors?.[param.name],
              error: !!errors?.[param.name]?.length,
            })}
            onChange={({ target }) => {
              const { [param.name]: error, ...restErrors } = errors;
              dispatch(
                actions.setSettingsTabAction({
                  platform: {
                    ...platform,
                    [param.name]: target.value,
                  },
                  errors: restErrors,
                }),
              );
            }}
          />
        </FormRow>
      );
    }

    return (
      <FormRow key={`${param.name}${param.label}`} label={param.label}>
        <TextField
          value={platform[param.name] ?? ''}
          size="small"
          placeholder={['Enter', param.label].join(' ')}
          {...getRequiredInputProps({
            fieldName: param.name,
            label: param.required ? 'Required' : '',
            error: !!errors?.[param.name]?.length,
          })}
          onChange={({ target }) => {
            const { [param.name]: error, ...restErrors } = errors;
            dispatch(
              actions.setSettingsTabAction({
                platform: {
                  ...platform,
                  [param.name]: target.value.replace(/\s/g, ''),
                },
                errors: restErrors,
              }),
            );
          }}
        />
      </FormRow>
    );
  });
};

function HeaderBiddingForm(props) {
  const dispatch = useDispatch();

  const settings = useSelector(selectors.settingsSelector);
  const {
    format,
    supplyChainOverride,
    supplyChainValue,
    supplyChainNode,
    floorPrice,
    maxFloor,
    adjustFloor,
    bidMappingFileName,
    bidMappingFileData,
    platform: platformProps,
    platforms,
    errors,
  } = settings;

  const showNotification = (o) => dispatch(showNotificationAction(o));
  const setSettingsTab = (o) => dispatch(actions.setSettingsTabAction(o));

  const platform = platforms?.find((item) => item.id === platformProps?.connectorId) ?? null;

  const handleCopyTooltip = () => {
    copyToClipboard(chainNode).then(() => {
      dispatch(
        showNotificationAction({
          type: TYPE_SUCCESS,
          message: 'Supply Chain Node was copied',
        }),
      );
    });
  };

  return (
    <>
      <FormRow label="Platform">
        <Autocomplete
          id="platform-list"
          value={platform}
          options={platforms?.filter((platf) => platf.format === format || platf.format === HB_FORMATS[0].value) ?? []}
          optionLabelKey="name"
          optionValueKey="name"
          disableClearable
          // eslint-disable-next-line react/prop-types
          disabled={!(props.isCreatingNew || props.isDuplicate)}
          onChange={(e, value) => {
            const { platform: platformError, ...restErrors } = errors;
            const defaultValues =
              value?.params?.reduce((acc, curr) => {
                if (curr.defaultValue) {
                  return {
                    ...acc,
                    [curr.name]: curr.defaultValue,
                  };
                }

                return acc;
              }, {}) ?? {};

            dispatch(
              actions.setSettingsTabAction({
                platform: {
                  name: value.name,
                  connectorId: value.id,
                  code: value.code,
                  ...defaultValues,
                },
                errors: restErrors,
              }),
            );

            if (!DEMAND_TAG_HB_GAM_PLATFORMS.includes(value.code)) {
              dispatch(
                actions.setPricingTabAction({
                  model: DEMAND_TAG_PAGE_BUSINESS_MODEL_HB_NOT_GAM[0].value,
                }),
              );
            }
          }}
          size="small"
          renderInput={(params) => (
            <TextField
              {...params}
              data-id="platform"
              helperText={errors?.platform ?? ''}
              placeholder="Select Platform"
              size="small"
              {...getRequiredInputProps({
                fieldName: 'platform',
                error: !!errors?.platform?.length,
              })}
            />
          )}
        />
      </FormRow>
      {useRenderFields(platform)}

      {platformProps?.code?.toUpperCase() === 'APS' && (
        <FormRow label="Bid Mapping">
          <BidMappingFileButton
            bidMappingFileName={bidMappingFileName}
            bidMappingFileData={bidMappingFileData}
            setSettingsTab={setSettingsTab}
            errors={errors}
            showNotificationAction={showNotification}
          />
        </FormRow>
      )}
      <FormRow
        label="Supply Chain Override"
        tooltip="AnyClip automatically passes the default supply chain object, including
          the AnyClip seller_id (sid) assigned to the respective site.
          However, this must be overridden and set to Blank for direct publisher demand."
      >
        <Switch
          color="primary"
          size="small"
          checked={supplyChainOverride === DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE.enabled}
          onChange={() =>
            dispatch(
              actions.setSettingsTabAction({
                supplyChainOverride:
                  supplyChainOverride === DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE.enabled
                    ? DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE.disabled
                    : DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE.enabled,
              }),
            )
          }
        />
      </FormRow>

      {supplyChainOverride === DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE.enabled && (
        <>
          <FormRow label="Supply Chain Value">
            <ToggleButtonGroup equalWidth size="small" color="primary" variant="outlined" value={supplyChainValue}>
              <ToggleButton
                value={DEMAND_TAG_SUPPLY_CHAIN_VALUE.blank}
                onClick={() =>
                  dispatch(
                    actions.setSettingsTabAction({
                      supplyChainValue: DEMAND_TAG_SUPPLY_CHAIN_VALUE.blank,
                    }),
                  )
                }
              >
                Blank
              </ToggleButton>
              <ToggleButton
                value={DEMAND_TAG_SUPPLY_CHAIN_VALUE.custom}
                onClick={() =>
                  dispatch(
                    actions.setSettingsTabAction({
                      supplyChainValue: DEMAND_TAG_SUPPLY_CHAIN_VALUE.custom,
                    }),
                  )
                }
              >
                Custom
              </ToggleButton>
            </ToggleButtonGroup>
          </FormRow>
          {supplyChainValue === DEMAND_TAG_SUPPLY_CHAIN_VALUE.custom && (
            <FormRow
              label="Supply Chain Node"
              tooltip={
                <>
                  {chainNode}
                  <IconButton onClick={handleCopyTooltip} size="small">
                    <ContentCopyRounded />
                  </IconButton>
                </>
              }
            >
              <TextField
                value={supplyChainNode}
                size="small"
                placeholder="Enter Supply Chain Node"
                {...getRequiredInputProps({
                  fieldName: 'supplyChainNode',
                  error: !!errors?.supplyChainNode?.length,
                })}
                onChange={({ target }) => {
                  const { supplyChainNode: supplyChainNodeError, ...restErrors } = errors;
                  dispatch(
                    actions.setSettingsTabAction({
                      supplyChainNode: target.value,
                      errors: restErrors,
                    }),
                  );
                }}
              />
            </FormRow>
          )}
        </>
      )}

      <FormRow
        label="Floor Price"
        tooltip={
          // eslint-disable-next-line
          "Utilize the publisher's default floor price or\n" + 'customize it specifically for this demand tag'
        }
      >
        <ToggleButtonGroup size="small" color="primary" variant="outlined" equalWidth value={floorPrice.override}>
          <ToggleButton
            value={FLOOR_PRICE.publisherDefault}
            onClick={() =>
              dispatch(
                actions.setSettingsTabAction({
                  floorPrice: {
                    ...floorPrice,
                    override: FLOOR_PRICE.publisherDefault,
                  },
                }),
              )
            }
          >
            Publisher Default Floor
          </ToggleButton>
          <ToggleButton
            value={FLOOR_PRICE.override}
            onClick={() =>
              dispatch(
                actions.setSettingsTabAction({
                  floorPrice: {
                    ...floorPrice,
                    override: FLOOR_PRICE.override,
                  },
                }),
              )
            }
          >
            Override Floor
          </ToggleButton>
        </ToggleButtonGroup>
      </FormRow>

      {floorPrice.override === FLOOR_PRICE.override && (
        <>
          <FormRow label="Floor Rate - Viewable">
            <TextField
              value={floorPrice.viewableFloor}
              size="small"
              placeholder="0.00"
              {...getRequiredInputProps({
                fieldName: 'floorRateViewable',
                error: !!errors?.viewableFloor?.length,
              })}
              onChange={({ target }) => {
                const { viewableFloor, ...restErrors } = errors;
                if (floorRegex.test(target.value) || target.value.length === 0) {
                  dispatch(
                    actions.setSettingsTabAction({
                      floorPrice: {
                        ...floorPrice,
                        viewableFloor: target.value,
                      },
                      errors: restErrors,
                    }),
                  );
                }
              }}
            />
          </FormRow>
          <FormRow label="Floor Rate - NonViewable">
            <TextField
              value={floorPrice.floor}
              size="small"
              placeholder="0.00"
              {...getRequiredInputProps({
                fieldName: 'floorRateNonViewable',
                error: !!errors?.floor?.length,
              })}
              onChange={({ target }) => {
                const { floor, ...restErrors } = errors;
                if (floorRegex.test(target.value) || target.value.length === 0) {
                  dispatch(
                    actions.setSettingsTabAction({
                      floorPrice: {
                        ...floorPrice,
                        floor: target.value,
                      },
                      errors: restErrors,
                    }),
                  );
                }
              }}
            />
          </FormRow>
        </>
      )}

      {DEMAND_TAG_HB_GAM_PLATFORMS.includes(platformProps.code) && (
        <FormRow label="Max Floor">
          <TextField
            value={maxFloor}
            size="small"
            placeholder="Max Floor"
            label="Required"
            {...getRequiredInputProps({
              fieldName: 'maxFloor',
              error: !!errors?.maxFloor?.length,
            })}
            onChange={({ target }) => {
              const { maxFloor: maxFloorError, ...restErrors } = errors;
              if (
                target.value.length === 0 ||
                (target.value > 0 && target.value < 100 && maxFloorRegex.test(target.value))
              ) {
                dispatch(
                  actions.setSettingsTabAction({
                    maxFloor: target.value,
                    errors: restErrors,
                  }),
                );
              }
            }}
          />
        </FormRow>
      )}

      <FormRow
        label="Automatic floor participation"
        tooltip="Activate the option to allow the AnyClip AI to dynamically
        adjust the bid floor sent to this demand tag during the session,
        aiming to optimize yield for each session individually"
      >
        <Switch
          color="primary"
          size="small"
          checked={adjustFloor}
          onChange={() =>
            dispatch(
              actions.setSettingsTabAction({
                adjustFloor: !adjustFloor,
              }),
            )
          }
        />
      </FormRow>
    </>
  );
}

export default HeaderBiddingForm;
