import { PrinterFilled } from "@ant-design/icons";
import { Alert, Button, Card, Col, DatePicker, Form, Input, Result, Row, Select, Space, Typography } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { connect } from "react-redux";
import { useReactToPrint } from "react-to-print";
import { createStructuredSelector } from "reselect";
import ipcTypes from "../../../ipc.types";
import { queryReportingData } from "../../../redux/reporting/reporting.actions";
import { selectAuditError, selectReportingError } from "../../../redux/reporting/reporting.selectors";
import dayjs from "../../../util/day";
import AuditResultsOrganism from "../../organisms/audit-results/audit-results.organism";
import FeatureWrapper from "../../templates/feature-wrapper";
import "./audit.page.styles.scss";
import { selectBodyshop } from "../../../redux/user/user.selectors";
import { Link } from "react-router-dom";
import { setSelectedJobId } from "../../../redux/application/application.actions";

const { ipcRenderer } = window;

const getAuditDatePresets = () => [
  {
    label: "2 Months ago",
    value: [
      dayjs().startOf("month").subtract(2, "month"),
      dayjs().startOf("month").subtract(2, "month").endOf("month")
    ]
  },
  {
    label: "Last Month",
    value: [
      dayjs().startOf("month").subtract(1, "month"),
      dayjs().startOf("month").subtract(1, "month").endOf("month")
    ]
  },
  { label: "This Month", value: [dayjs().startOf("month"), dayjs().endOf("month")] },
  {
    label: "Last Quarter",
    value: [
      dayjs().startOf("quarter").subtract(1, "quarter"),
      dayjs().startOf("quarter").subtract(1, "day")
    ]
  },
  {
    label: "Last 3 Months",
    value: [
      dayjs().startOf("month").subtract(3, "month"),
      dayjs().startOf("month").subtract(1, "month").endOf("month")
    ]
  }
];

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
  auditError: selectAuditError,
  reportingError: selectReportingError
});
const mapDispatchToProps = (dispatch) => ({
  queryReportingData: (dates) => dispatch(queryReportingData(dates)),
  setSelectedJobId: (id) => dispatch(setSelectedJobId(id))
});
export default connect(mapStateToProps, mapDispatchToProps)(AuditPage);

export function AuditPage({ auditError, queryReportingData, bodyshop, reportingError, setSelectedJobId }) {
  const [form] = Form.useForm();
  const auditDatePresets = getAuditDatePresets();
  const [sheets, setSheets] = useState([]);
  useEffect(() => {
    ipcRenderer.on(ipcTypes.audit.toRenderer.auditFilePath, async (event, { filePath, sheets }) => {
      setSheets(sheets);
      if (sheets.includes("Shop RPS Claim Detail")) {
        form.setFieldsValue({ sheetName: "Shop RPS Claim Detail" });
      }
      form.setFieldsValue({ filePath });
    });

    return () => {
      //ipcRenderer.removeListener(ipcTypes.audit.toRenderer.auditFilePath);
    };
  }, [form]);

  const handleBrowseForFile = async () => {
    const { dateRange } = form.getFieldsValue();
    queryReportingData({
      startDate: dateRange[0],
      endDate: dateRange[1]
    });
    ipcRenderer.send(ipcTypes.audit.toMain.browseForFile, {});
  };

  const handleRunAudit = async ({ sheetName, dateRange }) => {
    ipcRenderer.send(ipcTypes.app.toMain.track, {
      event: "RUN_AUDIT"
    });
    ipcRenderer.send(ipcTypes.audit.toMain.runAudit, { sheetName });
  };

  const componentRef = useRef();
  const handlePrint = useReactToPrint({
    content: () => componentRef.current,
    bodyClass: "audit-container-print"
  });

  window.ref = componentRef.current;
  if (auditError) console.log("Error when opening audit file.", auditError);
  return (
    <FeatureWrapper featureName="audit" noauth={<NoAuditAccess features={bodyshop.features} />}>
      <div className="audit-container" id="audit-results-container">
        {bodyshop.features.audit_trial && (
          <Alert
            type="info"
            message={`You are currently on a trial of the RPS audit functionality. It will expire on ${bodyshop.features.audit_trial}`}
          />
        )}
        <Row gutter={[16, 16]} ref={componentRef}>
          <Col span={24}>
            <Card>
              <Form form={form} onFinish={handleRunAudit}>
                <Form.Item
                  label="1. Ready for Payment Date Between"
                  name="dateRange"
                  tooltip="Select the time period that you would like to audit. This is typically a whole month or quarter."
                  rules={[
                    { type: "array", required: true },
                    {
                      validator(rule, value) {
                        if (!value || !value.length === 2) {
                          return Promise.resolve();
                        }

                        // if (dayjs(value[1]).diff(dayjs(value[0]), "month", true) > 1) {
                        //   return Promise.reject("Time period exceeds 1 month. Please select a shorter date range.");
                        // } else {
                        return Promise.resolve();
                        // }
                      }
                    }
                  ]}
                >
                  <DatePicker.RangePicker format="MM/DD/YYYY" presets={auditDatePresets} />
                </Form.Item>

                <Space align="middle" wrap>
                  <Form.Item
                    label="2. File Path"
                    name="filePath"
                    tooltip="File path to the MPI score card you want to audit. Ensure that this scorecard has not been modified or altered in any way."
                    rules={[{ required: true }]}
                  >
                    <Input disabled width="200px" />
                  </Form.Item>
                  <Form.Item shouldUpdate>
                    {() => {
                      const disabled = !form.getFieldsValue().dateRange;
                      return (
                        <Button disabled={disabled} onClick={handleBrowseForFile}>
                          Select MPI Audit XLS File
                        </Button>
                      );
                    }}
                  </Form.Item>
                  <Form.Item
                    label="3. Sheet Name"
                    tooltip="The name of the sheet which contains detailed RPS claim data."
                    name="sheetName"
                    rules={[{ required: true }]}
                  >
                    {/* <Input width="200px" /> */}
                    <Select
                      style={{ minWidth: "200px" }}
                      options={sheets.map((sheet) => ({ label: sheet, value: sheet }))}
                    />
                  </Form.Item>
                  <Form.Item shouldUpdate>
                    {() => {
                      return (
                        <Button type="primary" htmlType="submit">
                          Run Audit
                        </Button>
                      );
                    }}
                  </Form.Item>
                  <Button onClick={handlePrint}>
                    <PrinterFilled />
                  </Button>
                </Space>
              </Form>
            </Card>
          </Col>
          {auditError && (
            <Col span={24}>
              <Alert
                type="error"
                banner
                message="Error encountered when opening the audit file. Please ensure it is not open in any other programs, and the sheet name is correct."
              />
            </Col>
          )}
          {reportingError && (
            <div>
              <Typography.Title level={4}>{reportingError.message}</Typography.Title>
              <ul>
                {reportingError.jobs.map((j, idx) => (
                  <li key={idx}>
                    <Link onClick={() => setSelectedJobId(j.id)} to={"/"}>
                      {`${j.clm_no} - ${j.error}`}
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
          )}
          <AuditResultsOrganism />
        </Row>
      </div>
    </FeatureWrapper>
  );
}

function NoAuditAccess({ features }) {
  return (
    <Result
      status="warning"
      title="You do not currently have access to the audit feature of ImEX RPS."
      subTitle="Auditing allows you to instantly and automatically find discrepancies between the data you have recorded in ImEX RPS and the scorecard provided to your by your SRA."
      extra={[
        <Button
          size="large"
          type="primary"
          onClick={() => {
            window.$crisp.push(["do", "chat:open"]);
            window.$crisp.push(["do", "message:thread:start", ["Subscription Upgrade - RPS Audit"]]);
            window.$crisp.push([
              "do",
              "message:send",
              ["text", "Hello, I would like to subscribe to the RPS audit feature."]
            ]);
          }}
        >
          Subscribe
        </Button>,
        <Button
          size="large"
          disabled={features.audit_trial}
          onClick={() => {
            window.$crisp.push(["do", "chat:open"]);
            window.$crisp.push(["set", "session:event", [[["trial_request", { feature: "audit" }]]]]);
            window.$crisp.push(["do", "message:thread:start", ["Trial Request - RPS Audit"]]);
            window.$crisp.push([
              "do",
              "message:send",
              ["text", "Hello, I would like to request a trial of the RPS audit feature."]
            ]);
          }}
        >
          {features.audit_trial ? `(Trial ended on ${features.audit_trial})` : "Request Trial"}
        </Button>
      ]}
    />
  );
}
