//import {useMutation, useQuery } from "@apollo/client";
import { Button, Form, Layout, Result, Typography } from "antd";
import axios from "axios";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useParams } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import AlertComponent from "../../components/alert/alert.component";
import ConfigFormComponents from "../../components/config-form-components/config-form-components.component";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import { selectCurrentUser } from "../../redux/user/user.selectors";
import { DateTimeFormat } from "./../../utils/DateFormatter";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser
});

const mapDispatchToProps = () => ({});

export default connect(mapStateToProps, mapDispatchToProps)(CsiContainerPage);

export function CsiContainerPage({ currentUser }) {
  const { surveyId } = useParams();
  const [form] = Form.useForm();
  const [axiosResponse, setAxiosResponse] = useState(null);
  const [submitting, setSubmitting] = useState({
    loading: false,
    submitted: false
  });
  const { t } = useTranslation();

  const getAxiosData = useCallback(async () => {
    try {
      try {
        window.$crisp?.push(["do", "chat:hide"]);
      } catch {
        console.log("Unable to attach to crisp instance. ");
      }
      setSubmitting((prevSubmitting) => ({ ...prevSubmitting, loading: true }));
      const response = await axios.post("/csi/lookup", {
        surveyId
      });
      setSubmitting((prevSubmitting) => ({
        ...prevSubmitting,
        loading: false
      }));
      setAxiosResponse(response.data);
    } catch (error) {
      console.error(`Something went wrong...: ${error.message}`);
      console.dir({
        stack: error?.stack,
        message: error?.message
      });
    }
  }, [setAxiosResponse, surveyId]);

  useEffect(() => {
    getAxiosData().catch((err) => console.error(`Something went wrong fetching axios data: ${err.message || ""}`));
  }, [getAxiosData]);

  // Return if authorized
  if (currentUser && currentUser.authorized) {
    return (
      <Layout style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
        <Result
          status="error"
          title={t("csi.labels.nologgedinuser", {
            app: InstanceRenderManager({
              imex: "$t(titles.imexonline)",
              rome: "$t(titles.romeonline)"
            })
          })}
          subTitle={t("csi.labels.nologgedinuser_sub", {
            app: InstanceRenderManager({
              imex: "$t(titles.imexonline)",
              rome: "$t(titles.romeonline)"
            })
          })}
        />
      </Layout>
    );
  }

  if (submitting.loading) return <LoadingSpinner />;

  const handleFinish = async (values) => {
    try {
      setSubmitting({ ...submitting, loading: true, submitting: true });
      const result = await axios.post("/csi/submit", { surveyId, values });
      console.log("result", result);
      if (!result.errors && result.data.update_csi.affected_rows > 0) {
        setSubmitting({ ...submitting, loading: false, submitted: true });
      }
    } catch (error) {
      console.error(`Something went wrong...: ${error.message}`);
      console.dir({
        stack: error?.stack,
        message: error?.message
      });
    }
  };

  if (!axiosResponse || axiosResponse.csi_by_pk === null) {
    // Do something here , this is where you would return a loading box or something
    return (
      <>
        <Layout style={{ display: "flex", flexDirection: "column" }}>
          <Layout.Content
            style={{
              backgroundColor: "var(--content-bg)",
              margin: "2em 4em",
              padding: "2em",
              overflowY: "auto",
              textAlign: "center",
              display: "flex",
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Form>
              <Result
                status="error"
                title={t("csi.errors.notfoundtitle")}
                subTitle={t("csi.errors.notfoundsubtitle")}
              />
            </Form>
          </Layout.Content>
          <Layout.Footer>
            {t("csi.labels.copyright")} {t("csi.fields.surveyid", { surveyId: surveyId })}
          </Layout.Footer>
        </Layout>
      </>
    );
  } else {
    const {
      relateddata: { bodyshop, job },
      csiquestion: { config: csiquestions }
    } = axiosResponse.csi_by_pk;
    return (
      <Layout style={{ display: "flex", flexDirection: "column" }}>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center"
          }}
        >
          <div style={{ display: "flex", alignItems: "center", margin: "2em" }}>
            {bodyshop.logo_img_path && bodyshop.logo_img_path.src ? (
              <img
                src={bodyshop.logo_img_path.src}
                alt={bodyshop.shopname.concat("Logo")}
                height={bodyshop.logo_img_path.height}
                width={bodyshop.logo_img_path.width}
              />
            ) : null}
            <div style={{ margin: "2em", verticalAlign: "middle" }}>
              <Typography.Title level={4} style={{ margin: 0 }}>
                {bodyshop.shopname || ""}
              </Typography.Title>
              <Typography.Paragraph style={{ margin: 0 }}>
                {`${bodyshop.address1 || ""}${bodyshop.address2 ? ", " : ""}${bodyshop.address2 || ""}`.trim()}
              </Typography.Paragraph>
              <Typography.Paragraph style={{ margin: 0 }}>
                {`${bodyshop.city || ""}${
                  bodyshop.city && bodyshop.state ? ", " : ""
                }${bodyshop.state || ""} ${bodyshop.zip_post || ""}`.trim()}
              </Typography.Paragraph>
            </div>
          </div>
          <Typography.Title>{t("csi.labels.title")}</Typography.Title>
          <strong>
            {t("csi.labels.greeting", {
              name: job.ownr_co_nm || job.ownr_fn || ""
            })}
          </strong>
          <Typography.Paragraph>
            {t("csi.labels.intro", {
              shopname: bodyshop.shopname || ""
            })}
          </Typography.Paragraph>
        </div>
        {submitting.error ? <AlertComponent title={submitting.error} type="error" /> : null}
        {submitting.submitted ? (
          <Layout.Content
            style={{
              backgroundColor: "var(--content-bg)",
              margin: "2em 4em",
              padding: "2em",
              overflowY: "auto"
            }}
          >
            <Result status="success" title={t("csi.successes.submitted")} subTitle={t("csi.successes.submittedsub")} />
          </Layout.Content>
        ) : (
          <Layout.Content
            style={{
              backgroundColor: "var(--content-bg)",
              margin: "2em 4em",
              padding: "2em",
              overflowY: "auto"
            }}
          >
            <Form form={form} onFinish={handleFinish}>
              {axiosResponse.csi_by_pk.valid ? (
                <>
                  <ConfigFormComponents componentList={csiquestions} />
                  <Button loading={submitting.loading} type="primary" htmlType="submit" style={{ float: "right" }}>
                    {t("general.actions.submit")}
                  </Button>
                </>
              ) : (
                <>
                  <Result
                    title={t("csi.errors.surveycompletetitle")}
                    status="warning"
                    subTitle={t("csi.errors.surveycompletesubtitle", {
                      date: DateTimeFormat(axiosResponse.csi_by_pk.completedon)
                    })}
                  />
                  <Typography.Paragraph type="secondary" style={{ textAlign: "center" }}>
                    {t("csi.successes.submittedsub")}
                  </Typography.Paragraph>
                </>
              )}
            </Form>
          </Layout.Content>
        )}
        <Layout.Footer>
          {t("csi.labels.copyright")} {t("csi.fields.surveyid", { surveyId: surveyId })}
        </Layout.Footer>
      </Layout>
    );
  }
}
