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

import { AD_FORMATS, HB_CONNECTOR_STATUSES } from '@/modules/marketplace/hbConnectors/constants';

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

import { Form, FormContent, FormRow, FormSection } from '@/modules/@common/Form';
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Link,
  MenuItem,
  Select,
  Stack,
  Switch,
  TextField,
  Typography,
} from '@/mui/components';

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

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

  const name = useSelector(selectors.nameSelector);
  const code = useSelector(selectors.codeSelector);
  const parameters = useSelector(selectors.parametersSelector);
  const comments = useSelector(selectors.commentsSelector);
  const status = useSelector(selectors.statusSelector);
  const format = useSelector(selectors.formatSelector);

  const router = useRouter();
  const [errors, setErrors] = useState({
    name: null,
    code: null,
    parameters: null,
  });
  const [openDialog, setOpenDialog] = useState(false);

  const [id] = router.query.params;
  const isCreateForm = id === 'new';

  useEffect(() => {
    if (!isCreateForm) {
      dispatch(actions.getConnectorByIdAction({ id }));
    }
  }, []);

  const validateFields = (fields = {}) => {
    let newErrors = { ...errors };
    Object.entries(fields).forEach(([field, value]) => {
      if (field === 'name') {
        if (!value?.length) {
          newErrors = {
            ...newErrors,
            name: 'Required',
          };
        } else {
          newErrors = {
            ...newErrors,
            name: null,
          };
        }
      }

      if (field === 'code') {
        if (!value?.length) {
          newErrors = {
            ...newErrors,
            code: 'Required',
          };
        } else if (!/^\S+$/.test(value)) {
          newErrors = {
            ...newErrors,
            code: 'Code should be without spaces',
          };
        } else {
          newErrors = {
            ...newErrors,
            code: null,
          };
        }
      }

      if (field === 'parameters') {
        try {
          const params = JSON.parse(value);

          if (isCreateForm && Object.keys(params).length === 0) {
            newErrors = {
              ...newErrors,
              parameters: 'Required',
            };
          } else {
            newErrors = {
              ...newErrors,
              parameters: null,
            };
          }
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
        } catch (error) {
          newErrors = {
            ...newErrors,
            parameters: 'The Parameters JavaScript is invalid',
          };
        }
      }
    });
    setErrors(newErrors);
  };

  const handleSubmit = () => {
    validateFields({
      name,
      code,
      parameters,
    });

    if (!(errors.name || errors.code || errors.parameters) && name?.length && code?.length) {
      if (isCreateForm) {
        dispatch(actions.createConnectorAction());
      } else {
        setOpenDialog(true);
      }
    }
  };

  return (
    <div className={styles.Wrapper}>
      <Stack direction="column" fullWidth justifyContent="center" className={styles.Title}>
        <Typography component="div" variant="h6" noWrap>
          {isCreateForm ? 'New HB Connector' : `${name} > Settings`}
        </Typography>
      </Stack>
      <Stack
        spacing={1}
        fullWidth
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        className={styles.Controls}
      >
        <Stack spacing={2} justifyContent="flex-end" alignItems="center" direction="row">
          <Button
            variant="outlined"
            size="small"
            color="primary"
            onClick={() => {
              router.push('/hb-connectors');
              dispatch(actions.resetFormAction());
            }}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            size="small"
            color="primary"
            onClick={handleSubmit}
            disabled={errors.name || errors.code || errors.parameters}
          >
            Save
          </Button>
        </Stack>
      </Stack>
      <Form>
        <FormContent>
          <FormSection>
            <FormRow label="Connector Name">
              <TextField
                data-id="name"
                value={name}
                size="small"
                placeholder="Connector Name"
                {...getRequiredInputProps({
                  fieldName: 'name',
                  error: !!errors?.name?.length,
                  helperText: errors?.name,
                })}
                onChange={({ target: { value } }) => {
                  validateFields({ name: value });
                  dispatch(actions.setFieldAction({ name: value }));
                }}
              />
            </FormRow>
            <FormRow label="Bidder Code">
              <TextField
                data-id="code"
                value={code}
                size="small"
                placeholder="Bidder Code"
                {...getRequiredInputProps({
                  fieldName: 'code',
                  error: !!errors?.code?.length,
                  helperText: errors?.code,
                })}
                onChange={({ target: { value } }) => {
                  validateFields({ code: value });
                  dispatch(actions.setFieldAction({ code: value }));
                }}
                disabled={!isCreateForm}
              />
            </FormRow>
            <FormRow label="Active">
              <Switch
                data-id="status"
                color="primary"
                size="small"
                checked={status === HB_CONNECTOR_STATUSES.enabled}
                onChange={() =>
                  dispatch(
                    actions.setFieldAction({
                      status:
                        status === HB_CONNECTOR_STATUSES.enabled
                          ? HB_CONNECTOR_STATUSES.disabled
                          : HB_CONNECTOR_STATUSES.enabled,
                    }),
                  )
                }
              />
            </FormRow>
            <FormRow label=" Ad Format">
              <Select
                data-id="format"
                size="small"
                variant="outlined"
                value={format}
                onChange={(event) => {
                  dispatch(actions.setFieldAction({ format: event.target.value }));
                }}
              >
                {AD_FORMATS.map((item) => (
                  <MenuItem value={item.value} key={item.key}>
                    {item.label}
                  </MenuItem>
                ))}
              </Select>
            </FormRow>
            <FormRow label={isCreateForm ? 'Parameters' : 'Add New Parameters'} multiline>
              <TextField
                value={parameters}
                placeholder="Parameters"
                size="small"
                multiline
                rows={10}
                {...getRequiredInputProps({
                  fieldName: 'parameters',
                  error: !!errors?.parameters?.length,
                  helperText: (
                    <Typography variant="caption" color="text.primary" component="span" fontWeight={400}>
                      <Link
                        target="_blank"
                        rel="noreferrer"
                        href="https://ac-prod-marketplace-data-in.anyclipsrv.info/v1/api/dtag/platforms/all"
                      >
                        Click here
                      </Link>
                      {' to see parameters of existing connectors'}
                    </Typography>
                  ),
                })}
                onChange={({ target: { value } }) => {
                  validateFields({ parameters: value });
                  dispatch(actions.setFieldAction({ parameters: value }));
                }}
              />
            </FormRow>
            <FormRow label="Comments">
              <TextField
                value={comments}
                placeholder="Comments"
                multiline
                size="small"
                rows={3}
                {...getRequiredInputProps({
                  fieldName: 'comments',
                  label: '',
                  error: !!errors?.comments?.length,
                  helperText: errors?.comments,
                })}
                onChange={({ target: { value } }) => {
                  dispatch(actions.setFieldAction({ comments: value }));
                }}
              />
            </FormRow>
          </FormSection>
        </FormContent>
      </Form>

      <Dialog
        open={openDialog}
        onClose={() => {
          setOpenDialog(false);
        }}
      >
        <DialogTitle
          onClose={() => {
            setOpenDialog(false);
          }}
        >
          Important Notification
        </DialogTitle>
        <DialogContent>
          Any change to an existing HB connector must be pre approved and supported by the Player dev team
        </DialogContent>
        <DialogActions>
          <Button
            variant="contained"
            size="small"
            color="primary"
            onClick={() => {
              dispatch(actions.updateConnectorAction({ id }));
              setOpenDialog(false);
            }}
          >
            OK
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

export default HBConnectorForm;
