import { useEffect } from 'react';
import { FormProvider, useFormContext } from 'react-hook-form';
import { useQuery } from 'react-query';

import { capitalize } from 'lodash-es';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuFormInputSelect from '@material-hu/components/design-system/Inputs/Select/form';
import HuPills from '@material-hu/components/design-system/Pills';
import HuSkeleton from '@material-hu/components/design-system/Skeleton';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { getSmTicketPillType } from 'src/pages/dashboard/ServiceManagement/utils';
import { getStates } from 'src/services/workflowsService';
import {
  FlowNode,
  NodeType,
  ServiceStatus,
  ServiceStatusDictionary,
  ServiceType,
} from 'src/types/workflows';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { workflowsKeys } from '../../queries';
import { InvalidNodeInfo } from '../../utils';

type ChangeFieldStatusProps = {
  node?: FlowNode;
  invalidNodes?: InvalidNodeInfo[];
};

const ChangeFieldStatus = ({ node, invalidNodes }: ChangeFieldStatusProps) => {
  const HuGoThemeProvider = useHuGoTheme();
  const { t } = useLokaliseTranslation('workflows');
  const { enqueueSnackbar } = useHuSnackbar();
  const form = useFormContext();

  useEffect(() => {
    if (node) form.setValue('node', node);
    const isNewNode = form.getValues('node').type === NodeType.NEW;

    form.setValue('node.type', NodeType.CHANGE_STATE);
    form.setValue('node.newAssigneeId', undefined);

    if (isNewNode) {
      form.setValue('node.name', t('update_state'));
    }
  }, []);

  const { data: states, isLoading } = useQuery(
    workflowsKeys.states(ServiceType.INCIDENT),
    () => getStates(ServiceType.INCIDENT),
    {
      select: response =>
        response?.data
          ?.filter(
            state =>
              ![ServiceStatus.ASSIGNED, ServiceStatus.UNASSIGNED].includes(
                ServiceStatusDictionary[state.name],
              ),
          )
          ?.map(state => ({
            label: state.name,
            value: state.id,
          })) || [],
      onError: () => {
        enqueueSnackbar({
          title: t('states_error'),
          variant: 'error',
        });
      },
    },
  );

  const nodeIsInvalid = invalidNodes?.some(
    n => n.id === form.getValues('node').id,
  );
  useEffect(() => {
    if (nodeIsInvalid && states?.length) {
      form.trigger();
    }
  }, [nodeIsInvalid, states]);

  return (
    <HuGoThemeProvider>
      <FormProvider {...form}>
        <Stack sx={{ height: '100%', gap: 2 }}>
          <Typography variant="globalS">
            {t('change_status_description')}
          </Typography>
          <Stack
            sx={{
              backgroundColor: theme =>
                theme.palette.new.background.elements.grey,
              borderRadius: 2,
              gap: 2,
              p: 2,
            }}
          >
            {!isLoading && states && (
              <HuFormInputSelect
                inputProps={{
                  label: t('choose_status'),
                  options: states,
                  placeholder: t('choose_status_placeholder'),
                  renderOption: option => (
                    <HuPills
                      type={getSmTicketPillType(option.label)}
                      label={capitalize(option.label)}
                      hasIcon={false}
                      sx={{ my: 0.5 }}
                    />
                  ),
                }}
                name="node.newStateId"
                rules={{
                  required: {
                    value: true,
                    message: t('error_state_required'),
                  },
                }}
              />
            )}
            {isLoading && (
              <HuSkeleton
                height={50}
                isLoading
              />
            )}
          </Stack>
        </Stack>
      </FormProvider>
    </HuGoThemeProvider>
  );
};

export default ChangeFieldStatus;
