import { Card, Input, Table } from "antd";
import React, { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { alphaSort } from "../../utils/sorters";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import { pageLimit } from "../../utils/config";

export default function ContractsJobsComponent({ loading, data, selectedJob, handleSelect }) {
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" },
    search: ""
  });

  const { t } = useTranslation();

  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      width: "8%",
      sorter: (a, b) => alphaSort(a.ro_number, b.ro_number),
      sortOrder: state.sortedInfo.columnKey === "ro_number" && state.sortedInfo.order,

      render: (text, record) => <span>{record.ro_number ? record.ro_number : t("general.labels.na")}</span>
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
      width: "25%",
      sortOrder: state.sortedInfo.columnKey === "owner" && state.sortedInfo.order,
      render: (text, record) => <OwnerNameDisplay ownerObject={record} />
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",
      width: "10%",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.status, b.status),
      sortOrder: state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      render: (text, record) => {
        return record.status || t("general.labels.na");
      }
    },

    {
      title: t("jobs.fields.vehicle"),
      dataIndex: "vehicle",
      key: "vehicle",
      width: "15%",
      ellipsis: true,
      render: (text, record) => {
        return record.vehicleid ? (
          <span>{`${record.v_model_yr || ""} ${record.v_make_desc || ""} ${record.v_model_desc || ""}`}</span>
        ) : (
          t("jobs.errors.novehicle")
        );
      }
    },
    {
      title: t("vehicles.fields.plate_no"),
      dataIndex: "plate_no",
      key: "plate_no",
      width: "8%",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.plate_no, b.plate_no),
      sortOrder: state.sortedInfo.columnKey === "plate_no" && state.sortedInfo.order,
      render: (text, record) => {
        return record.plate_no ? <span>{record.plate_no}</span> : t("general.labels.unknown");
      }
    },
    {
      title: t("jobs.fields.clm_no"),
      dataIndex: "clm_no",
      key: "clm_no",
      width: "12%",
      ellipsis: true,
      sorter: (a, b) => alphaSort(a.clm_no, b.clm_no),
      sortOrder: state.sortedInfo.columnKey === "clm_no" && state.sortedInfo.order,
      render: (text, record) => {
        return record.clm_no ? <span>{record.clm_no}</span> : t("general.labels.unknown");
      }
    }
  ];

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

  const filteredData =
    state.search === ""
      ? data
      : data.filter(
          (j) =>
            (j.ro_number || "").toString().toLowerCase().includes(state.search.toLowerCase()) ||
            (j.ownr_co_nm || "").toLowerCase().includes(state.search.toLowerCase()) ||
            (j.ownr_fn || "").toLowerCase().includes(state.search.toLowerCase()) ||
            (j.ownr_ln || "").toLowerCase().includes(state.search.toLowerCase()) ||
            (j.clm_no || "").toLowerCase().includes(state.search.toLowerCase()) ||
            (j.v_make_desc || "").toLowerCase().includes(state.search.toLowerCase()) ||
            (j.v_model_desc || "").toLowerCase().includes(state.search.toLowerCase()) ||
            (j.plate_no || "").toLowerCase().includes(state.search.toLowerCase())
        );

  const defaultCurrent = useMemo(() => {
    const page = Math.floor((filteredData.findIndex((v) => v.id === selectedJob) || 0) / 10) + 1;
    if (page === 0) return 1;
    return page;
  }, [filteredData, selectedJob]);

  if (loading) return <LoadingSkeleton />;
  return (
    <Card
      title={t("jobs.labels.availablejobs")}
      extra={
        <Input.Search
          placeholder={t("general.labels.search")}
          value={state.search}
          onChange={(e) => setState({ ...state, search: e.target.value })}
        />
      }
    >
      <Table
        loading={loading}
        pagination={{
          position: "top",
          defaultPageSize: pageLimit,
          defaultCurrent: defaultCurrent
        }}
        columns={columns}
        rowKey="id"
        dataSource={filteredData}
        onChange={handleTableChange}
        rowSelection={{
          onSelect: handleSelect,
          type: "radio",
          selectedRowKeys: [selectedJob]
        }}
        onRow={(record, rowIndex) => {
          return {
            onClick: (event) => {
              handleSelect(record);
            }
          };
        }}
      />
    </Card>
  );
}
