import React from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { PCN_GET_MARKETPLACE_DASHBOARD } from '@/modules/@common/acl/constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';
import { DEMAND_TAG_DEFAULT_TIER_VALUES } from '@/modules/marketplace/account/constants';

import * as selectors from '../../redux/selectors';
import * as actions from '../../redux/slices';
import { getInputPropsByName } from '@/modules/@common/Form/helpers';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { showNotificationAction } from '@/modules/layout/redux/slices';
import { parseNumberWithRound } from '@/modules/marketplace/common/helpers';

import { Form, FormContent, FormGroupTitle, FormRow, FormSection } from '@/modules/@common/Form';
import FormImageUploader from '@/modules/@common/Form/FormImageUploader/FormImageUploader';
import ActionAutocomplete from '../DemandSettings/components/TargetingTab/components/ActionAutocomplete';
import { Autocomplete, NumberField, Switch, TextField, ToggleButton, ToggleButtonGroup } from '@/mui/components';

function AdvertiserSettingsTab() {
  const dispatch = useDispatch();

  const scheme = useSelector(selectors.advertiserSettingsValidationSchemeSelector);

  const userPermissions = useSelector(getUserPermissionsSelector);
  const advertiserSettings = useSelector(selectors.advertiserSettingsSelector);

  const {
    countries,
    tier,
    name,
    demandAccountId,
    pbsEnabled,
    profitability,
    frequencyCapAdjustment,
    frequencyCapAdjustmentPerSupply,
    frequencyCapAdjustmentThreshold,
    errors,
    logo,
  } = advertiserSettings;
  const userDemandAccounts = useSelector(selectors.userDemandAccountsSelector);
  const pageConfig = useSelector(selectors.pageConfigSelector);
  const targeting = useSelector(selectors.targetingSelector);
  const { countriesList } = targeting;
  const info = useSelector(selectors.infoSelector);

  const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);

  return (
    <Form>
      <FormContent>
        <FormSection>
          <FormGroupTitle>Details</FormGroupTitle>
          <FormRow label="Name">
            <TextField
              size="small"
              value={name}
              placeholder="Enter Advertiser Name"
              onChange={({ target }) => {
                const { name: nameError, ...restErrors } = errors;
                dispatch(
                  actions.setAdvertiserSettingsTabAction({
                    name: target.value,
                    errors: restErrors,
                  }),
                );
              }}
              {...getInputPropsByName(scheme, ['advertiserSettings.name'])}
              onFocus={() =>
                dispatch(actions.advertiserSettingsValidationRemoveErrorByPropAction(['advertiserSettings.name']))
              }
            />
          </FormRow>
          <FormRow label="Demand Account">
            <Autocomplete
              value={
                pageConfig?.isCreatingNew
                  ? userDemandAccounts?.find((item) => item.id === demandAccountId)
                  : { id: demandAccountId, name: info?.accountName ?? '' }
              }
              options={userDemandAccounts}
              optionLabelKey="name"
              onChange={(e, option) => {
                const { demandAccountId: error, ...restErrors } = errors;
                dispatch(
                  actions.setAdvertiserSettingsTabAction({
                    demandAccountId: option?.id ?? null,
                    errors: restErrors,
                  }),
                );
              }}
              onOpen={() => {
                if (isAdminMP) {
                  dispatch(actions.getHubsAndDemandAccountsAction());
                }
              }}
              size="small"
              disabled={!pageConfig?.isCreatingNew}
              renderInput={(params) => (
                <TextField
                  {...params}
                  placeholder="Select Demand Account"
                  onChange={({ target }) => {
                    if (isAdminMP) {
                      dispatch(
                        actions.getHubsAndDemandAccountsAction({
                          search: target.value,
                        }),
                      );
                    }
                  }}
                  size="small"
                  {...getInputPropsByName(scheme, ['advertiserSettings.demandAccountId'])}
                  onFocus={() =>
                    dispatch(
                      actions.advertiserSettingsValidationRemoveErrorByPropAction([
                        'advertiserSettings.demandAccountId',
                      ]),
                    )
                  }
                />
              )}
            />
          </FormRow>

          <FormRow
            label={isAdminMP ? 'Geography' : 'Geography Targeting'}
            tooltip="Set geography targeting that will be applicable to all demand tags associated with this advertiser"
          >
            <ActionAutocomplete
              label=""
              value={countries}
              options={countriesList}
              onChange={(data) => dispatch(actions.setAdvertiserSettingsTabAction({ countries: data }))}
              size="small"
            />
          </FormRow>

          <FormRow
            label="PBS Enabled"
            tooltip="Enable this for advertisers using tags of type HB Adapter. Keep it disabled for GAM, APS (Amazon), VPAID, or MP4 demand."
          >
            <Switch
              color="primary"
              size="small"
              checked={pbsEnabled}
              onChange={() =>
                dispatch(
                  actions.setAdvertiserSettingsTabAction({
                    pbsEnabled: !pbsEnabled,
                  }),
                )
              }
            />
          </FormRow>

          {isAdminMP && (
            <>
              <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.setAdvertiserSettingsTabAction({
                            tier: item.value,
                          }),
                        )
                      }
                    >
                      {item.value}
                    </ToggleButton>
                  ))}
                </ToggleButtonGroup>
              </FormRow>

              <FormRow label="Tag Profitability Indicator">
                <Switch
                  color="primary"
                  size="small"
                  checked={profitability}
                  onChange={() =>
                    dispatch(
                      actions.setAdvertiserSettingsTabAction({
                        profitability: !profitability,
                      }),
                    )
                  }
                />
              </FormRow>
            </>
          )}

          <FormRow
            label="Auto Frequency Cap Adjustment"
            tooltip="Toggle ON to allow all demand tags under this advertiser to automatically adjust their Frequency Cap based on performance. Toggle OFF to maintain a fixed Frequency Cap for all demand tags under this advertiser. Note: Only demand tags with Frequency Cap enabled are eligible for participation"
          >
            <Switch
              color="primary"
              size="small"
              checked={frequencyCapAdjustment}
              onChange={() => {
                const nextValue = !frequencyCapAdjustment;

                dispatch(
                  actions.setAdvertiserSettingsTabAction({
                    frequencyCapAdjustment: nextValue,
                  }),
                );

                if (nextValue) {
                  dispatch(
                    actions.setAdvertiserSettingsTabAction({
                      frequencyCapAdjustmentPerSupply: nextValue,
                    }),
                  );
                }
              }}
            />
          </FormRow>

          {frequencyCapAdjustment && (
            <>
              <FormRow
                label="Auto Optimization per Supply tag"
                tooltip="When enabled, the frequency cap will be automatically adjusted separately for each supply tag based on its individual performance"
              >
                <Switch
                  color="primary"
                  size="small"
                  checked={frequencyCapAdjustmentPerSupply}
                  onChange={() =>
                    dispatch(
                      actions.setAdvertiserSettingsTabAction({
                        frequencyCapAdjustmentPerSupply: !frequencyCapAdjustmentPerSupply,
                      }),
                    )
                  }
                />
              </FormRow>
              <FormRow
                label="Fill Rate Threshold %"
                tooltip="Sets the fill rate target. If actual fill is above this value, frequency cap increases. If below, frequency cap decreases."
              >
                <NumberField
                  min={0}
                  step={1}
                  max={100}
                  maxDecimals={10}
                  variant="outlined"
                  size="small"
                  textAlign="left"
                  shape="rounded"
                  label="Required"
                  value={
                    frequencyCapAdjustmentThreshold?.length === 0 ||
                    Number.isNaN(Number(frequencyCapAdjustmentThreshold))
                      ? ''
                      : parseNumberWithRound(frequencyCapAdjustmentThreshold * 100)
                  }
                  placeholder="Enter Fill Rate Threshold"
                  onChange={({ target }) => {
                    const { frequencyCapAdjustmentThreshold: skipError, ...restErrors } = errors;
                    dispatch(
                      actions.setAdvertiserSettingsTabAction({
                        frequencyCapAdjustmentThreshold: target.value?.length
                          ? parseNumberWithRound(Math.trunc(target.value) / 100)
                          : '',
                        errors: restErrors,
                      }),
                    );
                  }}
                  {...getInputPropsByName(scheme, ['advertiserSettings.frequencyCapAdjustmentThreshold'])}
                  onFocus={() =>
                    dispatch(
                      actions.advertiserSettingsValidationRemoveErrorByPropAction([
                        'advertiserSettings.frequencyCapAdjustmentThreshold',
                      ]),
                    )
                  }
                />
              </FormRow>
            </>
          )}

          <FormRow label="Logo">
            <FormImageUploader
              imageWidth={64}
              imageHeight={64}
              image={logo}
              accept="image/*"
              restrictionMessage={'JPEG, PNG.\n It will be converted and resized to 64px*64px'}
              onValidate={(file) => {
                const allowedExtensions = ['jpg', 'jpeg', 'png'];
                const extension = file.name.split('.').pop();

                if (!allowedExtensions.some((ext) => ext === extension)) {
                  dispatch(
                    showNotificationAction({
                      type: TYPE_ERROR,
                      message: `Invalid file extension, valid only (${allowedExtensions.join(',')})`,
                    }),
                  );

                  return false;
                }

                return true;
              }}
              onRemove={() => {
                dispatch(actions.setAdvertiserSettingsTabAction({ logo: '', logoFile: null }));
              }}
              onLoad={(event, logoFile, logoBase64Url) => {
                dispatch(actions.setAdvertiserSettingsTabAction({ logo: logoBase64Url, logoFile }));
              }}
            />
          </FormRow>
        </FormSection>
      </FormContent>
    </Form>
  );
}

export default AdvertiserSettingsTab;
