import React, { useEffect, useState } from 'react';
import { Card, CardBody, CardText, CardTitle } from 'reactstrap';
import { useTranslation } from 'react-i18next';
import { useBrowserQuery } from '../../context/BrowserQuery';
import { useHistory, useParams } from "react-router-dom";


const unsubscribeFromNewUsersWeeklyEmail = (token) => {

 

  const baseUrl = process.env.REACT_APP_CLIENT_BASE_URL

  return new Promise((resolve, reject) => {
    fetch(`${baseUrl}/unsubscribe_user_match/${token}`,
      { method: 'POST' }
    ).then(response => {
      if (response.ok) {
        resolve(response);
      } else {
        reject(response)
      }
    })
  })
}

const unsubscribe = (token) => {
  const baseUrl = process.env.REACT_APP_CLIENT_BASE_URL
  return new Promise((resolve, reject) => {
    fetch(`${baseUrl}/unsubscribe/${token}`, { method: 'POST', headers: { 'Content-Type': 'application/json', accept: 'application/json' } })
      .then(response => {
        if (response.ok) {
          resolve(response)
        } else {
          reject(response)
        }
      }).catch(error => {
        reject(error);
      });
  })
}

function JKUnsubscribe() {
  const { t } = useTranslation("unsubscribe");
  const history = useHistory()
  const [loading, setLoading] = useState(true)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState(null)
  const { tok } = useParams();

  useEffect(() => {
    if (tok) {
      unsubscribe(tok)
        .then((resp) => {
          if (resp.ok) {
            setSuccess(true)
          } else {
            setSuccess(false)
          }
        })
        .catch(error => {
          setError(error)
        }).finally(() => {
          setLoading(false)
        });
    } else {
      history.push('/')
    }
  }, [])

  return (

    <Card style={{ width: '25rem', margin: '2rem auto' }}>
      <CardBody>
        <CardTitle className="mb-2">{t('page_title')}</CardTitle>
        <>
          {loading && <div className="text-muted"><span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>{t('loading')}</div>}
          {success && <div className="text-success">{t('success')}</div>}
          {error && <div className="text-danger">{t('error')}</div>}
        </>

      </CardBody>
    </Card>

  )
}

export default JKUnsubscribe
