import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';

import { IconInfoCircle } from '@material-hu/icons/tabler';
import { useTheme } from '@material-hu/mui/index';
import Stack from '@material-hu/mui/Stack';
import { tooltipClasses } from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import HuDrawer from '@material-hu/components/design-system/Drawer';
import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuFormSwitcher from '@material-hu/components/design-system/Switcher/form';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

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

import { COLORS } from '../../constants';
import useModuleConfiguration from '../../hooks/useModuleConfiguration';
import { BannerColor } from '../../types';
import { configurationFields } from '../form/form';
import { type ConfigurationForm } from '../ServiceItems';

import BannerColorPreview from './BannerColorPreview';
import FormColorSelect from './FormColorSelect';

const FALLBACK_COLOR = '#2574C6';
const TOOLTIP_BANNER_DELAY = 500;

type Props = {
  open: boolean;
  onClose: () => void;
  onSelect: () => void;
  loading: boolean;
  loadingAction?: boolean;
};

const ConfigurationDrawer: FC<Props> = ({
  open,
  onClose,
  onSelect,
  loading,
  loadingAction = false,
}) => {
  const theme = useTheme();
  const { t } = useLokaliseTranslation(['service_management', 'general']);
  const { watch } = useFormContext<ConfigurationForm>();

  const { moduleConfiguration } = useModuleConfiguration();

  const color = watch(configurationFields.coverColor());
  const csatEnabled = watch(configurationFields.csatEnabled());

  const colorOptions = Object.keys(BannerColor).map(colorEnum => ({
    label: t(`${colorEnum}`),
    value: colorEnum,
  }));

  const csatEnabledChanged = csatEnabled !== moduleConfiguration?.csatEnabled;
  const coverColorChanged = color !== moduleConfiguration?.coverColor;
  const saveButtonDisabled =
    loadingAction || (!coverColorChanged && !csatEnabledChanged);

  return (
    <HuDrawer
      anchor="right"
      open={open}
      onClose={onClose}
      sx={{ zIndex: 1300 }}
      title={t('configurations')}
      primaryButtonProps={{
        children: t('general:save'),
        onClick: onSelect,
        loading: loadingAction,
        disabled: saveButtonDisabled,
        fullWidth: true,
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: onClose,
        disabled: loadingAction,
        fullWidth: true,
      }}
    >
      {loading && <HuSpinner centered />}
      {!loading && (
        <Stack sx={{ gap: 2 }}>
          <Stack
            sx={{
              backgroundColor: ({ palette }) =>
                palette.new.background.elements.grey,
              borderRadius: ({ shape }) => shape.borderRadiusS,
              p: 2,
              gap: 2,
            }}
          >
            <Stack>
              <Stack
                sx={{ flexDirection: 'row', alignItems: 'center', gap: 0.5 }}
              >
                <Typography
                  variant="globalS"
                  sx={{
                    color: theme.palette.new.text.neutral.default,
                    fontWeight: 'fontWeightSemiBold',
                  }}
                >
                  {t('cover')}
                </Typography>
                <HuTooltip
                  title={
                    <BannerColorPreview
                      color={COLORS[color]?.value || FALLBACK_COLOR}
                    />
                  }
                  delay={TOOLTIP_BANNER_DELAY}
                  direction="bottom"
                  slotProps={{
                    arrow: {
                      sx: {
                        display: 'none',
                      },
                    },
                    popper: {
                      sx: {
                        [`& .${tooltipClasses.tooltip}`]: {
                          backgroundColor: 'transparent',
                          borderRadius: ({ shape }) => shape.borderRadiusM,
                        },
                      },
                    },
                  }}
                >
                  <IconInfoCircle
                    size={13}
                    color={theme.palette.new.text.neutral.default}
                  />
                </HuTooltip>
              </Stack>
              <Typography
                variant="globalXS"
                color={theme.palette.new.text.neutral.lighter}
              >
                {t('cover_description')}
              </Typography>
            </Stack>
            <Stack sx={{ gap: 0.5 }}>
              <Typography
                variant="globalS"
                sx={{
                  color: theme.palette.new.text.neutral.default,
                  fontWeight: 'fontWeightSemiBold',
                }}
              >
                {t('cover_color')}
              </Typography>
              <FormColorSelect
                name={configurationFields.coverColor()}
                options={colorOptions}
              />
            </Stack>
          </Stack>
          <Stack
            sx={{
              backgroundColor: ({ palette }) =>
                palette.new.background.elements.grey,
              borderRadius: ({ shape }) => shape.borderRadiusS,
              p: 2,
            }}
          >
            <Stack
              sx={{
                flexDirection: 'row',
                gap: 0.5,
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <HuFormSwitcher
                name={configurationFields.csatEnabled()}
                switcherProps={{
                  Icon: (
                    <HuTooltip
                      description={t('csat_survey_tooltip')}
                      direction="bottom"
                    >
                      <IconInfoCircle
                        size={13}
                        color={theme.palette.new.text.neutral.default}
                      />
                    </HuTooltip>
                  ),
                  title: t('csat_survey'),
                  titleProps: {
                    variant: 'globalS',
                    fontWeight: 'fontWeightSemiBold',
                    color: theme.palette.new.text.neutral.default,
                  },
                  description: t('csat_survey_description'),
                }}
              />
            </Stack>
          </Stack>
        </Stack>
      )}
    </HuDrawer>
  );
};

export default ConfigurationDrawer;
