import {
  BranchesOutlined,
  ExclamationCircleFilled,
  PauseCircleOutlined,
} from "@ant-design/icons";
import { Card, 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 ChatOpenButton from "../../chat-open-button/chat-open-button.component";
import OwnerNameDisplay from "../../owner-name-display/owner-name-display.component";
import DashboardRefreshRequired from "../refresh-required.component";
import {pageLimit} from "../../../utils/config";

export default function DashboardScheduledOutToday({ data, ...cardProps }) {
  const { t } = useTranslation();
  const [state, setState] = useState({
    sortedInfo: {},
  });
  if (!data) return null;
  if (!data.scheduled_out_today)
    return <DashboardRefreshRequired {...cardProps} />;

  data.scheduled_out_today.forEach((item) => {
    item.scheduled_completion= dayjs(item.scheduled_completion).format("hh:mm a")
  });
  data.scheduled_out_today.sort(function (a, b) {
    return new Date(a.scheduled_completion) - new Date(b.scheduled_completion);
  });

  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      render: (text, record) => (
        <Link
          to={"/manage/jobs/" + record.jobid}
          onClick={(e) => e.stopPropagation()}
        >
          <Space>
            {record.ro_number || t("general.labels.na")}
            {record.production_vars && record.production_vars.alert ? (
              <ExclamationCircleFilled className="production-alert" />
            ) : null}
            {record.suspended && (
              <PauseCircleOutlined style={{ color: "orangered" }} />
            )}
            {record.iouparent && (
              <Tooltip title={t("jobs.labels.iou")}>
                <BranchesOutlined style={{ color: "orangered" }} />
              </Tooltip>
            )}
          </Space>
        </Link>
      ),
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      ellipsis: true,
      responsive: ["md"],
      render: (text, record) => {
        return record.ownerid ? (
          <Link
            to={"/manage/owners/" + record.ownerid}
            onClick={(e) => e.stopPropagation()}
          >
            <OwnerNameDisplay ownerObject={record} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record} />
          </span>
        );
      },
    },
    {
      title: t("jobs.fields.ownr_ph1"),
      dataIndex: "ownr_ph1",
      key: "ownr_ph1",
      ellipsis: true,
      responsive: ["md"],
      render: (text, record) => (
        <ChatOpenButton phone={record.ownr_ph1} jobid={record.jobid} />
      ),
    },
    {
      title: t("jobs.fields.ownr_ph2"),
      dataIndex: "ownr_ph2",
      key: "ownr_ph2",
      ellipsis: true,
      responsive: ["md"],
      render: (text, record) => (
        <ChatOpenButton phone={record.ownr_ph2} jobid={record.jobid} />
      ),
    },
    {
      title: t("jobs.fields.ownr_ea"),
      dataIndex: "ownr_ea",
      key: "ownr_ea",
      ellipsis: true,
      responsive: ["md"],
      render: (text, record) => (
        <ChatOpenButton phone={record.ownr_ea} jobid={record.jobid} />
      ),
    },
    {
      title: t("jobs.fields.vehicle"),
      dataIndex: "vehicle",
      key: "vehicle",
      ellipsis: true,
      render: (text, record) => {
        return record.vehicleid ? (
          <Link
            to={"/manage/vehicles/" + record.vehicleid}
            onClick={(e) => e.stopPropagation()}
          >
            {`${record.v_model_yr || ""} ${record.v_make_desc || ""} ${
              record.v_model_desc || ""
            }`}
          </Link>
        ) : (
          <span>{`${record.v_model_yr || ""} ${record.v_make_desc || ""} ${
            record.v_model_desc || ""
          }`}</span>
        );
      },
    },
    {
      title: t("jobs.fields.ins_co_nm"),
      dataIndex: "ins_co_nm",
      key: "ins_co_nm",
      ellipsis: true,
      responsive: ["md"],
    },
    {
      title: t("jobs.fields.scheduled_completion"),
      dataIndex: "scheduled_completion",
      key: "scheduled_completion",
      ellipsis: true,
      responsive: ["md"],
    },
    {
      title: t("appointments.fields.alt_transport"),
      dataIndex: "alt_transport",
      key: "alt_transport",
      ellipsis: true,
      responsive: ["md"],
    },
  ];

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

  return (
    <Card
      title={t("dashboard.titles.scheduledouttoday", {
        date: dayjs().startOf("day").format("MM/DD/YYYY"),
      })}
      {...cardProps}
    >
      <div style={{ height: "100%" }}>
        <Table
          onChange={handleTableChange}
          pagination={{ position: "top", defaultPageSize: pageLimit }}
          columns={columns}
          scroll={{ x: true, y: "calc(100% - 2em)" }}
          rowKey="id"
          style={{ height: "85%" }}
          dataSource={data.scheduled_out_today}
        />
      </div>
    </Card>
  );
}

export const DashboardScheduledOutTodayGql = `
  scheduled_out_today: jobs(where: {
    date_invoiced: {_is_null: true}, 
    ro_number: {_is_null: false}, 
    voided: {_eq: false}, 
    scheduled_completion: {_gte: "${dayjs().startOf("day").toISOString()}", 
    _lte: "${dayjs().endOf("day").toISOString()}"}}) {
      alt_transport
      clm_no
      jobid: id
      ins_co_nm
      iouparent
      ownerid
      ownr_co_nm
      ownr_ea
      ownr_fn
      ownr_ln
      ownr_ph1
      ownr_ph2
      production_vars
      ro_number
      scheduled_completion
      suspended
      v_make_desc
      v_model_desc
      v_model_yr
      v_vin
      vehicleid

  }
`;
