import {SyncOutlined, WarningFilled} from "@ant-design/icons";
import {Button, Card, Dropdown, Input, Space, Table, Tooltip,} from "antd";
import dayjs from "../../utils/day";
import React, {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 {OwnerNameDisplayFunction} from "../owner-name-display/owner-name-display.component";

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 ? nextservicekm <= mileage : false;

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

                return (
                    <Space>
                        {t(record.status)}
                        {(mileageOver || dueForService) && (
                            <Tooltip title={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),
            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) => alphaSort(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 63:
                        return t("courtesycars.labels.fuel.58");
                    case 50:
                        return t("courtesycars.labels.fuel.12");
                    case 38:
                        return t("courtesycars.labels.fuel.34");
                    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, 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()) ||
                (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"
                ),
        },
    ];

    const menu = {items};

    return (
        <Card
            title={t("menus.header.courtesycars")}
            extra={
                <Space wrap>
                    <Button onClick={() => refetch()}>
                        <SyncOutlined/>
                    </Button>
                    <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>
            }
        >
            <Table
                loading={loading}
                pagination={{position: "top"}}
                columns={columns}
                rowKey="id"
                dataSource={tableData}
                onChange={handleTableChange}
            />
        </Card>
    );
}
