import {
  DeleteFilled,
  PlusCircleFilled,
  SyncOutlined,
} from "@ant-design/icons";
import { Button, notification, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { alphaSort } from "../../utils/sorters";
import JobsFindModalContainer from "../jobs-find-modal/jobs-find-modal.container";

export default function JobsAvailableSupplementComponent({
  loading,
  data,
  refetch,
  deleteJob,
  onModalOk,
  onModalCancel,
  modalVisible,
  setModalVisible,
  selectedJob,
  setSelectedJob,
  deleteAllNewJobs,
  loadEstData,
  estData,
  importOptionsState,
  modalSearchState,
}) {
  const { t } = useTranslation();

  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" },
  });

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };

  const columns = [
    {
      title: t("jobs.fields.cieca_id"),
      dataIndex: "cieca_id",
      key: "cieca_id",
      //width: "8%",
      // onFilter: (value, record) => record.ro_number.includes(value),
      // filteredValue: state.filteredInfo.text || null,
      sorter: (a, b) => alphaSort(a, b),
      sortOrder:
        state.sortedInfo.columnKey === "cieca_id" && state.sortedInfo.order,
    },
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "job_id",
      key: "job_id",
      //width: "8%",
      // onFilter: (value, record) => record.ro_number.includes(value),
      // filteredValue: state.filteredInfo.text || null,
      sorter: (a, b) => alphaSort(a, b),
      sortOrder:
        state.sortedInfo.columnKey === "cieca_id" && state.sortedInfo.order,
      render: (text, record) => <div>{record.job && record.job.ro_number}</div>,
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "ownr_name",
      key: "ownr_name",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
      //width: "25%",
      sortOrder:
        state.sortedInfo.columnKey === "ownr_name" && state.sortedInfo.order,
    },
    {
      title: t("jobs.fields.vehicle"),
      dataIndex: "vehicle_info",
      key: "vehicle_info",
      sorter: (a, b) => alphaSort(a.vehicle_info, b.vehicle_info),
      sortOrder:
        state.sortedInfo.columnKey === "vehicle_info" && state.sortedInfo.order,
      //ellipsis: true
    },
    {
      title: t("jobs.fields.clm_no"),
      dataIndex: "clm_no",
      key: "clm_no",
      sorter: (a, b) => alphaSort(a.clm_no, b.clm_no),
      sortOrder:
        state.sortedInfo.columnKey === "clm_no" && state.sortedInfo.order,
      //width: "12%",
      //ellipsis: true
    },
    {
      title: t("jobs.fields.clm_total"),
      dataIndex: "clm_amt",
      key: "clm_amt",
      sorter: (a, b) => a.clm_amt - b.clm_amt,
      sortOrder:
        state.sortedInfo.columnKey === "clm_amt" && state.sortedInfo.order,
      render: (text, record) => (
        <CurrencyFormatter>{record.clm_amt}</CurrencyFormatter>
      ),
      //width: "12%",
      //ellipsis: true
    },
    {
      title: t("jobs.fields.uploaded_by"),
      dataIndex: "uploaded_by",
      key: "uploaded_by",
      sorter: (a, b) => alphaSort(a.uploaded_by, b.uploaded_by),
      sortOrder:
        state.sortedInfo.columnKey === "uploaded_by" && state.sortedInfo.order,
      //width: "12%",
      //ellipsis: true
    },
    {
      title: t("jobs.fields.updated_at"),
      dataIndex: "updated_at",
      key: "updated_at",
      sorter: (a, b) => new Date(a.updated_at) - new Date(b.updated_at),
      sortOrder:
        state.sortedInfo.columnKey === "updated_at" && state.sortedInfo.order,
      render: (text, record) => (
        <DateTimeFormatter>{record.updated_at}</DateTimeFormatter>
      ),
      //width: "12%",
      //ellipsis: true
    },
    {
      title: t("general.labels.actions"),
      key: "actions",
      render: (text, record, index) => (
        <span>
          <Button
            onClick={() => {
              deleteJob({ variables: { id: record.id } }).then((r) => {
                notification["success"]({
                  message: t("jobs.successes.deleted"),
                });
                refetch();
              });
            }}>
            <DeleteFilled />
          </Button>
          <Button
            onClick={() => {
              loadEstData({ variables: { id: record.id } });
              modalSearchState[1](record.clm_no);
              setModalVisible(true);
            }}>
            <PlusCircleFilled />
          </Button>
        </span>
      ),
    },
  ];

  const handleDeleteAll = () => {
    deleteAllNewJobs()
      .then((r) => {
        notification["success"]({
          message: t("jobs.successes.all_deleted", {
            count: r.data.delete_available_jobs.affected_rows,
          }),
        });
        refetch();
      })
      .catch((r) => {
        notification["error"]({
          message: t("jobs.errors.deleted") + " " + r.message,
        });
      });
  };

  return (
    <div>
      <JobsFindModalContainer
        loading={estData.loading}
        error={estData.error}
        selectedJob={selectedJob}
        setSelectedJob={setSelectedJob}
        importOptionsState={importOptionsState}
        visible={modalVisible}
        onOk={onModalOk}
        onCancel={onModalCancel}
        modalSearchState={modalSearchState}
      />
      <Table
        loading={loading}
        title={() => {
          return (
            <div>
              <strong>{t("jobs.labels.availablesupplements")}</strong>
              <Button
                onClick={() => {
                  refetch();
                }}>
                <SyncOutlined />
              </Button>
              <Button onClick={handleDeleteAll}>Delete All</Button>
            </div>
          );
        }}
        size='small'
        pagination={{ position: "top" }}
        columns={columns}
        rowKey='id'
        dataSource={data && data.available_jobs}
        onChange={handleTableChange}
      />
    </div>
  );
}
