import { Card, Col, Divider, Empty, Result, Space, Table, Tooltip } from "antd";
import Dinero from "dinero.js";
import React from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { setSelectedJobId, setSelectedJobTargetPc } from "../../../redux/application/application.actions";
import { selectAuditData, selectAuditLoading } from "../../../redux/reporting/reporting.selectors";
import { DateFormat } from "../../../util/constants";
import dayjs from "../../../util/day";
import { alphaSort, dateSort } from "../../../util/sorters";
import RequiresReimportDisplay from "../../atoms/requires-reimport/requires-reimport.atom";

const mapStateToProps = createStructuredSelector({
  selectAuditData: selectAuditData,
  auditLoading: selectAuditLoading
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
  setSelectedJobId: (id) => dispatch(setSelectedJobId(id)),
  setSelectedJobTargetPc: (job) => dispatch(setSelectedJobTargetPc(job))
});

export function AuditResultsOrganism({ auditLoading, setSelectedJobId, selectAuditData }) {
  const missingColumns = [
    {
      key: "clm_no",
      width: "12%",
      title: "Claim No.",
      sorter: (a, b) => alphaSort(a.clm_no, b.clm_no),
      dataIndex: "clm_no",
      render: (text, record) =>
        record.id ? (
          <Link onClick={() => setSelectedJobId(record.id)} to={"/"}>
            {text}
          </Link>
        ) : (
          text
        )
    },
    {
      key: "close_date",
      width: "12%",
      title: "[ImEX RPS] Close",
      dataIndex: "close_date",
      defaultSortOrder: "ascend",
      sorter: (a, b) => dateSort(a.close_date, b.close_date),
      render: (text, record) => dayjs(record.close_date).format(DateFormat)
    },
    { key: "v_model_yr", width: "12%", title: "Model Year", dataIndex: "v_model_yr" },
    { key: "v_makedesc", width: "20%", title: "Make", dataIndex: "v_makedesc" },
    { key: "v_model", width: "20%", title: "Model", dataIndex: "v_model" },
    {
      key: "expected_rps",
      width: "12%",
      title: "Expected RPS ",
      dataIndex: ["audit", "expectedRpsDollars"],
      render: (text, record) =>
        record.expectedRpsDollars
          ? record?.expectedRpsDollars?.toFormat()
          : Dinero({ amount: Math.round((record?.expected_rps_dollars || 0) * 100) }).toFormat()
    },
    {
      key: "actual_rps",
      width: "12%",
      title: " Actual RPS",
      dataIndex: ["audit", "jobRpsDollars"],
      render: (text, record) =>
        record?.jobRpsDollars
          ? record?.jobRpsDollars.toFormat()
          : Dinero({ amount: Math.round((record?.actual_rps_dollars || 0) * 100) }).toFormat()
    }
  ];

  const mismatchColumns = [
    {
      key: "clm_no",
      width: "12%",
      title: "Claim No.",
      sorter: (a, b) => alphaSort(a.rps.clm_no, b.rps.clm_no),
      dataIndex: ["rps", "clm_no"],
      render: (text, record) =>
        record.rps?.id ? (
          <Link onClick={() => setSelectedJobId(record.rps.id)} to={"/"}>
            <Space size="small">
              {text}
              <RequiresReimportDisplay job={record.rps} />
            </Space>
          </Link>
        ) : (
          text
        )
    },
    {
      key: "close_date",
      title: "[ImEX RPS] Close",
      dataIndex: "close_date",
      defaultSortOrder: "ascend",
      sorter: (a, b) => dateSort(a.rps.close_date, b.rps.close_date),
      render: (text, record) => dayjs(record.rps.close_date).format(DateFormat)
    },
    {
      key: "close_date_audit",
      width: "12%",
      title: "[MPI Audit] Close",
      dataIndex: "close_date_audit",
      sorter: (a, b) => dateSort(a.audit.close_date, b.audit.close_date),

      render: (text, record) => dayjs(record.audit.close_date).format(DateFormat)
    },
    { key: "v_model_yr", width: "12%", title: "Model Year", dataIndex: ["audit", "v_model_yr"] },
    { key: "v_makedesc", width: "12%", title: "Make", dataIndex: ["audit", "v_makedesc"] },
    { key: "v_model", width: "12%", title: "Model", dataIndex: ["audit", "v_model"] },
    {
      key: "expected_rps",
      width: "12%",
      title: "Expected RPS (ImEX RPS/Audit)",
      dataIndex: ["audit", "expectedRpsDollars"],
      render: (text, record) => (
        <Space split={<Divider type="vertical" />}>
          <Tooltip title="ImEX RPS Expected Savings">{record.rps.expectedRpsDollars.toFormat()}</Tooltip>
          <Tooltip title="MPI Audit Expected Savings">
            {Dinero({ amount: Math.round(record.audit.expected_rps_dollars * 100) }).toFormat()}
          </Tooltip>
        </Space>
      )
    },
    {
      key: "actual_rps",
      width: "12%",
      title: " Actual RPS (ImEX RPS/Audit)",
      dataIndex: ["audit", "jobRpsDollars"],
      render: (text, record) => (
        <Space split={<Divider type="vertical" />}>
          <Tooltip title="ImeX RPS Actual Savings">{record.rps.jobRpsDollars.toFormat()}</Tooltip>
          <Tooltip title="MPI Audit Actual Savings">
            {Dinero({ amount: Math.round(record.audit.actual_rps_dollars * 100) }).toFormat()}
          </Tooltip>
        </Space>
      )
    }
  ];

  if (Object.keys(selectAuditData).length === 0)
    return (
      <Col span={24}>
        <Card>
          <Empty
            // image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
            // imageStyle={{
            //   height: 60
            // }}
            description={
              <span>No audit has been run yet. Please select a date range and audit file to view results.</span>
            }
          />
        </Card>
      </Col>
    );

  return (
    <>
      <Col span={24}>
        <Card title="Jobs in ImEX RPS, not found in MPI Audit">
          <Table
            loading={auditLoading}
            columns={missingColumns}
            pagination={false}
            dataSource={selectAuditData?.missingFromRps}
            rowKey="clm_no"
            locale={{
              emptyText: <Result status="success" subTitle="No discrepancies found." />
            }}
          />
        </Card>
      </Col>
      <Col span={24}>
        <Card title="Jobs in MPI Audit, not in ImEX RPS">
          <Table
            loading={auditLoading}
            columns={missingColumns}
            pagination={false}
            dataSource={selectAuditData?.missingFromAudit}
            rowKey="clm_no"
            locale={{
              emptyText: <Result status="success" subTitle="No discrepancies found." />
            }}
          />
        </Card>
      </Col>
      <Col span={24}>
        <Card title="Mismatch - Expected Savings">
          <Table
            loading={auditLoading}
            columns={mismatchColumns}
            pagination={false}
            dataSource={selectAuditData?.expectedMismatch}
            rowKey="clm_no"
            locale={{
              emptyText: <Result status="success" subTitle="No discrepancies found." />
            }}
          />
        </Card>
      </Col>
      <Col span={24}>
        <Card title="Mismatch - Actual Savings">
          <Table
            loading={auditLoading}
            columns={mismatchColumns}
            pagination={false}
            dataSource={selectAuditData?.actualMismatch}
            rowKey="clm_no"
            locale={{
              emptyText: <Result status="success" subTitle="No discrepancies found." />
            }}
          />
        </Card>
      </Col>
    </>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(AuditResultsOrganism);
