import React, { useState } from 'react';
import { Box, Checkbox, Text } from '@nova-hf/ui';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { IContext } from 'typings/context';

import Cart from '../../../store/cart';
import MobileSignup from '../../../store/mobileSignup';
import {
  PaymentType,
  useAddPaymentToOrderMutation,
  useCreateOrderMutation,
  useMobileCartQuery,
} from '../../../typings/graphql';
import LayoutWrapper from '../components/LayoutWrapper';
import CardForm from '../greidsla/components/cardForm';

type GreidslaOskradProps = {
  mobileSignup: MobileSignup;
  cart: Cart;
};

type PaymentMethodForm = {
  expiry: string;
  cvc: string;
  cardNumber: string;
};

const GreidslaOskrad = ({ cart }: GreidslaOskradProps) => {
  const router = useRouter();
  const [hasAcceptedTerms, setHasAcceptedTerms] = useState(false);
  const { data: cartData } = useMobileCartQuery({
    variables: { input: { cartId: cart.activeCartId } },
    fetchPolicy: 'network-only',
  });
  const [createOrder, { error: orderError }] = useCreateOrderMutation();
  const [addPayment, { error: paymentError }] = useAddPaymentToOrderMutation();
  const [otherErrorWorthDisplaying, setOtherErrorWorthDisplaying] = useState('');
  const requiresRecurringPaymentInfo =
    cartData?.cart?.paymentRequirements?.requiresRecurringPaymentInfo;
  const requiresPaymentInfo = cartData?.cart?.paymentRequirements?.requiresPaymentInfo;

  const onPay = async (form: PaymentMethodForm) => {
    if (cart.activeCartId) {
      const res = await createOrder({
        variables: {
          input: {
            cartId: cart.activeCartId,
          },
        },
      });
      const orderId = res.data?.createOrder.order?.id;
      if (!orderId) {
        setOtherErrorWorthDisplaying('Ekki tókst að stofna pöntun.');
      }
      if (orderId) {
        const res = await addPayment({
          variables: {
            input: {
              orderId: orderId,
              ...(requiresPaymentInfo && {
                paymentInfo: {
                  amount: cartData?.cart?.totalDue ?? 0,
                  paymentType: PaymentType.CreditCard,
                  savePayment: false,
                  cardNumber: form?.cardNumber,
                  cvc: form?.cvc,
                  expiryMonth: form?.expiry.substring(0, 2),
                  expiryYear: form?.expiry.substring(2, 4),
                },
              }),
              ...(requiresRecurringPaymentInfo && {
                recurringPaymentInfo: {
                  amount: cartData?.cart?.totalDue ?? 0,
                  paymentType: PaymentType.CreditCard,
                  savePayment: false,
                  cardNumber: form?.cardNumber,
                  cvc: form?.cvc,
                  expiryMonth: form?.expiry.substring(0, 2),
                  expiryYear: form?.expiry.substring(2, 4),
                },
              }),
            },
          },
        });
        if (res?.data?.addPaymentToOrder?.order?.id) {
          cart?.setCustomerId('');
          router?.push(`/farsimi/takk/${res?.data?.addPaymentToOrder?.order?.id}`);
        }
      }
    }
  };

  return (
    <LayoutWrapper image="https://images.ctfassets.net/j5d5y4z9f7ki/6XH2eOVWoZ8UwIPSxJqhA5/616d804bb3233e30ee9e2dcf969ae3a9/UmAlltLand_1416x1250.png">
      <Box
        marginBottom={10}
        minHeight={{ sm: '100vh' }}
        display="flex"
        alignItems="center"
        width="100%"
      >
        <Box width="100%">
          <Box marginBottom={2}>
            <Text variant="subHeading">Veldu greiðsluleið</Text>
          </Box>
          <Box
            display="flex"
            flexDirection="column"
            gap={2}
            marginBottom={10}
            backgroundColor="grey200"
            paddingX={3}
            paddingY={3}
            borderStyle="solid"
            borderColor="pink"
            style={{ borderRadius: '16px' }}
          >
            <CardForm
              enabledCondition={hasAcceptedTerms}
              buttonText={'Greiða og byrja með Nova'}
              isInverted={false}
              onSubmit={onPay}
            />
            <Checkbox
              isChecked={hasAcceptedTerms}
              type="checked"
              color="pink"
              onChange={() => {
                setHasAcceptedTerms(!hasAcceptedTerms);
              }}
            >
              <span>
                Ég samþykki{' '}
                <a
                  href="https://www.nova.is/baksvids/skilmalar"
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{ color: '#000', textDecoration: 'underline', cursor: 'pointer' }}
                >
                  skilmála
                </a>{' '}
                Nova
              </span>
            </Checkbox>
            {paymentError && (
              <Text color="warning" variant="pSmallBold">
                {paymentError?.message}
              </Text>
            )}
            {orderError && (
              <Text color="warning" variant="pSmallBold">
                {orderError?.message}
              </Text>
            )}
            {otherErrorWorthDisplaying && (
              <Text color="warning" variant="pSmallBold">
                {otherErrorWorthDisplaying}
              </Text>
            )}
          </Box>
        </Box>
      </Box>
    </LayoutWrapper>
  );
};

GreidslaOskrad.getInitialProps = ({ pathname }: IContext) => {
  return {
    pathname,
    namespacesRequired: [''],
  };
};

export default inject('mobileSignup', 'cart', 'authentication')(observer(GreidslaOskrad));
