import {useLazyQuery} from "@apollo/client";
import {Button, Card, Col, DatePicker, Form, Input, Radio, Row, Typography,} from "antd";
import _ from "lodash";
import moment from "moment";
import React, {useState} from "react";
import {useTranslation} from "react-i18next";
import {connect} from "react-redux";
import {createStructuredSelector} from "reselect";
import {QUERY_ACTIVE_EMPLOYEES} from "../../graphql/employees.queries";
import {QUERY_ALL_VENDORS} from "../../graphql/vendors.queries";
import {selectReportCenter} from "../../redux/modals/modals.selectors";
import DatePickerRanges from "../../utils/DatePickerRanges";
import {GenerateDocument} from "../../utils/RenderTemplate";
import {TemplateList} from "../../utils/TemplateConstants";
import EmployeeSearchSelect from "../employee-search-select/employee-search-select.component";
import VendorSearchSelect from "../vendor-search-select/vendor-search-select.component";
import "./report-center-modal.styles.scss";
import ReportCenterModalFiltersSortersComponent from "./report-center-modal-filters-sorters-component";
import {selectBodyshop} from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
    reportCenterModal: selectReportCenter,
    bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(ReportCenterModalComponent);

export function ReportCenterModalComponent({reportCenterModal, bodyshop}) {
  const [form] = Form.useForm();
  const [search, setSearch] = useState("");

  const [loading, setLoading] = useState(false);
  const {t} = useTranslation();
  const Templates = TemplateList("report_center");
  const ReportsList = Object.keys(Templates).map((key) => {
    return Templates[key];
  });
  const {open} = reportCenterModal;

  const [callVendorQuery, {data: vendorData, called: vendorCalled}] =
      useLazyQuery(QUERY_ALL_VENDORS, {
        skip: !(
            open &&
            Templates[form.getFieldValue("key")] &&
            Templates[form.getFieldValue("key")].idtype
        ),
      });

  const [callEmployeeQuery, {data: employeeData, called: employeeCalled}] =
      useLazyQuery(QUERY_ACTIVE_EMPLOYEES, {
        skip: !(
            open &&
            Templates[form.getFieldValue("key")] &&
            Templates[form.getFieldValue("key")].idtype
        ),
      });

  const handleFinish = async (values) => {
    setLoading(true);
    const start = values.dates ? values.dates[0] : null;
    const end = values.dates ? values.dates[1] : null;
    const { id } = values;

      const templateConfig = {
          name: values.key,
          variables: {
              ...(start
                  ? {start: moment(start).startOf("day").format("YYYY-MM-DD")}
                  : {}),
              ...(end ? {end: moment(end).endOf("day").format("YYYY-MM-DD")} : {}),
              ...(start ? {starttz: moment(start).startOf("day")} : {}),
              ...(end ? {endtz: moment(end).endOf("day")} : {}),

              ...(id ? {id: id} : {}),
          },
          filters: values.filters,
          sorters: values.sorters,
      };

      if (_.isString(values.defaultSorters) && !_.isEmpty(values.defaultSorters)) {
          templateConfig.defaultSorters = JSON.parse(values.defaultSorters);
      }

      await GenerateDocument(
          templateConfig,
        {
          to: values.to,
          subject: Templates[values.key]?.subject,
        },
        values.sendbyexcel === "excel"
            ? "x"
            : values.sendby === "email"
                ? "e"
                : "p",
        id
    );
    setLoading(false);
  };

  const FilteredReportsList =
      search !== ""
          ? ReportsList.filter((r) =>
              r.title.toLowerCase().includes(search.toLowerCase())
          )
          : ReportsList;

  //Group it, create cards, and then filter out.

  const grouped = _.groupBy(FilteredReportsList, "group");

  return (
      <div>
        <Form
            onFinish={handleFinish}
            autoComplete={"off"}
            layout="vertical"
            form={form}
        >
          <Input.Search
              onChange={(e) => setSearch(e.target.value)}
              value={search}
          />
            <Form.Item name="defaultSorters" hidden/>
            <Form.Item
              name="key"
              label={t("reportcenter.labels.key")}
              //  className="radio-group-columns"
              rules={[
                {
                  required: true,
                  //message: t("general.validation.required"),
                },
              ]}
          >
            <Radio.Group>
              {/* {Object.keys(Templates).map((key) => (
                <Radio key={key} value={key}>
                  {Templates[key].title}
                </Radio>
              ))} */}

              <Row gutter={[16, 16]}>
                {Object.keys(grouped).map((key) => (
                    <Col md={8} sm={12} key={key}>
                      <Card.Grid
                          style={{
                            width: "100%",
                            height: "100%",
                            maxHeight: "33vh",
                            overflowY: "scroll",
                          }}
                      >
                        <Typography.Title level={4}>
                          {t(`reportcenter.labels.groups.${key}`)}
                        </Typography.Title>
                        <ul style={{  listStyleType: 'none', columns: "2 auto"}}>
                          {grouped[key].map((item) => (
                              <li key={item.key}>
                                <Radio key={item.key} value={item.key}>
                                  {item.title}
                                </Radio>
                              </li>
                          ))}
                        </ul>
                      </Card.Grid>
                    </Col>
                ))}
              </Row>
            </Radio.Group>
          </Form.Item>
          <Form.Item style={{margin: 0, padding: 0}} dependencies={["key"]}>
            {() => {
              const key = form.getFieldValue("key");
              if (!key) return null;
              //Kind of Id
              const rangeFilter = Templates[key] && Templates[key].rangeFilter;
              if (!rangeFilter) return null;
              return (
                  <div>
                    {t("reportcenter.labels.filterson", {
                      object: rangeFilter.object,
                      field: rangeFilter.field,
                    })}
                  </div>
              );
            }}
          </Form.Item>
            <ReportCenterModalFiltersSortersComponent form={form} bodyshop={bodyshop} />
          <Form.Item style={{margin: 0, padding: 0}} dependencies={["key"]}>
            {() => {
              const key = form.getFieldValue("key");
              const currentId = form.getFieldValue("id");
              if (!key) return null;
              //Kind of Id
              const idtype = Templates[key] && Templates[key].idtype;
              if (!idtype && currentId) {
                form.setFieldsValue({id: null});
                return null;
              }
              if (!vendorCalled && idtype === "vendor") callVendorQuery();
              if (!employeeCalled && idtype === "employee") callEmployeeQuery();
              if (idtype === "vendor")
                return (
                    <Form.Item
                        name="id"
                        label={t("reportcenter.labels.vendor")}
                        rules={[
                          {
                            required: true,
                            //message: t("general.validation.required"),
                          },
                        ]}
                    >
                      <VendorSearchSelect
                          options={vendorData ? vendorData.vendors : []}
                      />
                    </Form.Item>
                );
              if (idtype === "employee")
                return (
                    <Form.Item
                        name="id"
                        label={t("reportcenter.labels.employee")}
                        rules={[
                          {
                            required: true,
                            //message: t("general.validation.required"),
                          },
                        ]}
                    >
                      <EmployeeSearchSelect
                          options={employeeData ? employeeData.employees : []}
                      />
                    </Form.Item>
                );
              else return null;
            }}
          </Form.Item>
          <Form.Item style={{margin: 0, padding: 0}} dependencies={["key"]}>
            {() => {
              const key = form.getFieldValue("key");
              const datedisable = Templates[key] && Templates[key].datedisable;

              // TODO: MERGE NOTE, Ranges turns to presets in DatePicker.RangePicker

              if (datedisable !== true) {
                return (
                    <Form.Item
                        name="dates"
                        label={t("reportcenter.labels.dates")}
                        rules={[
                          {
                            required: true,
                            //message: t("general.validation.required"),
                          },
                        ]}
                    >
                      <DatePicker.RangePicker
                          format="MM/DD/YYYY"
                          ranges={DatePickerRanges}
                      />
                    </Form.Item>
                );
              } else return null;
            }}
          </Form.Item>
          <Form.Item style={{margin: 0, padding: 0}} dependencies={["key"]}>
            {() => {
              const key = form.getFieldValue("key");
              //Kind of Id
              const reporttype = Templates[key] && Templates[key].reporttype;

              if (reporttype === "excel")
                return (
                    <Form.Item
                        label={t("general.labels.sendby")}
                        name="sendbyexcel"
                        initialValue="excel"
                    >
                      <Radio.Group>
                        <Radio value="excel">{t("general.labels.excel")}</Radio>
                      </Radio.Group>
                    </Form.Item>
                );
              if (reporttype !== "excel")
                return (
                    <Form.Item
                        label={t("general.labels.sendby")}
                        name="sendby"
                        initialValue="print"
                    >
                      <Radio.Group>
                        <Radio value="email">{t("general.labels.email")}</Radio>
                        <Radio value="print">{t("general.labels.print")}</Radio>
                      </Radio.Group>
                    </Form.Item>
                );
            }}
          </Form.Item>

          <div
              style={{
                display: "flex",
                justifyContent: "center",
                marginTop: "1rem",
              }}
          >
            <Button onClick={() => form.submit()} style={{}} loading={loading}>
              {t("reportcenter.actions.generate")}
            </Button>
          </div>
        </Form>
      </div>
  );
}

