Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
7.9 kB
3
Indexable
Never
import styles from './signupform.module.scss';
import formData from '../../../../data/forms/signup.json';
import Container from '../../common/Container/Container';
import Button from '../../atoms/Button/Button';
import localFont from 'next/font/local';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';

import React from 'react';
import Input from '../../atoms/Input/Input';
const sansLight = localFont({
  src: '../../../../public/fonts/Soure_Sans_Pro/SourceSansPro-Light.ttf',
});
const sansRegular = localFont({
  src: '../../../../public/fonts/Soure_Sans_Pro/SourceSansPro-Regular.ttf',
});
const sansPro = localFont({
  src: '../../../../public/fonts/Soure_Sans_Pro/SourceSansPro-ExtraLight.ttf',
});

const SignupForm = () => {
  const router = useRouter();
  const signupFormData = formData;

  const [manaualAddress, setManualAddress] = useState(false);
  const [findAddress, setFindAddress] = useState(false);
  const [sortedAddressList, setSortedAddressList] = useState({});
  const [fetchedAddresses, setFetchedAddresses] = useState({});
  const [enteredPostcode, setEnteredPostcode] = useState('');

  const generateInitialState = (formType) => {
    const formData =
      formType === 1 ? signupFormData?.primary : signupFormData?.secondary;

    return formData.map((field) => {
      const { label, name, type, required, hasIcon, layoutSplit } = field;
      return {
        label,
        name,
        type,
        value: '',
        required,
        hasIcon: formType === 1 ? hasIcon : null,
        layoutSplit: formType === 1 ? layoutSplit : null,
      };
    });
  };

  const [primaryInputFields, setPrimaryFields] = useState(
    generateInitialState(1)
  );
  const [secondaryFields, setSecondaryFields] = useState(
    generateInitialState(2)
  );

  //TODO: router.push('/signup-success');

  // handle form input changes
  const handleInputChange = (event, index) => {
    const { name, value } = event.target;
    setPrimaryFields((prevState) => {
      const updatedInputs = [...prevState];
      updatedInputs[index] = { ...updatedInputs[index], value: value };
      return updatedInputs;
    });
  };

  // Handle address box list items
  const handleAddressItem = (e) => {
    const clickedFieldValue = e.currentTarget.innerHTML.split(', ');
    setSecondaryFields({
      ...secondaryFields,
      address1: clickedFieldValue[0],
      town: clickedFieldValue[1],
      country: clickedFieldValue[2],
    });
    setManualAddress(true);
    setFindAddress(false);
  };

  const handleSubmit = () => {};
  const handleFindAddress = () => {
    setFindAddress(!findAddress);
    fetchPostcode(enteredPostcode);
  };

  const handlePostcodeInput = (e) => {
    e.preventDefault();
    setEnteredPostcode(e.currentTarget.value);
  };

  const updateInput = (e) => {
    const { name, value } = e.currentTarget;
    setSecondaryFields({
      ...secondaryFields,
      [name]: value,
    });
  };

  const fetchPostcode = () => {
    // Fetch postcode with postcode as parameter
    fetch(
      `https://api.getAddress.io/find/${enteredPostcode}?api-key=${process.env.NEXT_PUBLIC_API_KEY}`
    )
      .then((res) => res.json())
      .then((data) => {
        if (data.addresses.length >= 1) {
          setFetchedAddresses(formatAddresses(data));
        } else {
          console.log('No addresses found');
        }
      });
  };

  const formatAddresses = (address) => {
    try {
      let formattedAddress = Object.values(address.addresses).map((address) => {
        let x = address.split(', ').filter(Boolean).join(', ');
        x += `, ${enteredPostcode.toUpperCase()}`;
        return x;
      });
      setSortedAddressList(formattedAddress);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <Container type="content_sm" className={styles.component}>
      <div className={styles.form_intro}>
        <h3 className={sansRegular.className}>Create your Account</h3>
        <p className={sansLight.className}>
          In 30 seconds you&#39;ll be a sign up pro!
        </p>
      </div>
      <form method="post" className={styles.form}>
        {/* Main form (primary) */}
        {primaryInputFields.length >= 1 &&
          primaryInputFields.map((field, idx) =>
            !field.layoutSplit ? (
              <div key={idx} className={styles.form_field}>
                {field.label && (
                  <label htmlFor={field.name} className={sansLight.className}>
                    {field.label}
                  </label>
                )}

                <Input
                  type={field.type}
                  icon={field.hasIcon}
                  className={sansRegular.className}
                  name={field.name}
                  onChange={(event) => handleInputChange(event, idx, 1)}
                  value={field.value}
                />
              </div>
            ) : (
              <>
                {/* Manual address sub-form (secondary) */}
                {manaualAddress && (
                  <div className={styles.form_manualAddress}>
                    {formData.secondary &&
                      formData.secondary.map((field, idx) => {
                        return (
                          <div key={idx} className={styles.form_field}>
                            {field.label && (
                              <label
                                htmlFor={field.name}
                                className={sansLight.className}
                              >
                                {field.label}
                              </label>
                            )}

                            <Input
                              name={field.name}
                              type={field.type}
                              className={sansRegular.className}
                              onChange={updateInput}
                              value={secondaryFields[field.name]}
                            />
                          </div>
                        );
                      })}
                  </div>
                )}
                <div key={idx} className={styles.form_field_variant}>
                  <div>
                    {field.label && (
                      <label
                        htmlFor={field.name}
                        className={sansLight.className}
                      >
                        {field.label}
                      </label>
                    )}
                    <Input
                      type={field.type}
                      className={sansRegular.className}
                      onChange={(e) => handlePostcodeInput(e)}
                    />
                  </div>

                  <Button
                    text="Find Address"
                    onClick={handleFindAddress}
                    type="button"
                    disabled={manaualAddress}
                  />
                </div>
              </>
            )
          )}
        <button
          className={`${styles.enterAddressManually} ${sansRegular.className}`}
          onClick={() => setManualAddress(!manaualAddress)}
          type="button"
        >
          Enter address manually
        </button>

        {findAddress && (
          <div className={styles.addressBox}>
            {sortedAddressList.length >= 1 && (
              <ul>
                {sortedAddressList.map((item, idx) => (
                  <li
                    key={idx}
                    className={sansRegular.className}
                    onClick={(e) => handleAddressItem(e)}
                  >
                    {item}
                  </li>
                ))}
              </ul>
            )}
          </div>
        )}

        <Button text="Sign Up" onClick={handleSubmit} type="button" />
      </form>
    </Container>
  );
};

export default SignupForm;