import { useState } from 'react';
import { useMutation } from '@apollo/client';
import { KLAVIYO_UPDATE, KLAVIYO_STATUS } from '../schema';
import {
  KlaviyoUpdateMutation,
  KlaviyoUpdateMutationVariables,
} from 'types/graphql';
import { call } from 'utils/call';

import { ModalContainer } from 'components/modals';
import { Box, Button, Spinner, Text } from 'components/common';
import { Input } from 'components/inputs';
import { ExternalLink } from 'components/router/ExternalLink';

const KLAVIYO_HELP_URL =
  'https://help.klaviyo.com/hc/en-us/articles/115005062267-How-to-Manage-Your-Account-s-API-Keys';

interface ConnectKlaviyoModalProps {
  publicKey?: string;
  privateKey?: string;
  onDismiss?: () => void;
}

export const ConnectKlaviyoModal = ({
  publicKey,
  privateKey,
  onDismiss,
}: ConnectKlaviyoModalProps) => {
  const [state, setState] = useState({ publicKey, privateKey });
  const [update, { loading, error }] = useMutation<
    KlaviyoUpdateMutation,
    KlaviyoUpdateMutationVariables
  >(KLAVIYO_UPDATE, {
    refetchQueries: [{ query: KLAVIYO_STATUS }],
    awaitRefetchQueries: true,
  });

  const handleChange: React.ChangeEventHandler<HTMLInputElement> = (ev) => {
    const { name, value } = ev.target;
    setState((s) => ({ ...s, [name]: value }));
  };

  const handleSubmit = async () => {
    const { privateKey, publicKey } = state;
    try {
      await update({
        variables: {
          status: 'connected',
          privateKey,
          publicKey,
        },
      });
      call(onDismiss);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <ModalContainer title="Connect Klaviyo">
      <form onSubmit={handleSubmit}>
        <Box spacingY={2}>
          <Input
            placeholder="Private key"
            name="privateKey"
            value={state.privateKey}
            onChange={handleChange}
            autoFocus
          />
          {/* <Input
            placeholder="Public key"
            name="publicKey"
            value={state.publicKey}
            onChange={handleChange}
          /> */}
          <Text size="s">
            Find out{' '}
            <ExternalLink className="link" href={KLAVIYO_HELP_URL}>
              how to access and manage
            </ExternalLink>{' '}
            your API keys for your Klaviyo account
          </Text>
        </Box>
        <Box display="flex" marginY={4} spacing={2}>
          {onDismiss && (
            <Button type="button" onClick={onDismiss} color="gray" block>
              Cancel
            </Button>
          )}
          <Button
            type="submit"
            onClick={handleSubmit}
            color="blue"
            block
            disabled={(!state.publicKey && !state.privateKey) || loading}
          >
            {error ? 'Try again' : 'Connect'}
          </Button>
        </Box>
      </form>
      {error && (
        <Text className="c-red" size="s" align="center">
          {error.message}
        </Text>
      )}
      <Spinner show={loading} />
    </ModalContainer>
  );
};
