import { SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Typography } from "antd";
import queryString from "query-string";
import { 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";
import ResponsiveTable from "../responsive-table/responsive-table.component";

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 });
    const updatedSearch = {
      ...search,
      page: pagination.current,
      sortcolumn: sorter.columnKey,
      sortorder: sorter.order
    };
    history({ search: queryString.stringify(updatedSearch) });
  };

  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()} icon={<SyncOutlined />} />

          <Input.Search
            placeholder={search.searh || t("general.labels.search")}
            onSearch={(value) => {
              const updatedSearch = { ...search, search: value };
              history({ search: queryString.stringify(updatedSearch) });
            }}
            enterButton
          />
        </Space>
      }
    >
      <ContractsFindModalContainer />
      <ResponsiveTable
        loading={loading}
        scroll={{
          x: "50%" //y: "40rem"
        }}
        pagination={{ placement: "top", pageSize: pageLimit, current: parseInt(page || 1, 10), total: total }}
        columns={columns}
        mobileColumnKeys={["agreementnumber", "driver_ln", "status", "scheduledreturn"]}
        rowKey="id"
        dataSource={contracts}
        onChange={handleTableChange}
      />
    </Card>
  );
}
