import React from 'react'
import { useLocation } from "react-router-dom";
import { Card, CardBody, CardText, CardTitle } from 'reactstrap';
import { useState, useEffect } from 'react';
import { updateEmail } from '../../helpers/rest';
import { useTranslation } from 'react-i18next';

const JKConfirmEmailChange = () => {
  const { t } = useTranslation("account");
  const location = useLocation();
  const params = new URLSearchParams(location.search);
  const token = params.get('token');

  const [success, setSuccess] = useState(false);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (token) {
      updateEmail(token)
        .then(response => {
          if (response.status === 200) {
            setSuccess(true);
          } else {
            setSuccess(false);
          }
        })
        .catch(() => {
          setSuccess(false);
          setError(t('identity.changed_email_confirmation.error'));
        }).finally(() => {
          setLoading(false);
        });
    }
  }, [token]);

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



export default JKConfirmEmailChange