import React, { ReactNode, useEffect, useState } from 'react';
import { Box, Checkbox, Text, useViewport } from '@nova-hf/ui';
import { IconType } from '@nova-hf/ui/umd/ts/src/icon-library/iconMap';
import { MainColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import Hradleid from 'store/hradleid';
import { IContext } from 'typings/context';
import { useTranslation } from 'utils/i18n';

import MultiActionsWrapper from '../multiActionsWrapper/MultiActionsWrapper';

type MultiStepWrapperProps = {
  hradleid: Hradleid;
  color: MainColorType;
  title: string;
  children: ReactNode;
  sendCheckedToChild: (subIds: Array<string>) => void;
  getMappedSubs: Array<{ name: string; info: string; id: string; payer: string }>;
  firstRowTitle: string;
  secondRowTitle: string;
  disabledSubIds: string[];
  icon: IconType;
  customerName: string;
  needsBiggerWidth?: boolean;
};

const MultiStepWrapper = ({
  hradleid,
  color,
  title,
  children,
  sendCheckedToChild,
  firstRowTitle,
  secondRowTitle,
  disabledSubIds,
  icon,
  getMappedSubs,
  customerName,
  needsBiggerWidth,
}: MultiStepWrapperProps) => {
  const { t } = useTranslation(['multi']);
  const router = useRouter();
  const ssn = router.query.ssn ?? '';
  const subIds = hradleid?.subscriptionIds ?? [];
  const [checkedSubIds, setCheckedSubIds] = useState<string[]>(subIds);
  const handleDisabledSubIds = disabledSubIds?.length ?? 0;
  const { isLarge, isXLarge } = useViewport();
  const isDesktop = isLarge || isXLarge;
  const mappedSubs = getMappedSubs;

  const handleCheckboxClick = (id: string) => {
    if (checkedSubIds.includes(id)) {
      setCheckedSubIds(checkedSubIds.filter((subId) => id !== subId));
    } else {
      setCheckedSubIds([...checkedSubIds, id]);
    }
  };

  useEffect(() => {
    sendCheckedToChild(checkedSubIds);
  }, [checkedSubIds]);

  return (
    <MultiActionsWrapper
      color={color}
      returnUrl={`/${ssn}/fjoldaskraning`}
      title={title}
      subTitle={customerName ?? t('multi.noName')}
      icon={icon}
      needsBiggerWidth={needsBiggerWidth}
      totalChecks={checkedSubIds?.length - handleDisabledSubIds}
      mainButton={{
        text: t('multi.needHelp'),
        renderAs: 'a',
        colorScheme: color,
        dottedShadow: 'none',
        icon: 'chat',
        href: 'https://www.nova.is/hafa-samband/panta-simtal',
        target: '_blank',
      }}
      childrenSide={
        <Box style={{ width: needsBiggerWidth ? '420px' : '350px' }} marginTop={-2}>
          <Box
            gap={10}
            marginBottom={2}
            display="flex"
            flexDirection="row"
            justifyContent="space-between"
          >
            <Text variant="pMediumBold" color="white">
              {firstRowTitle}
            </Text>
            <Text variant="pMediumBold" color="white">
              {secondRowTitle}
            </Text>
          </Box>
          <Box overflowY={'scroll'} maxHeight={isDesktop ? 50 : 20}>
            {mappedSubs?.map((sub) => {
              return (
                <Box display="flex" flexDirection="column" key={sub?.id}>
                  {sub?.id && (
                    <Box
                      marginBottom={2}
                      justifyContent="space-between"
                      display="flex"
                      flexDirection="row"
                      alignItems="center"
                    >
                      <Box
                        style={{
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                        }}
                        display="flex"
                        justifyContent="flex-start"
                        flexDirection="row"
                      >
                        <Checkbox
                          isChecked={
                            checkedSubIds?.includes(sub?.id) && !disabledSubIds?.includes(sub?.id)
                          }
                          isDisabled={disabledSubIds?.includes(sub?.id)}
                          type="checked"
                          color={color}
                          onChange={() => {
                            handleCheckboxClick(sub?.id);
                          }}
                        />
                        <Text variant="pMediumRegular" color="grey100">
                          {sub?.name}
                        </Text>
                      </Box>
                      <Box
                        style={{
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                        }}
                      >
                        <Text variant="pMediumBold" color="white">
                          {sub?.info}
                        </Text>
                      </Box>
                    </Box>
                  )}
                </Box>
              );
            })}
          </Box>
        </Box>
      }
    >
      {children}
    </MultiActionsWrapper>
  );
};

MultiStepWrapper.getInitialProps = ({ pathname, query }: IContext) => {
  return {
    pathname,
    ssn: query.ssn,
    namespacesRequired: ['multi'],
  };
};

export default inject('hradleid')(observer(MultiStepWrapper));
