import { SyncOutlined, WarningFilled } from "@ant-design/icons";
import {
  Button,
  Card,
  Dropdown,
  Input,
  Menu,
  Space,
  Table,
  Tooltip,
} from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { alphaSort } from "../../utils/sorters";
import { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";
import moment from "moment";
import { GenerateDocument } from "../../utils/RenderTemplate";
import { TemplateList } from "../../utils/TemplateConstants";
export default function CourtesyCarsList({ loading, courtesycars, refetch }) {
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" },
  });
  const [searchText, setSearchText] = useState("");
  const { t } = useTranslation();

  const columns = [
    {
      title: t("courtesycars.fields.fleetnumber"),
      dataIndex: "fleetnumber",
      key: "fleetnumber",
      sorter: (a, b) => alphaSort(a.fleetnumber, b.fleetnumber),
      sortOrder:
        state.sortedInfo.columnKey === "fleetnumber" && state.sortedInfo.order,
    },
    {
      title: t("courtesycars.fields.vin"),
      dataIndex: "vin",
      key: "vin",
      sorter: (a, b) => alphaSort(a.vin, b.vin),
      sortOrder: state.sortedInfo.columnKey === "vin" && state.sortedInfo.order,
      render: (text, record) => (
        <Link to={`/manage/courtesycars/${record.id}`}>{record.vin}</Link>
      ),
    },
    {
      title: t("courtesycars.fields.status"),
      dataIndex: "status",
      key: "status",
      sorter: (a, b) => alphaSort(a.status, b.status),
      filters: [
        {
          text: t("courtesycars.status.in"),
          value: "courtesycars.status.in",
        },
        {
          text: t("courtesycars.status.out"),
          value: "courtesycars.status.out",
        },
        {
          text: t("courtesycars.status.sold"),
          value: "courtesycars.status.sold",
        },
        {
          text: t("courtesycars.status.leasereturn"),
          value: "courtesycars.status.leasereturn",
        },
      ],
      onFilter: (value, record) => value.includes(record.status),
      sortOrder:
        state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      render: (text, record) => {
        const { nextservicedate, nextservicekm, mileage } = record;

        const mileageOver = nextservicekm <= mileage;

        const dueForService =
          nextservicedate && moment(nextservicedate).isBefore(moment());

        return (
          <Space>
            {t(record.status)}
            {(mileageOver || dueForService) && (
              <Tooltip title={t("contracts.labels.cardueforservice")}>
                <WarningFilled style={{ color: "tomato" }} />
              </Tooltip>
            )}
          </Space>
        );
      },
    },
    {
      title: t("courtesycars.fields.year"),
      dataIndex: "year",
      key: "year",
      sorter: (a, b) => alphaSort(a.year, b.year),
      sortOrder:
        state.sortedInfo.columnKey === "year" && state.sortedInfo.order,
    },
    {
      title: t("courtesycars.fields.make"),
      dataIndex: "make",
      key: "make",
      sorter: (a, b) => alphaSort(a.make, b.make),
      sortOrder:
        state.sortedInfo.columnKey === "make" && state.sortedInfo.order,
    },
    {
      title: t("courtesycars.fields.model"),
      dataIndex: "model",
      key: "model",
      sorter: (a, b) => alphaSort(a.model, b.model),
      sortOrder:
        state.sortedInfo.columnKey === "model" && state.sortedInfo.order,
    },
    {
      title: t("courtesycars.fields.plate"),
      dataIndex: "plate",
      key: "plate",
      sorter: (a, b) => alphaSort(a.plate, b.plate),
      sortOrder:
        state.sortedInfo.columnKey === "plate" && state.sortedInfo.order,
    },
    {
      title: t("courtesycars.labels.outwith"),
      dataIndex: "outwith",
      key: "outwith",
      // sorter: (a, b) => alphaSort(a.model, b.model),
      sortOrder:
        state.sortedInfo.columnKey === "model" && state.sortedInfo.order,
      render: (text, record) =>
        record.cccontracts.length === 1 ? (
          <Link to={`/manage/jobs/${record.cccontracts[0].job.id}`}>
            {`${
              record.cccontracts[0].job.ro_number
            } - ${OwnerNameDisplayFunction(record.cccontracts[0].job)}`}
          </Link>
        ) : null,
    },
    {
      title: t("contracts.fields.scheduledreturn"),
      dataIndex: "scheduledreturn",
      key: "scheduledreturn",
      render: (text, record) =>
        record.cccontracts.length === 1 && (
          <DateTimeFormatter>
            {record.cccontracts[0].scheduledreturn}
          </DateTimeFormatter>
        ),
    },
  ];

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

  const tableData = searchText
    ? courtesycars.filter(
        (c) =>
          (c.fleetnumber || "")
            .toLowerCase()
            .includes(searchText.toLowerCase()) ||
          (c.vin || "").toLowerCase().includes(searchText.toLowerCase()) ||
          (c.year || "").toLowerCase().includes(searchText.toLowerCase()) ||
          (c.make || "").toLowerCase().includes(searchText.toLowerCase()) ||
          (c.model || "").toLowerCase().includes(searchText.toLowerCase()) ||
          (t(c.status) || "").toLowerCase().includes(searchText.toLowerCase())
      )
    : courtesycars;
  return (
    <Card
      title={t("menus.header.courtesycars")}
      extra={
        <Space wrap>
          <Button onClick={() => refetch()}>
            <SyncOutlined />
          </Button>
          <Dropdown
            trigger="click"
            overlay={
              <Menu>
                <Menu.Item
                  onClick={() =>
                    GenerateDocument(
                      {
                        name: TemplateList("courtesycar").courtesy_car_inventory
                          .key,
                        variables: {
                          //id: contract.id
                        },
                      },
                      {},
                      "p"
                    )
                  }
                >
                  {t("printcenter.courtesycarcontract.courtesy_car_inventory")}
                </Menu.Item>
              </Menu>
            }
          >
            <Button>{t("general.labels.print")}</Button>
          </Dropdown>
          <Link to={`/manage/courtesycars/new`}>
            <Button>{t("courtesycars.actions.new")}</Button>
          </Link>
          <Input.Search
            className="imex-table-header__search"
            placeholder={t("general.labels.search")}
            onChange={(e) => {
              setSearchText(e.target.value);
            }}
            value={searchText}
            enterButton
          />
        </Space>
      }
    >
      <Table
        loading={loading}
        pagination={{ position: "top" }}
        columns={columns}
        rowKey="id"
        dataSource={tableData}
        onChange={handleTableChange}
      />
    </Card>
  );
}
