import React, { useEffect, useState } from 'react';
import { Box, Checkbox, Datepicker, Input, MainButton, Text } from '@nova-hf/ui';
import { IContext } from 'beta/typings/context';
import Wrapper from 'components/app-layout/Wrapper';
import { inject } from 'mobx-react';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';

import Authentication from '../../../store/authentication';
import UI from '../../../store/ui';
import {
  useCustomerNameByNationalIdQuery,
  useCustomerRestrictionSettingsQuery,
  useUpdateCustomerRestrictionSettingsMutation,
} from '../../../typings/graphql';
import { formatDate } from '../../../utils/helpers';
import { useTranslation } from '../../../utils/i18n';
import SEO from '../../../utils/SEO';
import Settings from '../containers/settings/Settings';

interface LokanirProps {
  ui?: UI;
  authentication?: Authentication;
}

const Lokanir = ({ ui, authentication }: LokanirProps) => {
  if (!authentication) return null;
  const router = useRouter();
  const { t } = useTranslation('stillingar');
  const { enqueueSnackbar } = useSnackbar();
  const { data: customerData } = useCustomerNameByNationalIdQuery({
    variables: { input: { nationalId: router?.query?.ssn?.toString() } },
    skip: !router?.query?.ssn,
  });
  const customerId = customerData?.customerByNationalId?.id;
  const {
    data: restrictionSettingData,
    refetch: restrictionSettingRefetch,
    loading: restrictionSettingLoading,
  } = useCustomerRestrictionSettingsQuery({
    variables: { input: { id: customerId ?? '' } },
    skip: !customerId,
  });
  const isChecked = restrictionSettingData?.customerRestrictionSettings?.doNotClose;
  const [on, setOn] = useState(isChecked === true ? isChecked : false);
  const [excludePhoneNumbers, setExcludePhoneNumbers] = useState(false);
  const validUntil = restrictionSettingData?.customerRestrictionSettings?.doNotCloseValidUntil;
  const [chosenDate, setChosenDate] = useState(new Date());
  const [isChosingDate, setIsChosingDate] = useState(false);
  const [numbers, setNumbers] = useState('');

  const [check] = useUpdateCustomerRestrictionSettingsMutation({
    onCompleted() {
      restrictionSettingRefetch();
    },
  });

  const onCheck = (differentToCurrentOn: boolean) => {
    if (differentToCurrentOn) {
      setIsChosingDate(true);
    }
    setOn(differentToCurrentOn);
  };

  const onExcludeCheck = (newValue: boolean) => {
    if (!newValue) {
      setNumbers('');
    }
    setExcludePhoneNumbers(newValue);
  };

  const onSubmit = async () => {
    const allowedNumbers = numbers?.length ? numbers.split(',') : null;
    try {
      await check({
        variables: {
          input: {
            id: customerId ?? '',
            doNotClose: on === true ? on : false,
            doNotCloseValidUntil: chosenDate ?? new Date(),
            excludeSmsReminders: excludePhoneNumbers,
            allowedPhoneNumbers: allowedNumbers?.length ? allowedNumbers : null,
          },
        },
      });
      enqueueSnackbar(t('general.message.success'), {
        variant: 'success',
      });
    } catch (e: any) {
      enqueueSnackbar(t('general.message.error', { error: e.message }), {
        variant: 'error',
      });
    }
  };

  useEffect(() => {
    setOn(isChecked);
  }, [isChecked]);

  return (
    <Wrapper header="dark">
      <SEO title={'Lokanir'} />
      <Settings link={router.asPath} color={ui?.pageColor}>
        <Box marginTop={5}>
          <Text color="black100">{t('openCloseSettings.validUntilDescription')}</Text>
          <Checkbox
            isChecked={on}
            label={t('openCloseSettings.cantClose')}
            type="checked"
            color={ui?.pageColor ?? 'pink'}
            onChange={() => {
              onCheck(!on);
            }}
          />
          {validUntil && isChecked && (
            <Box>
              <Text variant="pXSmallBold">{t('openCloseSettings.validUntil')}</Text>
              <Text variant="pXSmallRegular">{formatDate(validUntil, 'dd.MM.yyyy')}</Text>
            </Box>
          )}
          {isChosingDate && on && (
            <Box display="flex" flexDirection="column" gap={3}>
              <Datepicker
                onSelect={(value: Date) => setChosenDate(value)}
                selected={chosenDate}
                minDate={new Date()}
                color={ui?.pageColor ?? 'pink'}
              />
            </Box>
          )}
          <Box marginTop={1}>
            <Checkbox
              isChecked={excludePhoneNumbers}
              label={'Ekki senda tilkynningar fyrir lokun vegna vanskila'}
              type="checked"
              color={ui?.pageColor ?? 'pink'}
              onChange={() => {
                onExcludeCheck(!excludePhoneNumbers);
              }}
            />
            {excludePhoneNumbers && (
              <Box>
                <Text color="black100">
                  Hvaða númer eiga að fá tilkynningar? vinsamlegast sláið inn númer með kommu á
                  milli og engu bili.
                </Text>
                <Input
                  id="numbers"
                  name="numbers"
                  label={'Númer'}
                  icon="mobile"
                  color="grey900"
                  value={numbers}
                  isBold={false}
                  onChange={(e) => setNumbers(e.target.value)}
                />
              </Box>
            )}
          </Box>
          <Box marginTop={3} width="4/12">
            <MainButton
              colorScheme={ui?.pageColor ?? 'pink'}
              text={'Staðfesta'}
              isDisabled={restrictionSettingLoading}
              onClick={() => onSubmit()}
            />
          </Box>
        </Box>
      </Settings>
    </Wrapper>
  );
};

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

export default inject('authentication', 'ui')(Lokanir);
