import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { Visibility, VisibilityOff } from '@mui/icons-material';

import {
  DEMAND_TAG_DEFAULT_TIER_VALUES,
  DEMAND_TAG_FORMAT,
  DEMAND_TAG_KEY_VALUE_TARGETING_STATUS,
  DEMAND_TAG_PAGE_BROWSER_LIST,
  DEMAND_TAG_PAGE_DEVICE_LIST,
  DEMAND_TAG_PAGE_OS_LIST,
  DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE,
  DEMAND_TAG_TARGETING_VIEWABILITY_TYPE,
  DEMAND_TAG_VIEWABILITY_TARGETING,
} from '@/modules/marketplace/account/constants';

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

import { Form, FormContent, FormGroup, FormGroupTitle, FormRow, FormSection } from '@/modules/@common/Form';
import ActionAutocomplete from './components/ActionAutocomplete';
import KeyValue from './components/KeyValue';
import { Button, Switch, TextField, ToggleButton, ToggleButtonGroup, Typography } from '@/mui/components';

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

  const targeting = useSelector(selectors.targetingSelector);
  const {
    viewability,
    viewabilityTargeting,
    viewabilityThreshold,
    playerSize,
    devices,
    countries,
    os,
    browsers,
    countriesList,
    kvTargetingStatus,
    kvTargeting,
    keyNamesOptions,
    keyListsOptions,
    tier,
    errors,
  } = targeting;

  const settings = useSelector(selectors.settingsSelector);

  const getKeyNamesOptions = (o) => dispatch(actions.getKeyNamesOptionsAction(o));
  const getKeyListsOptions = (o) => dispatch(actions.getKeyListsOptionsAction(o));

  const handleChangeKeyValue = (id, newValue) => {
    dispatch(
      actions.setTargetingTabAction({
        kvTargeting: kvTargeting?.map((item, index) => {
          if (id === index) {
            return {
              ...item,
              ...newValue,
            };
          }
          return item;
        }),
      }),
    );
  };

  const handleDeleteKeyValue = (index) => {
    const newKeys = [...kvTargeting];
    newKeys.splice(index, 1);

    dispatch(
      actions.setTargetingTabAction({
        kvTargeting: newKeys,
        kvTargetingStatus: newKeys.length
          ? DEMAND_TAG_KEY_VALUE_TARGETING_STATUS.enabled
          : DEMAND_TAG_KEY_VALUE_TARGETING_STATUS.disabled,
      }),
    );
  };

  return (
    <Form>
      <FormContent>
        <FormSection>
          <FormGroupTitle>Details</FormGroupTitle>
          {props.tabConfig.geography && (
            <FormRow
              label="Geography"
              tooltip={
                props.tabConfig.geographyTooltip
                  ? 'Set geography targeting that will be applicable to all demand tags associated with this advertiser'
                  : ''
              }
            >
              <ActionAutocomplete
                value={countries}
                options={countriesList}
                onChange={(data) => dispatch(actions.setTargetingTabAction({ countries: data }))}
                size="small"
              />
            </FormRow>
          )}

          {
            // eslint-disable-next-line react/prop-types
            props.tabConfig.tier && (
              <FormRow
                label="Default Tier"
                tooltip="This tier functions as the default when creating a new demand tag for this advertiser,
                     and it can be customized independently for each demand tag"
              >
                <ToggleButtonGroup equalWidth size="small" color="primary" variant="outlined" value={tier}>
                  {DEMAND_TAG_DEFAULT_TIER_VALUES.map((item) => (
                    <ToggleButton
                      key={item.value}
                      disabled={item.value === 0}
                      value={item.value}
                      onClick={() =>
                        dispatch(
                          actions.setTargetingTabAction({
                            tier: item.value,
                          }),
                        )
                      }
                    >
                      {tier.value}
                    </ToggleButton>
                  ))}
                </ToggleButtonGroup>
              </FormRow>
            )
          }

          {props.tabConfig.playerSize && settings?.format !== DEMAND_TAG_FORMAT.sponsored && (
            <FormRow label="Player Size">
              <ToggleButtonGroup
                equalWidth
                size="small"
                color="primary"
                variant="outlined"
                value={Object.keys(playerSize).filter((key) => playerSize[key])}
              >
                {[
                  DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE.xs,
                  DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE.s,
                  DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE.m,
                  DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE.l,
                ].map((id) => (
                  <ToggleButton
                    key={id}
                    value={id}
                    onClick={() =>
                      dispatch(
                        actions.setTargetingTabAction({
                          playerSize: {
                            ...playerSize,
                            [id]: !playerSize[id],
                          },
                        }),
                      )
                    }
                  >
                    {id}
                  </ToggleButton>
                ))}
              </ToggleButtonGroup>
            </FormRow>
          )}

          {props.tabConfig.viewability && settings?.format !== DEMAND_TAG_FORMAT.sponsored && (
            <FormRow label="Viewability">
              <ToggleButtonGroup
                equalWidth
                color="primary"
                size="small"
                value={Object.keys(viewability).filter((key) => viewability[key])}
              >
                <ToggleButton
                  value={DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.inView}
                  onClick={() =>
                    dispatch(
                      actions.setTargetingTabAction({
                        viewability: {
                          ...viewability,
                          [DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.inView]:
                            !viewability[DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.inView],
                        },
                      }),
                    )
                  }
                >
                  <Visibility />
                </ToggleButton>
                <ToggleButton
                  value={DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.nonInView}
                  onClick={() =>
                    dispatch(
                      actions.setTargetingTabAction({
                        viewability: {
                          ...viewability,
                          [DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.nonInView]:
                            !viewability[DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.nonInView],
                        },
                      }),
                    )
                  }
                >
                  <VisibilityOff />
                </ToggleButton>
              </ToggleButtonGroup>
            </FormRow>
          )}

          {props.tabConfig.viewabilityTargeting &&
            settings?.format !== DEMAND_TAG_FORMAT.sponsored &&
            viewability[DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.inView] &&
            viewability[DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.nonInView] && (
              <FormRow
                label="Viewability Targeting"
                tooltip="When activated, the AnyClip algorithm ensures a minimum level of viewability,
              determined by the specified threshold below"
              >
                <Switch
                  color="primary"
                  size="small"
                  checked={viewabilityTargeting === DEMAND_TAG_VIEWABILITY_TARGETING.enabled}
                  onChange={() =>
                    dispatch(
                      actions.setTargetingTabAction({
                        viewabilityTargeting:
                          viewabilityTargeting === DEMAND_TAG_VIEWABILITY_TARGETING.enabled
                            ? DEMAND_TAG_VIEWABILITY_TARGETING.disabled
                            : DEMAND_TAG_VIEWABILITY_TARGETING.enabled,
                      }),
                    )
                  }
                />
              </FormRow>
            )}

          {props.tabConfig.viewabilityTargeting &&
            settings?.format !== DEMAND_TAG_FORMAT.sponsored &&
            viewability[DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.inView] &&
            viewability[DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.nonInView] &&
            viewabilityTargeting === DEMAND_TAG_VIEWABILITY_TARGETING.enabled && (
              <FormRow label="Viewability % Threshold">
                <TextField
                  type="number"
                  value={viewabilityThreshold}
                  size="small"
                  {...getRequiredInputProps({
                    fieldName: 'viewabilityThreshold',
                    error: !!errors?.viewabilityThreshold?.length,
                  })}
                  onChange={({ target }) => {
                    const { viewabilityThreshold: viewabilityThresholdError, ...restErrors } = errors;
                    const value =
                      target.value.split('.')[1]?.length > 2
                        ? target.value.substring(0, target.value.length - 1)
                        : target.value;

                    if (+target.value >= 0 && +target.value <= 100) {
                      dispatch(actions.setTargetingTabAction({ viewabilityThreshold: value, errors: restErrors }));
                    }
                  }}
                />
              </FormRow>
            )}
          {props.tabConfig.device && (
            <FormRow label="Device">
              <ActionAutocomplete
                value={devices}
                options={DEMAND_TAG_PAGE_DEVICE_LIST}
                onChange={(data) => dispatch(actions.setTargetingTabAction({ devices: data }))}
                size="small"
              />
            </FormRow>
          )}

          {props.tabConfig.os && (
            <FormRow label="OS">
              <ActionAutocomplete
                value={os}
                options={DEMAND_TAG_PAGE_OS_LIST}
                onChange={(data) => dispatch(actions.setTargetingTabAction({ os: data }))}
                size="small"
              />
            </FormRow>
          )}

          {props.tabConfig.browser && (
            <FormRow label="Browser">
              <ActionAutocomplete
                value={browsers}
                options={DEMAND_TAG_PAGE_BROWSER_LIST}
                onChange={(data) => dispatch(actions.setTargetingTabAction({ browsers: data }))}
                size="small"
              />
            </FormRow>
          )}

          {
            // eslint-disable-next-line react/prop-types
            props.tabConfig.kvTargeting && settings?.format !== DEMAND_TAG_FORMAT.sponsored && (
              <>
                <FormRow label="Key Value Targeting">
                  <Switch
                    color="primary"
                    size="small"
                    checked={kvTargetingStatus === DEMAND_TAG_KEY_VALUE_TARGETING_STATUS.enabled}
                    onChange={() =>
                      dispatch(
                        actions.setTargetingTabAction({
                          kvTargetingStatus:
                            kvTargetingStatus === DEMAND_TAG_KEY_VALUE_TARGETING_STATUS.enabled
                              ? DEMAND_TAG_VIEWABILITY_TARGETING.disabled
                              : DEMAND_TAG_KEY_VALUE_TARGETING_STATUS.enabled,
                          kvTargeting:
                            kvTargetingStatus === DEMAND_TAG_KEY_VALUE_TARGETING_STATUS.enabled
                              ? []
                              : [
                                  {
                                    keyName: null,
                                    state: 'INCLUDE',
                                    type: 'VALUE',
                                    values: [],
                                    valueLists: [],
                                  },
                                ],
                        }),
                      )
                    }
                  />
                </FormRow>
                {kvTargetingStatus === DEMAND_TAG_KEY_VALUE_TARGETING_STATUS.enabled && !!kvTargeting?.length && (
                  <FormGroup>
                    {kvTargeting.map((item, index) => (
                      <Fragment key={+index}>
                        {!!index && (
                          <FormRow label justifyContent="center">
                            <Typography variant="body2" color="text.secondary" component="div">
                              AND
                            </Typography>
                          </FormRow>
                        )}
                        <KeyValue
                          id={index}
                          keyName={item.keyName}
                          state={item.state}
                          type={item.type}
                          values={item.values}
                          valueLists={item.valueLists}
                          keyNamesOptions={keyNamesOptions}
                          keyListsOptions={keyListsOptions}
                          onChange={handleChangeKeyValue}
                          onDelete={() => handleDeleteKeyValue(index)}
                          getKeyNamesOptions={getKeyNamesOptions}
                          getKeyListsOptions={getKeyListsOptions}
                        />
                      </Fragment>
                    ))}
                    {kvTargeting?.length < 3 && (
                      <FormRow label justifyContent="center">
                        <Button
                          variant="outlined"
                          size="small"
                          onClick={() =>
                            dispatch(
                              actions.setTargetingTabAction({
                                kvTargeting: [
                                  ...kvTargeting,
                                  {
                                    key: '',
                                    state: 'INCLUDE',
                                    type: 'VALUE',
                                    values: [],
                                    listNames: [],
                                  },
                                ],
                              }),
                            )
                          }
                        >
                          Add Key-Value
                        </Button>
                      </FormRow>
                    )}
                  </FormGroup>
                )}
              </>
            )
          }
        </FormSection>
      </FormContent>
    </Form>
  );
}

TargetingTab.propTypes = {
  tabConfig: PropTypes.shape({
    domains: PropTypes.bool,
    geography: PropTypes.bool,
    playerSize: PropTypes.bool,
    viewability: PropTypes.bool,
    viewabilityTargeting: PropTypes.bool,
    device: PropTypes.bool,
    os: PropTypes.bool,
    browser: PropTypes.bool,
    geographyTooltip: PropTypes.bool,
  }).isRequired,
};

export default TargetingTab;
