import React, { useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';

import { STATUSES_ACTIVE, STATUSES_INACTIVE } from '../../../../List/constants';
import { OPTION_ALL, OPTION_ALL_ID } from '../../../constants';

import { getCanReadOnly } from '../../../helpers/getRestrictions';
import * as selectors from '../../../redux/selectors';
import { getAccountOptionsAction, removeErrorByPropAction, setAction } from '../../../redux/slices';
import { getInputPropsByName } from '@/modules/@common/Form/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

import { FormRow, useFormSettings } from '@/modules/@common/Form';
import { Autocomplete, Switch, TextField } from '@/mui/components';

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

  // selectors
  const account = useSelector(selectors.accountSelector);
  const allSites = useSelector(selectors.allSitesSelector);
  const accountOptions = useSelector(selectors.accountOptionsSelector);
  const publisherIds = useSelector(selectors.publisherIdsSelector);
  const lookerReportId = useSelector(selectors.lookerReportIdSelector);
  const uiName = useSelector(selectors.uiNameSelector);
  const description = useSelector(selectors.descriptionSelector);
  const enabled = useSelector(selectors.enabledSelector);
  const scheme = useSelector(selectors.schemeSelector);
  const userPermissions = useSelector(getUserPermissionsSelector);

  const publisherOptions = useMemo(() => [{ ...OPTION_ALL }, ...(account?.publishers || [])], [account?.publishers]);

  const hubValue = useMemo(() => {
    let value = [];

    if (allSites) {
      value = [{ ...OPTION_ALL }];
    } else if (publisherIds?.length) {
      value = publisherIds.map((id$) => {
        const name = account?.publishers?.find((p) => p.id === id$)?.name ?? '';

        return {
          name,
          id: id$,
        };
      });
    }

    return value;
  }, [account?.publishers, allSites, publisherIds]);

  const id = parseInt(router.query.id, 10);
  const canReadOnly = getCanReadOnly(id, userPermissions);

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

  return (
    <>
      <FormRow label="Account">
        <Autocomplete
          size={size}
          options={accountOptions || []}
          value={account}
          disabled={canReadOnly}
          optionLabelKey="name"
          optionValueKey="id"
          renderInput={(params) => (
            <TextField
              {...params}
              value=""
              placeholder="Select Account"
              {...getInputPropsByName(scheme, ['account'])}
              onFocus={() => dispatch(removeErrorByPropAction(['account']))}
            />
          )}
          filterSelectedOptions
          onOpen={() => dispatch(getAccountOptionsAction())}
          onInputChange={(event) => {
            if (event) {
              dispatch(getAccountOptionsAction({ searchText: event.target.value }));
            }
          }}
          onChange={(e, account$) =>
            handleSetState({
              account: account$,
              publisherIds: [],
            })
          }
        />
      </FormRow>
      <FormRow label="Hub">
        <Autocomplete
          size={size}
          options={publisherOptions}
          value={hubValue}
          multiple
          optionLabelKey="name"
          optionValueKey="id"
          filterSelectedOptions
          disableCloseOnSelect
          disabled={!account || canReadOnly}
          renderInput={(params) => (
            <TextField
              {...params}
              placeholder="Select Hub"
              {...getInputPropsByName(scheme, ['publisherIds'])}
              onFocus={() => dispatch(removeErrorByPropAction(['publisherIds']))}
            />
          )}
          onChange={(e, publisherIds$, reason, single) => {
            const isAll = single?.option?.id === OPTION_ALL_ID;

            handleSetState({
              allSites: reason !== 'removeOption' && isAll ? 1 : 0,
              publisherIds:
                reason === 'clear' || isAll
                  ? []
                  : publisherIds$.filter((item) => item.id !== OPTION_ALL_ID).map((item) => item.id),
            });
          }}
        />
      </FormRow>
      <FormRow label="Status">
        <Switch
          color="primary"
          size={size}
          checked={!!enabled}
          disabled={canReadOnly}
          onChange={(e) =>
            handleSetState({
              enabled: e.target.checked ? STATUSES_ACTIVE : STATUSES_INACTIVE,
            })
          }
        />
      </FormRow>
      <FormRow label="Looker Dashboard ID">
        <TextField
          size={size}
          placeholder="Enter Looker Id"
          value={lookerReportId}
          disabled={canReadOnly}
          inputProps={{
            maxlength: 50,
          }}
          onChange={(e) => handleSetState({ lookerReportId: e.target.value })}
          {...getInputPropsByName(scheme, ['lookerReportId'])}
          onFocus={() => dispatch(removeErrorByPropAction(['lookerReportId']))}
        />
      </FormRow>

      <FormRow label="Name">
        <TextField
          size={size}
          placeholder="Enter Name"
          value={uiName}
          disabled={canReadOnly}
          inputProps={{
            maxlength: 50,
          }}
          onChange={(e) => handleSetState({ uiName: e.target.value })}
          {...getInputPropsByName(scheme, ['uiName'])}
          onFocus={() => dispatch(removeErrorByPropAction(['uiName']))}
        />
      </FormRow>

      <FormRow label="Description">
        <TextField
          size={size}
          rows={4}
          multiline
          placeholder="Enter Description"
          value={description}
          disabled={canReadOnly}
          inputProps={{
            maxlength: 50,
          }}
          onChange={(e) => handleSetState({ description: e.target.value })}
          {...getInputPropsByName(scheme, ['description'])}
          label=""
          onFocus={() => dispatch(removeErrorByPropAction(['description']))}
        />
      </FormRow>
    </>
  );
}

export default GeneralTab;
