import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';

import {
  DEMAND_TAG_FORMAT,
  DISPLAY_TYPE_OPTIONS,
  SOURCE_TAG_OPTIONS,
  SUPPLY_TAG_PUBLISHER_DEMAND_ONLY,
} 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 { parseNumberWithRound } from '@/modules/marketplace/common/helpers';

import { FormRow } from '@/modules/@common/Form';
import { MenuItem, Select, Switch, TextField, ToggleButton, ToggleButtonGroup } from '@/mui/components';

const floorRegex = /^\d+(\.\d{0,2})?$/;

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

  const pageConfig = useSelector(selectors.pageConfigSelector);
  const info = useSelector(selectors.infoSelector);
  const supply = useSelector(selectors.supplySelector);

  const {
    name,
    source,
    platformId,
    format,
    displayType,
    floorPrice,
    waterfallNote,
    publisherDemandOnly,
    automaticFloorPrice,
    fillRateThreshold,
    minimumFloor,
    maximumFloor,
    errors,
  } = supply;

  const { isCreatingNew, isDuplicate } = pageConfig ?? {};

  useEffect(() => {
    if (isCreatingNew) {
      // set default values
      if (format === DEMAND_TAG_FORMAT.video) {
        dispatch(
          actions.setSupplyTabAction({
            floorPrice: {
              ...floorPrice,
              viewableFloor: '1.25',
              floor: '0.95',
              firstRequestFloor: '3.75',
            },
          }),
        );
      }
      if (format === DEMAND_TAG_FORMAT.display) {
        if (displayType === DISPLAY_TYPE_OPTIONS[0].value) {
          dispatch(
            actions.setSupplyTabAction({
              floorPrice: {
                ...floorPrice,
                viewableFloor: '0.75',
                floor: '0.65',
                firstRequestFloor: '2.25',
              },
            }),
          );
        }

        if (displayType === DISPLAY_TYPE_OPTIONS[1].value) {
          dispatch(
            actions.setSupplyTabAction({
              floorPrice: {
                ...floorPrice,
                viewableFloor: '0.55',
                floor: '0.45',
                firstRequestFloor: '1.65',
              },
            }),
          );
        }
      }
    }
  }, [isCreatingNew, format, displayType]);

  return (
    <>
      <FormRow label="Tag Name">
        <TextField
          size="small"
          value={name}
          placeholder="Enter Tag Name"
          {...getRequiredInputProps({
            fieldName: 'name',
            error: !!errors?.name?.length,
            helperText: errors?.name,
          })}
          onChange={({ target }) => {
            const { name: nameError, ...restErrors } = errors;
            dispatch(actions.setSupplyTabAction({ name: target.value, errors: restErrors }));
          }}
        />
      </FormRow>

      {props.isAdminMP && (
        <>
          <FormRow label="Source">
            <Select
              variant="outlined"
              size="small"
              id="source"
              value={source}
              onChange={(event) => {
                dispatch(actions.setSupplyTabAction({ source: event.target.value }));
              }}
              disabled={!(isCreatingNew || isDuplicate)}
            >
              {SOURCE_TAG_OPTIONS.map((item) => (
                <MenuItem key={item.value} value={item.value}>
                  {item.label}
                </MenuItem>
              ))}
            </Select>
          </FormRow>

          {source !== SOURCE_TAG_OPTIONS[0].value && (
            <FormRow label="Platform ID">
              <TextField
                size="small"
                value={platformId}
                placeholder="Enter Platform ID"
                disabled={!(isCreatingNew || isDuplicate)}
                {...getRequiredInputProps({
                  fieldName: 'platformId',
                  error: !!errors?.platformId?.length,
                  helperText: errors?.platformId,
                })}
                onChange={({ target }) => {
                  const { platformId: platformIdError, ...restErrors } = errors;
                  dispatch(actions.setSupplyTabAction({ platformId: target.value, errors: restErrors }));
                }}
              />
            </FormRow>
          )}
        </>
      )}

      {info?.accountType !== 'VAST' && // from info by id
        pageConfig?.supplyAccount?.accountType !== 'VAST' && ( // from queries for new tag
          <FormRow label="Format">
            <ToggleButtonGroup
              equalWidth
              size="small"
              color="primary"
              variant="outlined"
              disabled={!isCreatingNew}
              value={format}
            >
              <ToggleButton
                value={DEMAND_TAG_FORMAT.video}
                onClick={() =>
                  dispatch(
                    actions.setSupplyTabAction({
                      format: DEMAND_TAG_FORMAT.video,
                    }),
                  )
                }
              >
                Video
              </ToggleButton>
              <ToggleButton
                value={DEMAND_TAG_FORMAT.display}
                onClick={() =>
                  dispatch(
                    actions.setSupplyTabAction({
                      format: DEMAND_TAG_FORMAT.display,
                    }),
                  )
                }
              >
                Display
              </ToggleButton>
              <ToggleButton
                value={DEMAND_TAG_FORMAT.sponsored}
                onClick={() =>
                  dispatch(
                    actions.setSupplyTabAction({
                      format: DEMAND_TAG_FORMAT.sponsored,
                    }),
                  )
                }
              >
                Sponsored
              </ToggleButton>
            </ToggleButtonGroup>
          </FormRow>
        )}

      {props.isAdminMP && (
        <>
          {format === DEMAND_TAG_FORMAT.display && (
            <FormRow label="Display Type">
              <ToggleButtonGroup
                equalWidth
                size="small"
                color="primary"
                variant="outlined"
                disabled={!isCreatingNew}
                value={displayType}
              >
                {DISPLAY_TYPE_OPTIONS.map((item) => (
                  <ToggleButton
                    key={item.value}
                    value={item.value}
                    onClick={() =>
                      dispatch(
                        actions.setSupplyTabAction({
                          displayType: item.value,
                        }),
                      )
                    }
                  >
                    {item.label}
                  </ToggleButton>
                ))}
              </ToggleButtonGroup>
            </FormRow>
          )}

          {format !== DEMAND_TAG_FORMAT.sponsored && (
            <>
              <FormRow label="Default HB Floor - Viewable">
                <TextField
                  size="small"
                  value={floorPrice.viewableFloor}
                  placeholder="0.00"
                  {...getRequiredInputProps({
                    fieldName: 'viewableFloor',
                    error: !!errors?.viewableFloor?.length,
                  })}
                  onChange={({ target }) => {
                    const { viewableFloor, ...restErrors } = errors;
                    if (floorRegex.test(target.value) || target.value.length === 0) {
                      dispatch(
                        actions.setSupplyTabAction({
                          floorPrice: {
                            ...floorPrice,
                            viewableFloor: target.value,
                          },
                          errors: restErrors,
                        }),
                      );
                    }
                  }}
                />
              </FormRow>
              <FormRow label="Default HB Floor - Non-Viewable">
                <TextField
                  size="small"
                  value={floorPrice.floor}
                  placeholder="0.00"
                  {...getRequiredInputProps({
                    fieldName: 'floor',
                    error: !!errors?.floor?.length,
                  })}
                  onChange={({ target }) => {
                    const { floor, ...restErrors } = errors;
                    if (floorRegex.test(target.value) || target.value.length === 0) {
                      dispatch(
                        actions.setSupplyTabAction({
                          floorPrice: {
                            ...floorPrice,
                            floor: target.value,
                          },
                          errors: restErrors,
                        }),
                      );
                    }
                  }}
                />
              </FormRow>
              <FormRow label="First Request HB Floor">
                <TextField
                  size="small"
                  value={floorPrice.firstRequestFloor}
                  placeholder="0.00"
                  {...getRequiredInputProps({
                    fieldName: 'firstRequestFloor',
                    error: !!errors?.firstRequestFloor?.length,
                  })}
                  onChange={({ target }) => {
                    const { firstRequestFloor, ...restErrors } = errors;
                    if (floorRegex.test(target.value) || target.value.length === 0) {
                      dispatch(
                        actions.setSupplyTabAction({
                          floorPrice: {
                            ...floorPrice,
                            firstRequestFloor: target.value,
                          },
                          errors: restErrors,
                        }),
                      );
                    }
                  }}
                />
              </FormRow>

              <FormRow label="Automatic Floor Adjustment">
                <Switch
                  color="primary"
                  size="small"
                  checked={automaticFloorPrice}
                  onChange={() =>
                    dispatch(
                      actions.setSupplyTabAction({
                        automaticFloorPrice: !automaticFloorPrice,
                      }),
                    )
                  }
                />
              </FormRow>
            </>
          )}

          {automaticFloorPrice && (
            <>
              <FormRow label="Fill Rate Threshold">
                <TextField
                  size="small"
                  type="number"
                  value={
                    fillRateThreshold?.length === 0 || Number.isNaN(Number(fillRateThreshold))
                      ? ''
                      : parseNumberWithRound(fillRateThreshold * 100)
                  }
                  placeholder="Enter Fill Rate Threshold"
                  {...getRequiredInputProps({
                    fieldName: 'fillRateThreshold',
                    error: !!errors?.fillRateThreshold?.length,
                    helperText: errors?.fillRateThreshold,
                  })}
                  onChange={({ target }) => {
                    const { fillRateThreshold: fillRateThresholdError, ...restErrors } = errors;
                    dispatch(
                      actions.setSupplyTabAction({
                        fillRateThreshold: target.value?.length
                          ? parseNumberWithRound(Math.trunc(target.value) / 100)
                          : '',
                        errors: restErrors,
                      }),
                    );
                  }}
                />
              </FormRow>

              <FormRow label="Minimum Floor">
                <TextField
                  size="small"
                  value={minimumFloor}
                  placeholder="0.00"
                  {...getRequiredInputProps({
                    fieldName: 'minimumFloor',
                    error: !!errors?.minimumFloor?.length,
                    helperText: errors?.minimumFloor,
                  })}
                  onChange={({ target }) => {
                    const { minimumFloor: minimumFloorError, ...restErrors } = errors;
                    if (floorRegex.test(target.value) || target.value.length === 0) {
                      dispatch(
                        actions.setSupplyTabAction({
                          minimumFloor: target.value,
                          errors: restErrors,
                        }),
                      );
                    }
                  }}
                />
              </FormRow>

              <FormRow label="Maximum Floor">
                <TextField
                  size="small"
                  value={maximumFloor}
                  placeholder="0.00"
                  {...getRequiredInputProps({
                    fieldName: 'maximumFloor',
                    error: !!errors?.maximumFloor?.length,
                    helperText: errors?.maximumFloor,
                  })}
                  onChange={({ target }) => {
                    const { maximumFloor: maximumFloorError, ...restErrors } = errors;
                    if (floorRegex.test(target.value) || target.value.length === 0) {
                      dispatch(
                        actions.setSupplyTabAction({
                          maximumFloor: target.value,
                          errors: restErrors,
                        }),
                      );
                    }
                  }}
                />
              </FormRow>
            </>
          )}

          <FormRow label="Publisher Demand Only">
            <Switch
              color="primary"
              size="small"
              checked={publisherDemandOnly === SUPPLY_TAG_PUBLISHER_DEMAND_ONLY.enabled}
              onChange={() =>
                dispatch(
                  actions.setSupplyTabAction({
                    publisherDemandOnly:
                      publisherDemandOnly === SUPPLY_TAG_PUBLISHER_DEMAND_ONLY.enabled
                        ? SUPPLY_TAG_PUBLISHER_DEMAND_ONLY.disabled
                        : SUPPLY_TAG_PUBLISHER_DEMAND_ONLY.enabled,
                  }),
                )
              }
            />
          </FormRow>
          <FormRow label="Waterfall Note">
            <TextField
              size="small"
              value={waterfallNote}
              placeholder="Enter a Waterfall Note For The AnyClip Operations Team"
              onChange={({ target }) => {
                dispatch(actions.setSupplyTabAction({ waterfallNote: target.value }));
              }}
            />
          </FormRow>
        </>
      )}
    </>
  );
}

BaseSettings.propTypes = {
  isAdminMP: PropTypes.bool.isRequired,
};

export default BaseSettings;
