import React, { Fragment, useEffect, useMemo, useState } from 'react';
import { Col, Row } from 'reactstrap';
import { Link } from 'react-router-dom';
import JKRegistrationForm from '../JKRegistrationForm';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { getJamTrackBySlug } from '../../../helpers/rest';

const Registration = () => {
  const { t } = useTranslation('auth');
  const search = useLocation().search;
  const [jamTrack, setJamTrack] = useState(null);
  const [jamTrackArtistName, setJamTrackArtistName] = useState("");
  const [loading, setLoading] = useState(false);

  //coming to signup page after clicking on jamtrack or artist
  useEffect(() => {

    if (!search) return;

    const params = new URLSearchParams(search);

    const jamtrackSlug = params.get('jamtrack');
    const artistName = params.get('artist');

    setLoading(true);

    if (artistName && artistName !== "") {
      setJamTrackArtistName(artistName);
      setLoading(false);
    } else if (jamtrackSlug && jamtrackSlug !== "") {
      const fetchJamTrack = async (slug) => {
        try {
          const response = await getJamTrackBySlug({ slug });
          const jamTrack = await response.json();
          setJamTrack(jamTrack);
          setLoading(false);
        } catch (error) {
          console.error(error);
          setLoading(false);
        }
      }
      fetchJamTrack(jamtrackSlug);
    }else{
      setLoading(false);
    }
  }, [search]);

  const pageTitle = useMemo(() => {
    if (jamTrack || jamTrackArtistName) {
      return t('signupForm.jamtrack_signup_title');
    }
    return t('signupForm.signup_title');
  }, [jamTrack, jamTrackArtistName]);

  return (
    loading ? (
      <div className="text-center">
        <div className="spinner-border" role="status">
          <span className="sr-only">Loading...</span>
        </div>
      </div>
    ) : <Fragment>
      <Row className="text-left mb-3">
        <Col>
          <h5 id="modalLabel">{pageTitle}</h5>
        </Col>
      </Row>
      <JKRegistrationForm jamTrack={jamTrack} jamTrackArtistName={jamTrackArtistName} />
      <Row className='justify-content-center mb-2'>
        <Col xs="auto">
          <p className="fs--1 text-600">
            JamKazam <Link to="/public/terms">{t('terms_of_service', { ns: 'common' })}</Link> {t('and', { ns: 'common' })} <Link to="/public/privacy">{t('privacy_policy', { ns: 'common' })}</Link> {t('apply', { ns: 'common' })}.
          </p>
        </Col>
      </Row>
      <Row className='justify-content-center'>
        <Col xs="auto">
          <p className="fs--1 text-600">
            {t('signupForm.alreadyHaveAccount')} <Link to="/authentication/basic/login">{t('signin')}</Link>
          </p>
        </Col>
      </Row>
    </Fragment>
  );
};

export default Registration;
