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

import { TYPE_ACCOUNT, TYPE_ALL, TYPE_OPTIONS } from '../../../../List/constants';
import { DEFAULT_PAGE_OPTIONS } from '../../../constants';

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

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

const NAME_MAX_LENGTH = 100;

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

  const displayName = useSelector(selectors.displayNameSelector);
  const type = useSelector(selectors.typeSelector);
  const account = useSelector(selectors.accountSelector);
  const accountOptions = useSelector(selectors.accountOptionsSelector);
  const defaultPage = useSelector(selectors.defaultPageSelector);
  const visibleInSelfServe = useSelector(selectors.visibleInSelfServeSelector);
  const readOnlyInSelfServe = useSelector(selectors.readOnlyInSelfServeSelector);

  const scheme = useSelector(selectors.schemeSelector);

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

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

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

      <FormRow label="Type">
        <Select
          placeholder="Select Type"
          size={size}
          value={type}
          disabled={!isDuplicate && !!id}
          onChange={(e) => {
            const payload = { type: e.target.value };
            if (e.target.value !== TYPE_ACCOUNT) {
              payload.account = null;
            }

            handleSetState(payload);
          }}
        >
          {TYPE_OPTIONS.filter((o) => o.value !== TYPE_ALL).map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      </FormRow>

      <FormRow label="Account">
        <Stack fullWidth>
          <Autocomplete
            fullWidth
            value={account}
            options={accountOptions || []}
            optionValueKey="id"
            optionLabelKey="name"
            loading={!accountOptions}
            size={size}
            filterSelectedOptions
            disabled={type !== TYPE_ACCOUNT}
            onChange={(e, selected) => {
              handleSetState({
                account: selected,
              });
            }}
            onOpen={() => {
              dispatch(getAccountOptionsAction(''));
            }}
            onInputChange={(e, searchText) => dispatch(getAccountOptionsAction(searchText))}
            renderInput={(params) => (
              <TextField
                {...params}
                value=""
                placeholder="Select Account"
                {...getInputPropsByName(scheme, ['account'])}
                onFocus={() => dispatch(removeErrorByPropAction(['account']))}
                label=""
              />
            )}
          />
        </Stack>
      </FormRow>

      <FormRow label="Default Page">
        <Select
          placeholder="Select Default Page"
          size={size}
          value={defaultPage}
          onChange={(e) => handleSetState({ defaultPage: e.target.value })}
        >
          {DEFAULT_PAGE_OPTIONS.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      </FormRow>

      <FormRow label="Visible in Self-serve" tooltip="Whether the role’s users appear in the Users Self-serve">
        <Switch
          color="primary"
          size={size}
          checked={visibleInSelfServe}
          onChange={(e) =>
            handleSetState({
              visibleInSelfServe: e.target.checked,
              readOnlyInSelfServe: true,
            })
          }
        />
      </FormRow>

      <FormRow label="Read-only in Self-serve" tooltip="Whether the role could be assigned in the Users Self-serve">
        <Switch
          color="primary"
          size={size}
          checked={readOnlyInSelfServe}
          disabled={!visibleInSelfServe}
          onChange={(e) =>
            handleSetState({
              readOnlyInSelfServe: e.target.checked,
            })
          }
        />
      </FormRow>
    </>
  );
}

export default DetailsTab;
