import { useMutation } from '@apollo/client';
import { TEMP_CONNECT_AD_ACCOUNT } from '../schema/mutations';
import { call } from 'utils/call';

import { useSimpleForm } from 'hooks/useSimpleForm';

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

export const AddAdAccountModal = ({
  onDismiss,
}: {
  onDismiss?: () => void;
}) => {
  const [state, handleChange] = useSimpleForm({
    id: '',
    name: '',
    description: '',
  });

  const [submit, { loading, error }] = useMutation(TEMP_CONNECT_AD_ACCOUNT);

  const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (ev) => {
    ev.preventDefault();
    try {
      await submit({
        variables: {
          id: state.id,
          name: state.name,
          description: state.description,
        },
      });
      call(onDismiss);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <ModalContainer title="Add Ad Account by ID">
      <form onSubmit={handleSubmit}>
        <Box spacingY={2}>
          <Input
            name="id"
            value={state.id}
            onChange={handleChange}
            placeholder="Ad Account ID"
            disabled={loading}
            autoFocus
          />
          <Input
            name="name"
            value={state.name}
            onChange={handleChange}
            placeholder="Name"
            disabled={loading}
          />
          <Input
            name="description"
            value={state.description}
            onChange={handleChange}
            placeholder="Description"
            disabled={loading}
          />
        </Box>
        <Box display="flex" marginY={4} spacing={2}>
          <Button onClick={onDismiss} color="gray" block>
            Cancel
          </Button>
          <Button
            type="submit"
            // onClick={handleSubmit}
            block
            disabled={!state.id || loading}
          >
            {loading ? 'Connecting...' : error ? 'Try again' : 'Connect'}
          </Button>
        </Box>
      </form>
      {error && <Text align="center">Something went wrong</Text>}
    </ModalContainer>
  );
};
