import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { Inventory2Rounded } from '@mui/icons-material';

import { STATUSES_INACTIVE, STATUSES_OPTIONS_FOR_FORM } from '../../../../List/constants';

import * as selectors from '../../../redux/selectors';
import {
  getHubOptionsAction,
  getXRayCampaignOptionsAction,
  getXRayCreativeOptionsAction,
  removeErrorByPropAction,
  setAction,
} from '../../../redux/slices';
import { getInputPropsByName } from '@/modules/@common/Form/helpers';

import { FormGroupTitle, FormRow, FormSection, useFormSettings } from '@/modules/@common/Form';
import {
  Autocomplete,
  IconButton,
  InputAdornment,
  MenuItem,
  Select,
  Stack,
  TextField,
  Tooltip,
} from '@/mui/components';

const NAME_MAX_LENGTH = 149;

function GeneralTab() {
  const { size } = useFormSettings();
  const dispatch = useDispatch();
  const router = useRouter();

  // selectors
  const hub = useSelector(selectors.hubSelector);
  const hubOptions = useSelector(selectors.hubOptionsSelector);
  const xrayCampaign = useSelector(selectors.xrayCampaignSelector);
  const xrayCampaignOptions = useSelector(selectors.xrayCampaignOptionsSelector);
  const name = useSelector(selectors.nameSelector);
  const status = useSelector(selectors.statusSelector);
  const priority = useSelector(selectors.prioritySelector);
  const xrayCreative1 = useSelector(selectors.xrayCreative1Selector);
  const xrayCreative2 = useSelector(selectors.xrayCreative2Selector);
  const xrayCreative3 = useSelector(selectors.xrayCreative3Selector);
  const xrayCreativeOptionsFromStater = useSelector(selectors.xrayCreativeOptionsSelectors);

  const scheme = useSelector(selectors.schemeSelector);

  const id = parseInt(router.query.id, 10);
  const isDuplicate = router.asPath.split('/').filter(Boolean).reverse()[0] === 'duplicate';

  const shouldDisableWhenUpdate = id && !isDuplicate;

  const xrayCreativeOptions =
    xrayCreativeOptionsFromStater?.filter(
      (o) => ![xrayCreative1?.id, xrayCreative2?.id, xrayCreative3?.id].includes(o.id),
    ) || null;

  // handlers
  const handleSetState = (state) => dispatch(setAction(state));

  return (
    <FormSection>
      <FormRow label="Hub">
        <Stack fullWidth>
          <Autocomplete
            fullWidth
            value={hub}
            options={hubOptions || []}
            optionValueKey="id"
            optionLabelKey="name"
            loading={!hubOptions}
            size={size}
            filterSelectedOptions
            disabled={shouldDisableWhenUpdate}
            onChange={(e, selected) => {
              const payload = { hub: selected };

              if (hub?.id !== selected?.id) {
                payload.xrayCampaign = null;
                payload.xrayCreative1 = null;
                payload.xrayCreative2 = null;
                payload.xrayCreative3 = null;
                payload.watch = null;
                payload.watchChannel = null;
                payload.player = null;
                payload.player = null;
                payload.domains = [];
                payload.video = null;
                payload.people = [];
                payload.brands = [];
                payload.keywords = [];
                payload.labels = [];
              }

              handleSetState(payload);
            }}
            onOpen={() => {
              dispatch(getHubOptionsAction(''));
            }}
            onInputChange={(e, searchText) => dispatch(getHubOptionsAction(searchText))}
            renderInput={(params) => (
              <TextField
                {...params}
                value=""
                placeholder="Select Hub"
                {...getInputPropsByName(scheme, ['hub'])}
                onFocus={() => dispatch(removeErrorByPropAction(['hub']))}
              />
            )}
          />
        </Stack>
      </FormRow>

      <FormRow label="Campaign">
        <Stack fullWidth>
          <Autocomplete
            fullWidth
            value={xrayCampaign}
            options={xrayCampaignOptions || []}
            optionValueKey="id"
            optionLabelKey="name"
            loading={!hubOptions}
            size={size}
            filterSelectedOptions
            disabled={shouldDisableWhenUpdate || !hub}
            onChange={(e, selected) => {
              handleSetState({
                xrayCampaign: selected,
              });
            }}
            onOpen={() => {
              dispatch(getXRayCampaignOptionsAction(''));
            }}
            onInputChange={(e, searchText) => dispatch(getXRayCampaignOptionsAction(searchText))}
            renderInput={(params) => (
              <TextField
                {...params}
                value=""
                placeholder="Select Campaign"
                {...getInputPropsByName(scheme, ['xrayCampaign'])}
                onFocus={() => dispatch(removeErrorByPropAction(['xrayCampaign']))}
              />
            )}
          />
        </Stack>
      </FormRow>

      <FormRow label="Name">
        <TextField
          size={size}
          placeholder="Name"
          value={name}
          inputProps={{ maxLength: NAME_MAX_LENGTH }}
          onChange={(e) => handleSetState({ name: e.target.value })}
          {...getInputPropsByName(scheme, ['name'])}
          onFocus={() => dispatch(removeErrorByPropAction(['name']))}
        />
      </FormRow>

      <FormRow label="Status">
        <Select
          placeholder="Select Status"
          size={size}
          value={status}
          disabled={status === STATUSES_INACTIVE}
          onChange={(e) => handleSetState({ status: e.target.value })}
        >
          {STATUSES_OPTIONS_FOR_FORM.map((option) => (
            <MenuItem key={option.value} value={option.value} disabled={option.value === STATUSES_INACTIVE}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      </FormRow>

      <FormRow label="Priority">
        <Select
          placeholder="Select Priority"
          size={size}
          value={priority}
          onChange={(e) => handleSetState({ priority: e.target.value })}
        >
          {[...Array(10).keys()]
            .map((n) => n + 1)
            .map((option) => (
              <MenuItem key={option} value={option}>
                {option}
              </MenuItem>
            ))}
        </Select>
      </FormRow>

      <FormGroupTitle>Creatives</FormGroupTitle>

      <FormRow label="Creative #1">
        <Stack fullWidth>
          <Autocomplete
            fullWidth
            value={xrayCreative1}
            options={xrayCreativeOptions || []}
            optionValueKey="id"
            optionLabelKey="name"
            loading={!xrayCreativeOptions}
            size={size}
            filterSelectedOptions
            disabled={!hub}
            onChange={(e, selected) => {
              handleSetState({
                xrayCreative1: selected,
              });
            }}
            onOpen={() => {
              dispatch(getXRayCreativeOptionsAction(''));
            }}
            onInputChange={(e, searchText) => dispatch(getXRayCreativeOptionsAction(searchText))}
            renderInput={(params) => (
              <TextField
                {...params}
                value=""
                placeholder="Select Creative  #1"
                InputProps={{
                  ...params.InputProps,
                  ...(xrayCreative1?.status === STATUSES_INACTIVE
                    ? {
                        endAdornment: (
                          <InputAdornment position="end">
                            <Tooltip title="This creative has been archived" disableInteractive>
                              <IconButton onClick={() => null}>
                                <Inventory2Rounded />
                              </IconButton>
                            </Tooltip>
                          </InputAdornment>
                        ),
                      }
                    : {}),
                }}
                {...getInputPropsByName(scheme, ['xrayCreative1'])}
                onFocus={() => dispatch(removeErrorByPropAction(['xrayCreative1']))}
              />
            )}
          />
        </Stack>
      </FormRow>

      <FormRow label="Creative #2">
        <Stack fullWidth>
          <Autocomplete
            fullWidth
            value={xrayCreative2}
            options={xrayCreativeOptions || []}
            optionValueKey="id"
            optionLabelKey="name"
            loading={!xrayCreativeOptions}
            size={size}
            filterSelectedOptions
            disabled={!hub}
            onChange={(e, selected) => {
              handleSetState({
                xrayCreative2: selected,
              });
            }}
            onOpen={() => {
              dispatch(getXRayCreativeOptionsAction(''));
            }}
            onInputChange={(e, searchText) => dispatch(getXRayCreativeOptionsAction(searchText))}
            renderInput={(params) => (
              <TextField
                {...params}
                value=""
                placeholder="Select Creative  #2"
                {...getInputPropsByName(scheme, ['xrayCreative2'])}
                onFocus={() => dispatch(removeErrorByPropAction(['xrayCreative2']))}
                label=""
                InputProps={{
                  ...params.InputProps,
                  ...(xrayCreative2?.status === STATUSES_INACTIVE
                    ? {
                        endAdornment: (
                          <InputAdornment position="end">
                            <Tooltip title="This creative has been archived" disableInteractive>
                              <IconButton onClick={() => null}>
                                <Inventory2Rounded />
                              </IconButton>
                            </Tooltip>
                          </InputAdornment>
                        ),
                      }
                    : {}),
                }}
              />
            )}
          />
        </Stack>
      </FormRow>

      <FormRow label="Creative #3">
        <Stack fullWidth>
          <Autocomplete
            fullWidth
            value={xrayCreative3}
            options={xrayCreativeOptions || []}
            optionValueKey="id"
            optionLabelKey="name"
            loading={!xrayCreativeOptions}
            size={size}
            filterSelectedOptions
            disabled={!hub}
            onChange={(e, selected) => {
              handleSetState({
                xrayCreative3: selected,
              });
            }}
            onOpen={() => {
              dispatch(getXRayCreativeOptionsAction(''));
            }}
            onInputChange={(e, searchText) => dispatch(getXRayCreativeOptionsAction(searchText))}
            renderInput={(params) => (
              <TextField
                {...params}
                value=""
                placeholder="Select Creative  #3"
                {...getInputPropsByName(scheme, ['xrayCreative3'])}
                onFocus={() => dispatch(removeErrorByPropAction(['xrayCreative3']))}
                label=""
                InputProps={{
                  ...params.InputProps,
                  ...(xrayCreative3?.status === STATUSES_INACTIVE
                    ? {
                        endAdornment: (
                          <InputAdornment position="end">
                            <Tooltip title="This creative has been archived" disableInteractive>
                              <IconButton onClick={() => null}>
                                <Inventory2Rounded />
                              </IconButton>
                            </Tooltip>
                          </InputAdornment>
                        ),
                      }
                    : {}),
                }}
              />
            )}
          />
        </Stack>
      </FormRow>
    </FormSection>
  );
}

export default GeneralTab;
