import { useState } from "react";
import Button from "../../pageElements/Button";
import { Link, useNavigate } from "react-router-dom";
import Col from "react-bootstrap/Col";
import Form from "react-bootstrap/Form";
import Row from "react-bootstrap/Row";
import { demoFields, supportFields } 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 DemoRequestPage = () => {
  const { supReq } = useParams();
  const navigate = useNavigate();
  const token = window.sessionStorage.getItem("token");
  const [isBusy, setIsBusy] = useState();
  const fieldsChunkSize = 2;
  const isSupport = token && supReq === "5ac45d12";
  const inputFields = isSupport ? supportFields : demoFields;
  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 saveUserData(dataValues) {
    const requestDate = new Date();
    dataValues["requestDate"] = requestDate;
    const requestId = uuidv4();
    try {
      const demoRef = collection(db, "demorequests");
      await setDoc(doc(demoRef, requestId), dataValues);
    } catch (error) {
      console.log(`Error saving request data to db: ${error}`);
    }
  }

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

  async function handleRequestDemo() {
    const dataValues = validateData();
    if (dataValues === null) {
      return;
    }
    if (isSupport) {
      saveSupportRequestData(dataValues);
      navigate("/");
    } else {
      saveUserData(dataValues);
      navigate("/");
    }
  }

  return (
    <div className="signup-super-container">
      <div className="signup-sub-container">
        <div className="signup-header">
          {isSupport ? (
            <h2 className="signup-header-text">
              Request Technical Or Account Support
            </h2>
          ) : (
            <>
              <h2 className="signup-header-text">
                Revolutionize Your Practice: Request A Demo
              </h2>
              <p className="requestdemo-para">
                Enter your information below we will contact you to schedule
              </p>
            </>
          )}
        </div>
        <Form className="demo-request-form">
          {splitEvery(Object.keys(inputFields), fieldsChunkSize).map(
            (names, j) => (
              <Row key={`row${j}`}>
                {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="signup-button-box">
          <Button
            className="primary-button"
            type="button"
            size="lg"
            onClick={handleRequestDemo}
            disabled={isBusy}
            labelText={isSupport ? "Request Support" : "Request Demo"}
          />
          <div className="mt-3">
            {isSupport ? (
              <></>
            ) : (
              <span>
                <Link to="/signup">Go to signup</Link>
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default DemoRequestPage;
