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

import { useDrawer } from '@material-hu/hooks/useDrawer';
import { IconReplace, IconUserEdit } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuTitle from '@material-hu/components/design-system/Title';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { FlowNode, NodeType, WorkflowJson } from 'src/types/workflows';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { updateNode, type InvalidNodeInfo } from '../../utils';

import ActionInfoPillTooltip from '../ActionInfoPillTooltip';

import ChangeFieldAssignee from './ChangeFieldAssignee';
import ChangeFieldStatus from './ChangeFieldStatus';

type Props = {
  resetNodes: (newBody?: WorkflowJson, realign?: boolean) => void;
  onClose: () => void;
  node?: FlowNode;
  onInvalidNode?: (invalidNode: InvalidNodeInfo) => void;
  onValidNode?: (nodeId: string) => void;
};

const ChangeField = ({
  resetNodes,
  onClose: closeChange,
  node,
  onInvalidNode,
  onValidNode,
}: Props) => {
  const { t } = useLokaliseTranslation(['workflows', 'general']);
  const HuGoThemeProvider = useHuGoTheme();
  const workflowForm = useFormContext();

  const baseNode =
    node ||
    workflowForm
      .getValues()
      .body.tasks?.find((task: FlowNode) => task.type === NodeType.NEW);

  const drawerForm = useForm({
    defaultValues: {
      node: baseNode,
    },
    mode: 'onChange',
  });

  const { node: newNode } = drawerForm.watch();

  const {
    showDrawer: showChangeStatusDrawer,
    drawer: changeStatusDrawer,
    closeDrawer,
  } = useDrawer(ChangeFieldStatus, {
    title: t('change_status'),
    onClose: () => {
      closeDrawer();
    },
    primaryButtonProps: {
      children: t('general:add'),
      onClick: () => {
        updateNode(
          workflowForm,
          newNode,
          t,
          resetNodes,
          onInvalidNode,
          onValidNode,
        );
        closeDrawer();
        closeChange();
      },
      fullWidth: true,
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      onClick: () => {
        closeDrawer();
        drawerForm.reset();
      },
      fullWidth: true,
    },
    hasBackButton: true,
  });

  const {
    /** Temporally hidden functionality */
    // showDrawer: showChangeAssigneeDrawer,
    drawer: changeAssigneeDrawer,
    closeDrawer: closeAssigneeDrawer,
  } = useDrawer(ChangeFieldAssignee, {
    title: t('change_assignee'),
    onClose: () => {
      closeAssigneeDrawer();
    },
    primaryButtonProps: {
      children: t('general:add'),
      onClick: () => {
        updateNode(
          workflowForm,
          newNode,
          t,
          resetNodes,
          onInvalidNode,
          onValidNode,
        );
        closeAssigneeDrawer();
        closeChange();
      },
      fullWidth: true,
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      onClick: () => {
        closeAssigneeDrawer();
        drawerForm.reset();
      },
      fullWidth: true,
    },
    hasBackButton: true,
  });

  return (
    <HuGoThemeProvider>
      <FormProvider {...drawerForm}>
        {changeStatusDrawer}
        {changeAssigneeDrawer}
      </FormProvider>
      <Stack sx={{ height: '100%', gap: 2 }}>
        <Typography variant="globalS">{t('change_field_select')}</Typography>
        <HuCardContainer
          sx={{
            width: '100%',
            minHeight: 76,
            ':hover': {
              boxShadow: 1,
            },
          }}
          onClick={showChangeStatusDrawer}
          noHover
        >
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 1,
            }}
          >
            <HuAvatar
              variant="circular"
              color="highlight"
              Icon={IconReplace}
            />
            <HuTitle
              variant="S"
              title={t('change_status')}
              description={t('change_status_description')}
            />
          </Stack>
        </HuCardContainer>
        <HuCardContainer
          sx={{
            width: '100%',
            minHeight: 72,
            cursor: 'default',
            borderColor: ({ palette }) =>
              palette.hugoBackground?.neutralBgSecondary,
          }}
          noHover
        >
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 1,
                mr: 1,
                opacity: 0.65,
              }}
            >
              <HuAvatar
                variant="circular"
                color="highlight"
                Icon={IconUserEdit}
              />
              <HuTitle
                variant="S"
                title={t('change_assignee')}
                description={t('change_assignee_sub')}
              />
            </Stack>
            <ActionInfoPillTooltip type="soon" />
          </Stack>
        </HuCardContainer>
      </Stack>
    </HuGoThemeProvider>
  );
};

export default ChangeField;
