import { CalculatorOutlined } from "@ant-design/icons";
import { Input, Space, Table, Tag } from "antd";
import { useState } from "react";
import ipcTypes from "../../../ipc.types";
import { alphaSort } from "../../../util/sorters";
import CurrencyFormatterAtom from "../../atoms/currency-formatter/currency-formatter.atom";
import ErrorResultAtom from "../../atoms/error-result/error-result.atom";
import IgnoreJobLine from "../../atoms/ignore-job-line/ignore-job-line.atom";
import partTypeConverterAtom from "../../atoms/part-type-converter/part-type-converter.atom";
import PriceDiffPcFormatterAtom from "../../atoms/price-diff-pc-formatter/price-diff-pc-formatter.atom";

const { ipcRenderer } = window;

export default function JobLinesTableMolecule({ loading, job }) {
  const [searchText, setSearchText] = useState("");
  const [filters, setFilters] = useState({ ignore: ["false", "ai"] });

  if (!job) {
    return <ErrorResultAtom title="Error Displaying Job Lines" errorMessage="It looks like this job doesn't exist." />;
  }
  const { joblines } = job;
  const columns = [
    {
      title: "#",
      dataIndex: "line_no",
      key: "line_no",
      sorter: (a, b) => a.line_no - b.line_no,
      width: "5%"
    },
    {
      title: "S#",
      dataIndex: "line_ind",
      key: "line_ind",
      width: "5%",
      sorter: (a, b) => alphaSort(a.line_ind, b.line_ind)
    },
    {
      title: "Line Description",
      dataIndex: "line_desc",
      key: "line_desc",
      width: "25%",
      sorter: (a, b) => alphaSort(a.line_desc, b.line_desc),
      render: (text, record) => (
        <Space wrap size={"small"}>
          {record.line_desc}
          {record.part_qty > 1 && <Tag color="orange">Quantity {">"} 1</Tag>}
          {record.price_diff < 0 && !record.db_ref?.startsWith("9005") && <Tag color="orange">Negative Savings</Tag>}
          {/* {record.alerts &&
            record.alerts.length > 0 &&
            record.alerts.map((alert) => (
              <Tag key={`${record.id}-${alert.key}`} color="red">
                {alert.key}
              </Tag>
            ))} */}
        </Space>
      )
    },
    {
      title: "Part Type",
      dataIndex: "part_type",
      key: "part_type",
      width: "5%",
      sorter: (a, b) => alphaSort(a.part_type, b.part_type),
      render: (text, record) => partTypeConverterAtom(text)
    },
    {
      title: "Part Number",
      dataIndex: "oem_partno",
      key: "oem_partno",
      width: "15%",
      sorter: (a, b) => alphaSort(a.oem_partno, b.oem_partno)
    },
    {
      title: "Qty.",
      dataIndex: "part_qty",
      key: "part_qty",
      width: "5%",
      sorter: (a, b) => a.part_qty - b.part_qty
    },
    {
      title: "Database Price",
      dataIndex: "db_price",
      key: "db_price",
      width: "10%",
      sorter: (a, b) => a.db_price - b.db_price,
      render: (text, record) => <CurrencyFormatterAtom>{record.db_price}</CurrencyFormatterAtom>
    },
    {
      title: "Actual Price",
      dataIndex: "act_price",
      key: "act_price",
      width: "10%",
      sorter: (a, b) => a.act_price - b.act_price,
      render: (text, record) => <CurrencyFormatterAtom>{record.act_price}</CurrencyFormatterAtom>
    },
    {
      title: "Price Diff.",
      dataIndex: "price_diff",
      key: "price_diff",
      width: "10%",
      sorter: (a, b) => a.price_diff - b.price_diff,
      render: (text, record) => <CurrencyFormatterAtom>{record.price_diff}</CurrencyFormatterAtom>
    },
    {
      title: "Price Diff. %",
      dataIndex: "price_diff_pc",
      key: "price_diff_pc",
      width: "10%",
      sorter: (a, b) => a.price_diff_pc - b.price_diff_pc,
      render: (text, record) => (
        <PriceDiffPcFormatterAtom price_diff_pc={record.price_diff_pc} v_age={job.v_age} group={job.group} />
      )
    },
    {
      title: <CalculatorOutlined />,
      dataIndex: "ignore",
      key: "ignore",
      filters: [
        { text: "Eligible for RPS Calculation", value: false },
        { text: "Ineligible for RPS Calculation", value: true }
        // { text: "Lines with identified issues", value: "ai" }
      ],
      width: "5%",
      filteredValue: filters.ignore || null,
      onFilter: (value, record) => (value === "ai" ? record.alerts?.length > 0 : value === record.ignore),
      render: (text, record) => <IgnoreJobLine lineId={record.id} ignore={record.ignore} line_desc={record.line_desc} />
    }
  ];

  const data =
    searchText !== "" ? joblines.filter((j) => j.line_desc.toLowerCase().includes(searchText.toLowerCase())) : joblines;

  const handleChange = (pagination, filters, sorter) => {
    setFilters(filters);
  };

  return (
    <Space direction="vertical" style={{ width: "100%" }}>
      <Input.Search
        placeholder="Search"
        onSearch={(val) => {
          ipcRenderer.send(ipcTypes.app.toMain.track, {
            event: "JOB_LINES_SEARCH",
            query: val
          });
          setSearchText(val);
        }}
        enterButton
        allowClear
      />
      <Table
        columns={columns}
        rowKey="id"
        loading={loading}
        size="small"
        pagination={false}
        dataSource={data}
        onChange={handleChange}
        scroll={{
          x: true
          // y: "20rem"
        }}
      />
    </Space>
  );
}
