import { SyncOutlined, WarningFilled } from "@ant-design/icons";
import { Button, Card, Dropdown, Input, Space, Tooltip } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import dayjs from "../../utils/day";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { GenerateDocument } from "../../utils/RenderTemplate";
import { TemplateList } from "../../utils/TemplateConstants";
import { alphaSort } from "../../utils/sorters";
import useLocalStorage from "../../utils/useLocalStorage";
import { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function CourtesyCarsList({ loading, courtesycars, refetch }) {
  const [state, setState] = useState({
    sortedInfo: {}
  });
  const [searchText, setSearchText] = useState("");
  const [filter, setFilter] = useLocalStorage("filter_courtesy_cars_list", null);
  const { t } = useTranslation();
  const notification = useNotification();

  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),
      filteredValue: filter?.status || null,
      filters: [
        {
          text: t("courtesycars.status.in"),
          value: "courtesycars.status.in"
        },
        {
          text: t("courtesycars.status.inservice"),
          value: "courtesycars.status.inservice"
        },
        {
          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"
        },
        {
          text: t("courtesycars.status.unavailable"),
          value: "courtesycars.status.unavailable"
        }
      ],
      onFilter: (value, record) => record.status === value,
      sortOrder: state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      render: (text, record) => {
        const { nextservicedate, nextservicekm, mileage, insuranceexpires } = record;

        const mileageOver = nextservicekm ? nextservicekm <= mileage : false;

        const dueForService = nextservicedate && dayjs(nextservicedate).endOf("day").isSameOrBefore(dayjs());

        const insuranceOver = insuranceexpires && dayjs(insuranceexpires).endOf("day").isBefore(dayjs());

        return (
          <Space>
            {t(record.status)}
            {(mileageOver || dueForService || insuranceOver) && (
              <Tooltip
                title={
                  (mileageOver || dueForService) && insuranceOver
                    ? t("contracts.labels.insuranceexpired") + " / " + t("contracts.labels.cardueforservice")
                    : insuranceOver
                      ? t("contracts.labels.insuranceexpired")
                      : t("contracts.labels.cardueforservice")
                }
              >
                <WarningFilled style={{ color: "tomato" }} />
              </Tooltip>
            )}
          </Space>
        );
      }
    },
    {
      title: t("courtesycars.fields.readiness"),
      dataIndex: "readiness",
      key: "readiness",
      sorter: (a, b) => alphaSort(a.readiness, b.readiness),
      filteredValue: filter?.readiness || null,
      filters: [
        {
          text: t("courtesycars.readiness.ready"),
          value: "courtesycars.readiness.ready"
        },
        {
          text: t("courtesycars.readiness.notready"),
          value: "courtesycars.readiness.notready"
        }
      ],
      onFilter: (value, record) => value.includes(record.readiness),
      sortOrder: state.sortedInfo.columnKey === "readiness" && state.sortedInfo.order,
      render: (text, record) => t(record.readiness)
    },
    {
      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.color"),
      dataIndex: "color",
      key: "color",
      sorter: (a, b) => alphaSort(a.color, b.color),
      sortOrder: state.sortedInfo.columnKey === "color" && 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.fields.fuel"),
      dataIndex: "fuel",
      key: "fuel",
      sorter: (a, b) => a.fuel - b.fuel,
      sortOrder: state.sortedInfo.columnKey === "fuel" && state.sortedInfo.order,
      render: (text, record) => {
        switch (record.fuel) {
          case 100:
            return t("courtesycars.labels.fuel.full");
          case 88:
            return t("courtesycars.labels.fuel.78");
          case 75:
            return t("courtesycars.labels.fuel.34");
          case 63:
            return t("courtesycars.labels.fuel.58");
          case 50:
            return t("courtesycars.labels.fuel.12");
          case 38:
            return t("courtesycars.labels.fuel.38");
          case 25:
            return t("courtesycars.labels.fuel.14");
          case 13:
            return t("courtesycars.labels.fuel.18");
          case 0:
            return t("courtesycars.labels.fuel.empty");
          default:
            return record.fuel;
        }
      }
    },
    {
      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, sortedInfo: sorter });
    setFilter(filters);
  };

  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()) ||
          (c.plate || "").toLowerCase().includes(searchText.toLowerCase()) ||
          (t(c.status) || "").toLowerCase().includes(searchText.toLowerCase())
      )
    : courtesycars;

  const items = [
    {
      key: "courtesycar_inventory",
      label: t("printcenter.courtesycarcontract.courtesy_car_inventory"),
      onClick: () =>
        GenerateDocument(
          {
            name: TemplateList("courtesycar").courtesy_car_inventory.key,
            variables: {
              //id: contract.id
            }
          },
          {},
          "p",
          null,
          notification
        )
    }
  ];

  const menu = { items };

  return (
    <Card
      title={t("menus.header.courtesycars")}
      extra={
        <Space wrap>
          <Button onClick={() => refetch()} icon={<SyncOutlined />} />

          <Dropdown trigger="click" menu={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>
      }
    >
      <ResponsiveTable
        loading={loading}
        pagination={{ placement: "top" }}
        columns={columns}
        mobileColumnKeys={["status", "fleetnumber", "vin", "readiness"]}
        rowKey="id"
        dataSource={tableData}
        onChange={handleTableChange}
      />
    </Card>
  );
}
