import * as React from 'react';
import { useQuery } from '@apollo/client';
import {
  Box,
  Button,
  CheckboxDeprecated,
  CheckboxGroupDeprecated,
  ContainerDeprecated,
  Datepicker,
  ErrorMessage,
  PaymentFooter,
  PaymentForm,
  StepTitle,
  Text,
  TextBox,
} from '@nova-hf/ui';
import { SUBSCRIPTION } from 'graphql/queries/subscription';
import { inject } from 'mobx-react';
import { isStringPhoneNumber } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';

interface IGetReasonProps {
  change?: any;
  authentication?: any;
  color: string;
  subscriptionId: string;
  returnLink: any;
  onNext: any;
}

const GetReason = ({ change, authentication, color, subscriptionId, onNext }: IGetReasonProps) => {
  const { t } = useTranslation('cancel');

  const initValue = change.reason !== undefined && change.reason !== '' ? change.reason : '';

  const [showOtherInput, setShowOtherInput] = React.useState(change.reason === 'Other');
  const [showOtherInputError, setShowOtherInputError] = React.useState(false);
  const [showEmptyError, setshowEmptyError] = React.useState(false);
  const [reason, setReason] = React.useState(initValue);
  const [reasonText, setReasonText] = React.useState(change.reasonDescription);
  const today = new Date();
  const [date, setDate] = React.useState(today);

  const { data: dataSubscription } = useQuery(SUBSCRIPTION, {
    variables: { subscriptionId, accountInput: authentication.accountInput },
  });
  const subscriptionTitle = dataSubscription?.me?.profiles?.[0]?.title;
  const isPhoneNumber = isStringPhoneNumber(subscriptionTitle);
  const rateplanTitle = dataSubscription?.me?.profiles?.[0]?.rateplan?.title;
  const usedTitle = isPhoneNumber ? rateplanTitle?.toLowerCase() : subscriptionTitle;

  const reasons = [
    {
      id: 'NewService',
      text: t('steps.reason.reasons.newService'),
      showOption: true,
    },
    {
      id: 'AnotherOffer',
      text: t('steps.reason.reasons.anotherOffer'),
      showOption: true,
    },
    {
      id: 'ToExpensive',
      text: t('steps.reason.reasons.toExpensive'),
      showOption: true,
    },
    {
      id: 'PayAnotherDay',
      text: t('steps.reason.reasons.payAnotherDay', { subscriptionTitle: usedTitle }),
      showOption: true,
    },
    {
      id: 'TechnicalProblems',
      text: t('steps.reason.reasons.technicalProblems'),
      showOption: true,
    },
    {
      id: 'CancelNova',
      text: t('steps.reason.reasons.cancelNova'),
      showOption: true,
    },
    {
      id: 'IsMistake',
      text: t('steps.reason.reasons.isMistake'),
      showOption: authentication.isStaff,
    },
    {
      id: 'Other',
      text: t('steps.reason.reasons.other'),
      showOption: true,
    },
  ];

  const mobileReasons = [
    {
      id: 'ServiceArea',
      text: t('steps.reason.mobileReasons.serviceArea'),
      showOption: true,
    },
    {
      id: 'WontGiveReason',
      text: t('steps.reason.mobileReasons.wontGiveReason'),
      showOption: true,
    },
    {
      id: 'PhoneDontWork',
      text: t('steps.reason.mobileReasons.phoneDontWork'),
      showOption: true,
    },
    {
      id: 'WorkPays',
      text: t('steps.reason.mobileReasons.workPays'),
      showOption: true,
    },
    {
      id: 'EverythingInSamePlace',
      text: t('steps.reason.mobileReasons.everythingInSamePlace'),
      showOption: true,
    },
    {
      id: 'ToExpensive',
      text: t('steps.reason.mobileReasons.toExpensive'),
      showOption: true,
    },
    {
      id: 'LoadingCard',
      text: t('steps.reason.mobileReasons.loadingCard'),
      showOption: true,
    },
    {
      id: 'BadService',
      text: t('steps.reason.mobileReasons.badService'),
      showOption: true,
    },
    {
      id: 'AnotherOffer',
      text: t('steps.reason.mobileReasons.anotherOffer'),
      showOption: true,
    },
    {
      id: 'GoingAbroad',
      text: t('steps.reason.mobileReasons.goingAbroad'),
      showOption: true,
    },
    {
      id: 'CancelNova',
      text: t('steps.reason.mobileReasons.cancelNova'),
      showOption: true,
    },
    {
      id: 'AnotherNovaNumber',
      text: t('steps.reason.mobileReasons.anotherNovaNumber'),
      showOption: true,
    },
    {
      id: 'StoppedUsingNumber',
      text: t('steps.reason.mobileReasons.stoppedUsingNumber'),
      showOption: true,
    },
    {
      id: 'Other',
      text: t('steps.reason.mobileReasons.other'),
      showOption: true,
    },
  ];

  const usedReasons = isPhoneNumber ? mobileReasons : reasons;

  const onSubmit: any = () => {
    if (reason === '') {
      setshowEmptyError(true);
      return;
    }

    if (reason === 'Other') {
      if (reasonText === '') {
        setShowOtherInputError(true);
        return;
      }
      change.reasonDescription = reasonText;
    } else {
      change.reasonDescription = reasons.find((item) => item.id === reason)?.text;
    }
    change.reason = reason;
    change.terminationDate = date;

    onNext();
  };

  const onChangeReason: any = (e: any) => {
    const reasonTextValue = e.target.value;
    setReasonText(reasonTextValue);
    if (reasonTextValue !== '') {
      setShowOtherInputError(false);
    }
  };

  const onSelect: any = (e: any) => {
    const reasonValue = e.target.value;

    setReason(reasonValue);
    setshowEmptyError(false);

    if (reasonValue === 'Other') {
      setShowOtherInput(true);
      setReasonText('');
    } else {
      setShowOtherInput(false);
      setShowOtherInputError(false);
    }
  };

  return (
    <ContainerDeprecated>
      <StepTitle
        title={
          isPhoneNumber
            ? t('steps.reason.phoneNumberHeading', { subscriptionTitle: usedTitle })
            : t('steps.reason.heading', { subscriptionTitle: usedTitle })
        }
        subtitle={
          isPhoneNumber
            ? t('steps.reason.phoneNumberDescription', { subscriptionTitle: usedTitle })
            : t('steps.reason.description', { subscriptionTitle: usedTitle })
        }
        color={color}
      />
      <PaymentForm onecolumn>
        <CheckboxGroupDeprecated radio name="reason" color={color} listDirection="column" spacing>
          {usedReasons
            .filter((item) => item.showOption)
            .map((item) => (
              <CheckboxDeprecated
                key={item.id}
                name="cancelReason"
                value={item.id}
                type="radio"
                defaultChecked={item.id === initValue}
                onChange={(e: any) => onSelect(e)}
              >
                {item.text}
              </CheckboxDeprecated>
            ))}
        </CheckboxGroupDeprecated>

        {showOtherInput && (
          <TextBox
            name="otherReason"
            label={t('steps.reason.otherReasonInputLabel')}
            isTextarea
            onChange={(e: any) => onChangeReason(e)}
            value={reasonText}
          />
        )}
        {isPhoneNumber && (
          <Box display="flex" flexDirection="column" gap={2}>
            <Text variant="h5">{t('steps.date.title')}</Text>
            <Text variant="pMediumRegular">{t('steps.date.description')}</Text>
            <Datepicker
              onSelect={(value: Date) => setDate(value)}
              selected={date}
              minDate={today}
              color="black100"
              inputId={'date'}
              inputName={t('steps.date.title')}
            />
          </Box>
        )}
        {showOtherInputError && <ErrorMessage>{t('steps.reason.errorMessage')}</ErrorMessage>}
        {showEmptyError && <ErrorMessage>{t('steps.reason.errorMessageEmpty')}</ErrorMessage>}

        <PaymentFooter>
          <Button fill big background={color} onClick={onSubmit} loading={false} arrowRight>
            {t('steps.reason.button')}
          </Button>
        </PaymentFooter>
      </PaymentForm>
    </ContainerDeprecated>
  );
};

export default inject('change', 'authentication')(GetReason);
