import { useQuery, useMutation } from "@apollo/client";
import { Form, Layout, Typography, Button, Result } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
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 { QUERY_SURVEY, COMPLETE_SURVEY } from "../../graphql/csi.queries";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectCurrentUser } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(CsiContainerPage);

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

  const { loading, error, data } = useQuery(QUERY_SURVEY, {
    variables: { surveyId },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
  });

  const { t } = useTranslation();
  const [completeSurvey] = useMutation(COMPLETE_SURVEY);
  if (loading) return <LoadingSpinner />;

  if (error || !!!data.csi_by_pk)
    return (
      <div>
        <Result
          status="error"
          title={t("csi.errors.notfoundtitle")}
          subTitle={t("csi.errors.notfoundsubtitle")}
        >
          {error ? (
            <div>ERROR: {error.graphQLErrors.map((e) => e.message)}</div>
          ) : null}
        </Result>
      </div>
    );

  const handleFinish = async (values) => {
    setSubmitting({ ...submitting, loading: true });

    const result = await completeSurvey({
      variables: {
        surveyId,
        survey: {
          response: values,
          valid: false,
          completedon: new Date(),
        },
      },
    });

    if (!!!result.errors) {
      setSubmitting({ ...submitting, loading: false, submitted: true });
    } else {
      setSubmitting({
        ...submitting,
        loading: false,
        error: JSON.stringify(result.errors),
      });
    }
  };

  const {
    relateddata: { bodyshop, job },
    csiquestion: { config: csiquestions },
  } = data.csi_by_pk;

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

  return (
    <Layout
      style={{ height: "100vh", 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="Logo" />
          ) : null}
          <div style={{ margin: "2em" }}>
            <strong>{bodyshop.shopname || ""}</strong>
            <div>{`${bodyshop.address1 || ""}`}</div>
            <div>{`${bodyshop.address2 || ""}`}</div>
            <div>{`${bodyshop.city || ""} ${bodyshop.state || ""} ${
              bodyshop.zip_post || ""
            }`}</div>
          </div>
        </div>
        <Typography.Title>{t("csi.labels.title")}</Typography.Title>
        <strong>{`Hi ${job.ownr_co_nm || job.ownr_fn || ""}!`}</strong>
        <Typography.Paragraph>
          {`At ${
            bodyshop.shopname || ""
          }, we value your feedback. We would love to
          hear what you have to say. Please fill out the form below.`}
        </Typography.Paragraph>
      </div>

      {submitting.error ? (
        <AlertComponent message={submitting.error} type="error" />
      ) : null}

      {submitting.submitted ? (
        <Layout.Content
          style={{
            backgroundColor: "#fff",
            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: "#fff",
            margin: "2em 4em",
            padding: "2em",
            overflowY: "auto",
          }}
        >
          <Form form={form} onFinish={handleFinish}>
            <ConfigFormComponents componentList={csiquestions} />
            <Button
              loading={submitting.loading}
              type="primary"
              htmlType="submit"
            >
              {t("general.actions.submit")}
            </Button>
          </Form>
        </Layout.Content>
      )}

      <Layout.Footer>
        {`Copyright ImEX.Online. Survey ID: ${surveyId}`}
      </Layout.Footer>
    </Layout>
  );
}
