import { CloudUploadOutlined } from "@ant-design/icons";
import { Alert, Input, Space, Table } from "antd";
import dayjs from '../../../util/day.js';
import React, { useState } from "react";
import { useMemo } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import ipcTypes from "../../../ipc.types";
import { setSelectedJobId } from "../../../redux/application/application.actions";
import {
  selectReportData,
  selectReportLoading,
  selectScorecard,
} from "../../../redux/reporting/reporting.selectors";
import { alphaSort } from "../../../util/sorters";
import VehicleGroupAlertAtom from "../../atoms/vehicle-group-alert/vehicle-group-alert.atom";
import GroupVerifySwitch from "../group-verify-switch/group-verify-switch.component";

const { ipcRenderer } = window;

const mapStateToProps = createStructuredSelector({
  reportingLoading: selectReportLoading,
  reportData: selectReportData,
  scoreCard: selectScorecard,
});
const mapDispatchToProps = (dispatch) => ({
  setSelectedJobId: (id) => dispatch(setSelectedJobId(id)),
});

export function ReportingJobsListMolecule({
  scoreCard,
  reportingLoading,
  reportData,
  setSelectedJobId,
}) {
  const [searchText, setSearchText] = useState("");

  const columns = [
    {
      title: "Claim No.",
      dataIndex: "clm_no",
      key: "clm_no",
      render: (text, record) => (
        <Link onClick={() => setSelectedJobId(record.id)} to={"/"}>
          <Space>
            {text}
            {record.requires_reimport && (
              <CloudUploadOutlined
                title="A change in R4P date changed the applicable rules. Import this job again for accurate scoring."
                style={{ marginLeft: ".5rem", color: "tomato" }}
              />
            )}
          </Space>
        </Link>
      ),
      sorter: (a, b) => alphaSort(a.clm_no, b.clm_no),
    },
    {
      title: "R4P",
      dataIndex: "close_date",
      key: "close_date",
      render: (text, record) => dayjs(record.close_date).format("MM/DD/YYYY"),
      defaultSortOrder: "ascend",
      sorter: (a, b) =>
        dayjs(a.close_date).unix() - dayjs(b.close_date).unix(),
    },
    {
      title: "Ins Co.",
      dataIndex: "ins_co_nm",
      key: "ins_co_nm",
      sorter: (a, b) => alphaSort(a.ins_co_nm, b.ins_co_nm),
    },
    {
      title: "First Name",
      dataIndex: "ownr_fn",
      key: "ownr_fn",
      sorter: (a, b) => alphaSort(a.ownr_fn, b.ownr_fn),
    },
    {
      title: "Last Name",
      dataIndex: "ownr_ln",
      key: "ownr_ln",
      sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
    },
    {
      title: "Vehicle",
      dataIndex: "vehicle",
      key: "vehicle",
      render: (text, record) => (
        <VehicleGroupAlertAtom job={record} showGroup />
      ),
    },
    {
      title: "Database Price Sum",
      dataIndex: "dbPriceSum",
      key: "dbPriceSum",
      sorter: (a, b) => a.dbPriceSum.getAmount() - b.dbPriceSum.getAmount(),
      render: (text, record) => record.dbPriceSum.toFormat(),
    },
    {
      title: "Actual Price Sum",
      dataIndex: "actPriceSum",
      key: "actPriceSum",
      sorter: (a, b) => a.actPriceSum.getAmount() - b.actPriceSum.getAmount(),
      render: (text, record) => record.actPriceSum.toFormat(),
    },
    {
      title: "Group Verified?",
      dataIndex: "group_verified",
      key: "group_verified",
      sorter: (a, b) => a.group_verified - b.group_verified,
      render: (text, record) => <GroupVerifySwitch job={record} />,
    },
    {
      title: "$ (Act./Target)",
      dataIndex: "jobRpsDollars",
      key: "jobRpsDollars",
      render: (text, record) => (
        <span
          style={{
            color: record.jobRpsPc > record.jobTarget ? "seagreen" : "tomato",
          }}
        >
          {`${record.jobRpsDollars.toFormat()} / ${record.expectedRpsDollars.toFormat()}`}
        </span>
      ),
    },
    {
      title: "% (Act./Target)",
      dataIndex: "price_diff_pc",
      key: "price_diff_pc",
      render: (text, record) => (
        <span
          style={{
            color: record.jobRpsPc > record.jobTarget ? "seagreen" : "tomato",
          }}
        >
          {`${(record.jobRpsPc * 100 || 0).toFixed(1)}% / ${(
            record.jobTarget * 100
          ).toFixed(1)}%`}
        </span>
      ),
    },
  ];

  const data =
    searchText !== ""
      ? reportData.filter(
          (j) =>
            j.v_makedesc.toLowerCase().includes(searchText.toLowerCase()) ||
            j.v_model.toLowerCase().includes(searchText.toLowerCase()) ||
            j.ownr_fn.toLowerCase().includes(searchText.toLowerCase()) ||
            j.ownr_ln.toLowerCase().includes(searchText.toLowerCase()) ||
            j.clm_no.toLowerCase().includes(searchText.toLowerCase())
        )
      : reportData;

  const ErroredRecords = useMemo(
    () => reportData.filter((r) => r.requires_reimport).length,
    [reportData]
  );

  return (
    <div>
      {ErroredRecords > 0 && (
        <Alert
          showIcon
          message={`${ErroredRecords} job(s) may have innacurate data due to R4P and applicable rule changes. Please import them again.`}
          type="warning"
        />
      )}
      <Table
        title={() => (
          <Input.Search
            placeholder="Search"
            onSearch={(val) => {
              ipcRenderer.send(ipcTypes.app.toMain.track, {
                event: "REPORTS_LIST_SEARCH",
                query: val,
              });
              setSearchText(val);
            }}
            enterButton
            allowClear
          />
        )}
        columns={columns}
        rowKey="id"
        loading={reportingLoading}
        size="small"
        pagination={false}
        dataSource={data}
        scroll={{
          x: true,
        }}
        summary={() => (
          <Table.Summary.Row>
            <Table.Summary.Cell index={0}>
              <strong>Totals</strong>
            </Table.Summary.Cell>
            <Table.Summary.Cell
              index={1}
            >{`${data.length} record(s)`}</Table.Summary.Cell>
            <Table.Summary.Cell index={2}></Table.Summary.Cell>
            <Table.Summary.Cell index={3}></Table.Summary.Cell>
            <Table.Summary.Cell index={4}></Table.Summary.Cell>
            <Table.Summary.Cell index={5}></Table.Summary.Cell>
            <Table.Summary.Cell index={6}>
              {scoreCard && scoreCard.allJobsSumDbPrice.toFormat()}
            </Table.Summary.Cell>
            <Table.Summary.Cell index={7}>
              {scoreCard && scoreCard.allJobsSumActPrice.toFormat()}
            </Table.Summary.Cell>
            <Table.Summary.Cell index={8}></Table.Summary.Cell>
          </Table.Summary.Row>
        )}
      />
    </div>
  );
}

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