import { SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Table, Typography } from "antd";
import queryString from "query-string";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { setModalContext } from "../../redux/modals/modals.actions";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { alphaSort } from "../../utils/sorters";
import ContractsFindModalContainer from "../contracts-find-modal/contracts-find-modal.container";

import dayjs from "../../utils/day";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { pageLimit } from "../../utils/config";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
  setContractFinderContext: (context) => dispatch(setModalContext({ context: context, modal: "contractFinder" }))
});

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

export function ContractsList({ bodyshop, loading, contracts, refetch, total, setContractFinderContext }) {
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" }
  });
  const history = useNavigate();
  const search = queryString.parse(useLocation().search);
  const { page } = search;

  const { t } = useTranslation();

  const columns = [
    {
      title: t("contracts.fields.agreementnumber"),
      dataIndex: "agreementnumber",
      key: "agreementnumber",
      sorter: (a, b) => a.agreementnumber - b.agreementnumber,
      sortOrder: state.sortedInfo.columnKey === "agreementnumber" && state.sortedInfo.order,
      render: (text, record) => (
        <Link to={`/manage/courtesycars/contracts/${record.id}`}>{record.agreementnumber || ""}</Link>
      )
    },
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "job.ro_number",
      key: "job.ro_number",
      render: (text, record) => <Link to={`/manage/jobs/${record.job.id}`}>{record.job.ro_number || ""}</Link>
    },
    {
      title: t("contracts.fields.driver"),
      dataIndex: "driver_ln",
      key: "driver_ln",
      sorter: (a, b) => alphaSort(a.driver_ln, b.driver_ln),
      sortOrder: state.sortedInfo.columnKey === "driver_ln" && state.sortedInfo.order,
      render: (text, record) =>
        bodyshop.last_name_first
          ? `${record.driver_ln || ""}, ${record.driver_fn || ""}`
          : `${record.driver_fn || ""} ${record.driver_ln || ""}`
    },
    {
      title: t("contracts.labels.vehicle"),
      dataIndex: "vehicle",
      key: "vehicle",
      //sorter: (a, b) => alphaSort(a.status, b.status),
      //sortOrder:
      // state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      render: (text, record) => (
        <Link to={`/manage/courtesycars/${record.courtesycar.id}`}>{`${
          record.courtesycar.year
        } ${record.courtesycar.make} ${record.courtesycar.model}${
          record.courtesycar.plate ? ` (${record.courtesycar.plate})` : ""
        }${record.courtesycar.fleetnumber ? ` (${record.courtesycar.fleetnumber})` : ""}`}</Link>
      )
    },
    {
      title: t("contracts.fields.status"),
      dataIndex: "status",
      key: "status",
      sorter: (a, b) => alphaSort(a.status, b.status),
      sortOrder: state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      render: (text, record) => t(record.status)
    },
    {
      title: t("contracts.fields.start"),
      dataIndex: "start",
      key: "start",
      sorter: (a, b) => alphaSort(a.start, b.start),
      sortOrder: state.sortedInfo.columnKey === "start" && state.sortedInfo.order,
      render: (text, record) => <DateTimeFormatter>{record.start}</DateTimeFormatter>
    },
    {
      title: t("contracts.fields.scheduledreturn"),
      dataIndex: "scheduledreturn",
      key: "scheduledreturn",
      sorter: (a, b) => alphaSort(a.scheduledreturn, b.scheduledreturn),
      sortOrder: state.sortedInfo.columnKey === "scheduledreturn" && state.sortedInfo.order,
      render: (text, record) => <DateTimeFormatter>{record.scheduledreturn}</DateTimeFormatter>
    },
    {
      title: t("contracts.fields.actualreturn"),
      dataIndex: "actualreturn",
      key: "actualreturn",
      sorter: (a, b) => alphaSort(a.actualreturn, b.actualreturn),
      sortOrder: state.sortedInfo.columnKey === "actualreturn" && state.sortedInfo.order,
      render: (text, record) => <DateTimeFormatter>{record.actualreturn}</DateTimeFormatter>
    },
    {
      title: t("contracts.fields.length"),
      dataIndex: "length",
      key: "length",

      render: (text, record) =>
        (record.actualreturn &&
          record.start &&
          `${dayjs(record.actualreturn).diff(dayjs(record.start), "day", true).toFixed(1)} days`) ||
        ""
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
    search.page = pagination.current;
    search.sortcolumn = sorter.columnKey;
    search.sortorder = sorter.order;
    history({ search: queryString.stringify(search) });
  };

  return (
    <Card
      extra={
        <Space wrap>
          {search.search && (
            <>
              <Typography.Title level={4}>
                {t("general.labels.searchresults", { search: search.search })}
              </Typography.Title>
              <Button
                onClick={() => {
                  delete search.search;
                  history({ search: queryString.stringify(search) });
                }}
              >
                {t("general.actions.clear")}
              </Button>
            </>
          )}
          <Button onClick={() => setContractFinderContext()}>{t("contracts.actions.find")}</Button>
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          <Input.Search
            placeholder={search.searh || t("general.labels.search")}
            onSearch={(value) => {
              search.search = value;
              history({ search: queryString.stringify(search) });
            }}
          />
        </Space>
      }
    >
      <ContractsFindModalContainer />
      <Table
        loading={loading}
        scroll={{
          x: "50%" //y: "40rem"
        }}
        pagination={{
          position: "top",
          pageSize: pageLimit,
          current: parseInt(page || 1),
          total: total
        }}
        columns={columns}
        rowKey="id"
        dataSource={contracts}
        onChange={handleTableChange}
      />
    </Card>
  );
}
