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

import Typography from '@material-hu/mui/Typography';
import { IconExclamationCircle } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import useTheme from '@material-hu/mui/styles/useTheme';

import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import FormTextArea from '@material-hu/components/design-system/Inputs/TextArea/form';
import FormSwitcher from '@material-hu/components/design-system/Switcher/form';
import { Title } from '@material-hu/components/design-system/Title';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { NodeType } from 'src/types/workflows';
import { useLokaliseTranslation } from 'src/utils/i18n';

import AgentsByGroupAutocomplete from 'src/components/UsersAutocomplete/AgentsByGroupAutocomplete';

type TaskProps = {
  isNewNode?: boolean;
};

const Task = ({ isNewNode = false }: TaskProps) => {
  const { t } = useLokaliseTranslation('workflows');
  const HuGoThemeProvider = useHuGoTheme();
  const theme = useTheme();
  const form = useFormContext();

  const { setValue } = form;

  useEffect(() => {
    setValue('node.type', NodeType.TASK);
    setValue('node.newAssigneeId', undefined);
    setValue('node.newStateId', undefined);
    setValue('node.approverRoles', undefined);
    setValue('node.approverIds', undefined);
    if (isNewNode) {
      setValue('node.blockingTask', true);
    }
  }, [isNewNode, setValue]);

  const { node } = form.watch();
  const hasError = !isNewNode && !node?.assigneeId && !node?.agentGroupId;

  return (
    <HuGoThemeProvider>
      <FormProvider {...form}>
        <Stack sx={{ height: '100%', gap: 3, overflow: 'auto' }}>
          <Stack
            sx={{
              backgroundColor: theme =>
                theme.palette.new.background.layout.default,
              borderRadius: 2,
              gap: 2,
              p: 2,
            }}
          >
            <Stack sx={{ gap: 0.5 }}>
              <Typography
                variant="globalS"
                fontWeight="semiBold"
              >
                {t('tasks.name')}
                <span
                  style={{
                    color: theme.palette.new.text.feedback.error,
                  }}
                >
                  {' *'}
                </span>
              </Typography>
              <FormInputClassic
                name="node.name"
                inputProps={{
                  placeholder: t('write_here'),
                  hasCounter: false,
                }}
                rules={{
                  required: {
                    value: true,
                    message: t('validations:required'),
                  },
                }}
              />
            </Stack>
            <FormTextArea
              name="node.description"
              textAreaProps={{
                label: t('tasks.description'),
                placeholder: t('write_here'),
                simplifyEditor: true,
              }}
            />
          </Stack>
          <Stack
            sx={{
              gap: 2,
              backgroundColor: theme =>
                theme.palette.new.background.layout.default,
              borderRadius: 2,
              p: 2,
              pr: 1,
            }}
          >
            <Title
              variant="S"
              title={
                <>
                  {t('tasks.select_agent')}
                  <span
                    style={{
                      color: theme.palette.new.text.feedback.error,
                    }}
                  >
                    {' *'}
                  </span>
                </>
              }
              description={t('tasks.select_agent_description')}
            />
            <Stack
              sx={{
                backgroundColor: theme =>
                  theme.palette.new.background.layout.tertiary,
                borderRadius: 2,
                p: 2,
                gap: 2,
                ...(hasError && {
                  outline: theme =>
                    `1px solid ${theme.palette.new.border.states.error}`,
                }),
              }}
            >
              {/* TODO: Uncomment when agent groups are implemented in backend. MVP does not include this feature. */}
              {/* <AgentGroupsAutocomplete
                name="node.agentGroupId"
                agentFieldName="node.assigneeId"
                autocompleteProps={{
                  label: t('tasks.agents_group'),
                  placeholder: t('tasks.agents_group_placeholder'),
                }}
              /> */}
              <AgentsByGroupAutocomplete
                name="node.assigneeId"
                agentGroupsFieldName="node.agentGroupId"
                autocompleteProps={{
                  label: t('tasks.assigned_agent'),
                  placeholder: t('tasks.assigned_agent_placeholder'),
                }}
              />
            </Stack>
            {hasError && (
              <Stack
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 0.5,
                }}
              >
                <IconExclamationCircle
                  size={16}
                  color={theme.palette.new.text.feedback.error}
                />
                <Typography
                  variant="globalS"
                  sx={{
                    color: theme.palette.new.text.feedback.error,
                  }}
                >
                  {t('validations:required')}
                </Typography>
              </Stack>
            )}
          </Stack>
          <Stack
            sx={{
              backgroundColor: theme =>
                theme.palette.new.background.layout.default,
              borderRadius: 2,
              p: 2,
            }}
          >
            <FormSwitcher
              name="node.blockingTask"
              switcherProps={{
                title: t('tasks.block_flow'),
                description: t('tasks.block_flow_description'),
              }}
            />
          </Stack>
        </Stack>
      </FormProvider>
    </HuGoThemeProvider>
  );
};

export default Task;
