import { useState } from "react";
import Button from "../pageElements/Button";
import { useNavigate } from "react-router-dom";
import Col from "react-bootstrap/Col";
import Form from "react-bootstrap/Form";
import Row from "react-bootstrap/Row";
import { removalFields } from "../Constants/Fields/DemoFields";
import { useParams } from "react-router-dom";
import { splitEvery } from "../Utils/Array";
import TextInput from "../pageElements/TextInput";
import { objectMap } from "../Utils/Object";
import { v4 as uuidv4 } from "uuid";
import {
  getFormDataDefaults,
  getValidatedFormData,
  handleFormDataChange,
  isFormDataHasErrors,
} from "../Utils/Form";
import { db } from "../firebase";
import { collection, setDoc, doc } from "firebase/firestore";
import "../styles/demo-request-page.scss";

const OptoutPage = () => {
  const navigate = useNavigate();
  const token = window.sessionStorage.getItem("token");
  const [isBusy, setIsBusy] = useState();
  const fieldsChunkSize = 2;
  const inputFields = removalFields;
  const [data, setData] = useState(getFormDataDefaults(inputFields));
  const handleChangeInput = (e, name) => {
    const newData = handleFormDataChange(e, name, data, inputFields);
    if (newData !== null) {
      setData(newData);
    }
  };

  const validateData = () => {
    const newData = getValidatedFormData(data, inputFields);
    const hasErrors = isFormDataHasErrors(newData);
    setData(newData);
    return hasErrors ? null : objectMap(({ value }) => value, newData);
  };

  async function saveRequestData(dataValues) {
    const requestDate = new Date();
    dataValues["requestDate"] = requestDate;
    const requestId = uuidv4();
    try {
      const reqRemoveRef = collection(db, "removalrequests");
      await setDoc(doc(reqRemoveRef, requestId), dataValues);
    } catch (error) {
      console.log(`Error saving request data to db: ${error}`);
    }
  }

  async function handleRequestOptOut() {
    const dataValues = validateData();
    if (dataValues === null) {
      return;
    }
    console.log("datavalues", dataValues);
    saveRequestData(dataValues);
    navigate("/");
  }

  return (
    <div className="signup-super-container">
      <div className="signup-sub-container">
        <div className="signup-header">
          <h2 className="signup-header-text">Opt Out of Future Emails</h2>
          <p className="requestdemo-para">
            Enter your email address to be removed from our mailing list
          </p>
        </div>
        <Form className="demo-request-form">
          {splitEvery(Object.keys(inputFields), fieldsChunkSize).map(
            (names, j) => (
              <Row key={`row${j}`} className="demo-page-row">
                {names.map((name, i) => (
                  <Col
                    key={`${name}${i + fieldsChunkSize * j}`}
                    className="mb-3"
                  >
                    <TextInput
                      name={name}
                      value={data[name].value}
                      onChange={(e) => handleChangeInput(e, name)}
                      error={data[name].error}
                      message={data[name].message}
                      label={
                        data[name].value.length === 0
                          ? inputFields[name].label
                          : ""
                      }
                      type={inputFields[name].type}
                      values={inputFields[name].values}
                      disabled={isBusy}
                    />
                  </Col>
                ))}
              </Row>
            )
          )}
        </Form>
        <div className="demo-button-box">
          <Button
            className="primary-button demo"
            type="button"
            size="lg"
            onClick={handleRequestOptOut}
            disabled={isBusy}
            labelText={"Request Removal"}
          />
        </div>
      </div>
    </div>
  );
};

export default OptoutPage;
