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

import * as selectors from '../../redux/selectors';
import * as actions from '../../redux/slices';
import { getInputPropsByName } from '@/modules/@common/Form/helpers';

import { Form, FormContent, FormGroupTitle, FormRow, FormSection } from '@/modules/@common/Form';
import { Button, Stack, TextField, Tooltip, Typography } from '@/mui/components';

import styles from './KeyListForm.module.scss';

function KeyValueForm() {
  const store = useStore();
  const dispatch = useDispatch();

  const scheme = useSelector(selectors.schemeValueFormSelector);

  const keyName = useSelector(selectors.keyNameSelector);
  const keyValue = useSelector(selectors.keyValueSelector);

  const router = useRouter();

  const { id } = router.query;
  const isCreateForm = id === 'new';

  const clearForm = () => {
    dispatch(actions.setInitialFormAction());
  };

  useEffect(() => {
    clearForm();

    if (!isCreateForm) {
      dispatch(actions.getAvailableKeyByIdAction({ id }));
    }
  }, []);

  const handleSubmit = () => {
    const state = store.getState();
    const allProps = selectors.fullAccessToStoreFieldsForValidation(state);

    const { validation, errorList } = actions.validateValueFormFields(
      selectors.schemeValueFormSelector(state).map(({ fieldName }) => fieldName),
      allProps,
    );

    if (errorList.length) {
      const errorField = errorList[0];

      dispatch(actions.setScrollToFieldNameValueFormAction(errorField.fieldName));
    } else if (isCreateForm) {
      dispatch(actions.createAvailableKeyAction());
    } else {
      dispatch(actions.updateAvailableKeyAction({ id }));
    }

    dispatch(actions.setErrorByPropValueFormAction(validation));
  };

  const headerText = isCreateForm ? 'Adding New Key' : `${keyName} Key`;

  return (
    <div className={styles.Wrapper}>
      <Stack direction="column" fullWidth justifyContent="center" className={styles.Title}>
        <Typography component="div" variant="h6" noWrap>
          {headerText?.length > 50 ? (
            <Tooltip title={headerText}>
              <span>{`${headerText.substring(0, 50)}...  Key`}</span>
            </Tooltip>
          ) : (
            headerText
          )}
        </Typography>
      </Stack>
      <Stack
        spacing={1}
        fullWidth
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        className={styles.Controls}
      >
        <div />
        <Stack direction="row" spacing={2} alignItems="center">
          <Button
            size="small"
            onClick={() => {
              router.back();
              clearForm();
            }}
            variant="outlined"
          >
            Cancel
          </Button>
          <Button size="small" variant="contained" color="primary" onClick={handleSubmit}>
            Save
          </Button>
        </Stack>
      </Stack>
      <Form>
        <FormContent>
          <FormSection>
            <FormGroupTitle>Basic Setting</FormGroupTitle>
            <FormRow label="Name">
              <TextField
                data-id="keyName"
                value={keyName}
                variant="outlined"
                placeholder="Enter Name"
                size="small"
                onChange={({ target }) => {
                  dispatch(
                    actions.setFieldAction({
                      keyName: target.value,
                    }),
                  );
                }}
                {...getInputPropsByName(scheme, ['keyName'])}
                onFocus={() => dispatch(actions.removeErrorByPropValueFormAction(['keyName']))}
              />
            </FormRow>
            <FormRow label="Key">
              <TextField
                value={keyValue}
                placeholder="Enter Key"
                size="small"
                onChange={({ target }) => {
                  dispatch(
                    actions.setFieldAction({
                      keyValue: target.value,
                    }),
                  );
                }}
                {...getInputPropsByName(scheme, ['keyValue'])}
                onFocus={() => dispatch(actions.removeErrorByPropValueFormAction(['keyValue']))}
              />
            </FormRow>
          </FormSection>
        </FormContent>
      </Form>
    </div>
  );
}

export default KeyValueForm;
