import Input from "@/components/atoms/Input";
import React from "react";
import styles from "./Form.module.scss";
import form from "../../../data/global/form";
import { useState, useEffect } from "react";
import Container from "@/components/atoms/Container";
import Button from "@/components/atoms/Button";
import AddressList from "../AddressList";
import Fader from "@/components/atoms/Fader";
const Form = () => {
const [postcode, setPostcode] = useState(null);
const [postcodeReturned, setPostcodeReturned] = useState([]);
const [addressList, setAddressList] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [isManual, setIsManual] = useState(false);
const [finalData, setFinalData] = useState({});
const [formLast, setFormLast] = useState({});
const postcodeRef = React.createRef();
const formRef = React.createRef();
useEffect(() => {
// console.log("Final data:", finalData);
let data = JSON.parse(localStorage.getItem("Form"));
console.log("Local storage", data);
}, [finalData]);
const handleFindAddress = (e) => {
e.preventDefault();
setIsManual(false);
postcode != null && fetchPostcodeData(postcode);
setAddressList(!addressList);
};
const handleManualAddress = () => {
setIsManual(!isManual);
};
const handleFormSubmit = (e) => {
e.preventDefault();
let form = {
email: e.target[0].value,
password: e.target[1].value,
confirmPass: e.target[2].value,
firstName: e.target[3].value,
lastName: e.target[4].value,
firstLine: e.target[5].value,
secondLine: e.target[6].value,
thirdLine: e.target[7].value,
town: e.target[8].value,
country: e.target[9].value,
postcode: postcode,
};
if (e.target[1].value !== e.target[2].value) {
setErrorMessage("Passwords do not match, try again");
e.target[1].style.border = "1px red solid";
e.target[2].style.border = "1px red solid";
} else {
setFinalData(form);
localStorage.setItem("Form", JSON.stringify(form));
setFormToStorage(e);
}
};
const setFormToStorage = (form) => {
let data = JSON.parse(localStorage.getItem("Form"));
form.target[0].value = data.email;
form.target[1].value = data.password;
};
const handleChange = (e) => {
setPostcode(e.target.value);
};
const formatData = (data) => {
let formattedData = data?.map((val) =>
val
.split(",")
.filter((x) => x.trim().length !== 0)
.join(",")
);
return formattedData;
};
const fetchPostcodeData = (postcode) => {
fetch(`https://api.getAddress.io/find/${postcode}?api-key=${process.env.NEXT_PUBLIC_API_URL}`)
.then((res) => res.json())
.then((result) => setPostcodeReturned(formatData(result.addresses)))
.catch((error) => (setErrorMessage("Error connecting to network"), console.log(error)));
};
return (
<form onSubmit={(e) => handleFormSubmit(e)} ref={formRef}>
<section className={styles.form}>
{form.primary?.map((item) => (
<Input label={item.label} type={item.type} icon={item.hasIcon} />
))}
{isManual ? (
<Container className={styles.manualAddress}>
<Input label={"Adress line 1"} type={"text"} value={formLast?.firstLine} />
<Input label={"Adress line 2 (optional)"} type={"text"} />
<Input label={"Adress line 3 (optional)"} type={"text"} />
<Input label={"Town or City"} type={"text"} value={formLast?.town} />
<Input label={"Country"} type={"text"} value={formLast?.county} />
</Container>
) : (
<Container className={styles.postcode}>
<Container className={styles.postcode_input}>
<Input
label={"Postcode"}
onChange={(e) => handleChange(e)}
onClick={() => setAddressList(false)}
ref={postcodeRef}
id={"postcodeInput"}
/>
</Container>
<Container className={styles.postcode_button}>
<Button label={"Find Address"} disabled={false} onClick={(e) => handleFindAddress(e)} />
</Container>
</Container>
)}
{!addressList && (
<span onClick={handleManualAddress} className={styles.manualAddressText}>
Enter address manually
</span>
)}
{errorMessage && <Fader text={"Passwords do not match, try again..."} className={styles.error} />}
{addressList && (
<AddressList
addresses={postcodeReturned}
postcode={postcode}
isPopulated={addressList}
addressList={addressList}
setIsManual={setIsManual}
setAddressList={setAddressList}
setFormLast={setFormLast}
/>
)}
<Container className={styles.signup}>
<Button label={"Sign Up"} disabled={false} className={styles.postcode_signup} type={"submit"} />
</Container>
</section>
</form>
);
};
export default Form;