import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Alert, Badge, Input, Space, Table, Tooltip, Switch } from "antd";
import React, { useMemo, useState } 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 {
  selectExcludedIds,
  selectReportData,
  selectReportLoading,
  selectScorecard
} from "../../../redux/reporting/reporting.selectors";
import dayjs from "../../../util/day.js";
import { alphaSort } from "../../../util/sorters";
import RequiresReimportDisplay from "../../atoms/requires-reimport/requires-reimport.atom.jsx";
import VehicleGroupAlertAtom from "../../atoms/vehicle-group-alert/vehicle-group-alert.atom";
import GroupVerifySwitch from "../group-verify-switch/group-verify-switch.component";
import JobsClaimsClerkMolecule from "../jobs-claims-clerk/jobs-claims-clerk.molecule.jsx";
import { addExcludedId, removeExcludedId } from "../../../redux/reporting/reporting.actions.js";
import { getDecimalPrecision } from "../../../util/decimalPrecision.js";

const { ipcRenderer } = window;

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

export function ReportingJobsListMolecule({
  scoreCard,
  reportingLoading,
  reportData,
  setSelectedJobId,
  excludedIds,
  addExcludedId,
  removeExcludedId
}) {
  const [searchText, setSearchText] = useState("");
  const precision = getDecimalPrecision();
  const columns = [
    {
      title: "Claim No.",
      dataIndex: "clm_no",
      key: "clm_no",
      render: (text, record) => (
        <Link onClick={() => setSelectedJobId(record.id)} to={"/"}>
          <Space>
            {text}

            {record.alerts &&
              record.alerts.length > 0 && ( //2025-05-27 Removing CC AI
                <Tooltip title="Claims Clerk AI has detected possible issues with this estimate. Review the estimate to ensure you are following MPI guidelines.">
                  <Badge count={record.alerts.length} />
                </Tooltip>
              )}
            <RequiresReimportDisplay job={record} />
          </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",
      width: "110px",
      sorter: (a, b) => dayjs(a.close_date).unix() - dayjs(b.close_date).unix()
    },
    {
      title: "Ins.",
      dataIndex: "ins_co_nm",
      key: "ins_co_nm",
      sorter: (a, b) => alphaSort(a.ins_co_nm, b.ins_co_nm),
      width: "75px",
      ellipsis: true
    },
    {
      title: "First Name",
      dataIndex: "ownr_fn",
      key: "ownr_fn",
      sorter: (a, b) => alphaSort(a.ownr_fn, b.ownr_fn),
      ellipsis: true
    },
    {
      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 />
      //ellipsis: true
    },
    {
      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} />,
      width: "100px"
    },
    {
      title: "$ Variance",
      dataIndex: "jobRpsDollarsVariance",
      key: "jobRpsDollarsVariance",
      render: (text, record) => {
        const variance = record.jobRpsDollars.subtract(record.expectedRpsDollars);
        return (
          <Space
            style={{
              color: variance.getAmount() > 0 ? "seagreen" : "tomato"
            }}
          >
            {variance.toFormat()}
          </Space>
        );
      }
    },
    {
      title: "$ (Act./Target)",
      dataIndex: "jobRpsDollars",
      key: "jobRpsDollars",
      render: (text, record) => (
        <Space
          style={{
            color: record.jobRpsPc > record.jobTarget ? "seagreen" : "tomato"
          }}
        >
          {`${record.jobRpsDollars.toFormat()} / ${record.expectedRpsDollars.toFormat()}`}
          {/* {record.v_mileage < 20000 && (
            <Tooltip title="Vehicle is under 20,000 KMs. No expected savings.">
              <WarningOutlined style={{ color: "seagreen" }} />
            </Tooltip>
          )} */}
        </Space>
      )
    },
    {
      title: "% (Act./Target)",
      dataIndex: "price_diff_pc",
      key: "price_diff_pc",
      render: (text, record) => (
        <Space
          style={{
            color: record.jobRpsPc > record.jobTarget ? "seagreen" : "tomato"
          }}
        >
          {`${(record.jobRpsPc * 100 || 0).toFixed(precision)}% / ${(record.jobTarget * 100).toFixed(precision)}%`}
        </Space>
      )
    },
    {
      title: "Temporarily Exclude",
      dataIndex: "scenario_manager",
      key: "scenario_manager",
      render: (text, record) => (
        <Switch
          checked={excludedIds.includes(record.id)}
          onChange={(checked) => {
            checked ? addExcludedId(record.id) : removeExcludedId(record.id);
            ipcRenderer.send(ipcTypes.app.toMain.track, {
              event: "TOGGLE_SCENARIO_MANAGER"
            });
          }}
        />
      )
    }
  ];

  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 close date 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}
        expandable={{
          expandedRowRender: (record) => <JobsClaimsClerkMolecule job={record} />,
          rowExpandable: (record) => record.alerts && record.alerts.length > 0
        }}
        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);
