import { SyncOutlined } from "@ant-design/icons";
import { Button, Checkbox, Divider, Input, Space } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import dayjs from "../../utils/day";
import PhoneFormatter from "../../utils/PhoneFormatter";
import FormDateTimePickerComponent from "../form-date-time-picker/form-date-time-picker.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";

export default function JobsFindModalComponent({
  selectedJob,
  setSelectedJob,
  jobsList,
  jobsListLoading,
  importOptionsState,
  modalSearchState,
  jobsListRefetch,
  partsQueueToggle,
  setPartsQueueToggle,
  updateSchComp,
  setSchComp
}) {
  const { t } = useTranslation();
  const [modalSearch, setModalSearch] = modalSearchState;
  const [importOptions, setImportOptions] = importOptionsState;
  const [checkUTT, setCheckUTT] = useState(false);
  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      width: "8%",
      render: (text, record) => (
        <span>
          <Link to={"/manage/jobs/" + record.id}>{record.ro_number || t("general.labels.na")}</Link>
        </span>
      )
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      ellipsis: true,

      width: "25%",

      render: (text, record) => {
        return record.owner ? (
          <Link to={"/manage/owners/" + record.owner.id}>
            <OwnerNameDisplay ownerObject={record} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record} />
          </span>
        );
      }
    },
    {
      title: t("jobs.fields.ownr_ph1"),
      dataIndex: "ownr_ph1",
      key: "ownr_ph1",
      width: "12%",
      ellipsis: true,
      render: (text, record) => {
        return record.ownr_ph1 ? (
          <PhoneFormatter type={record.ownr_ph1_ty}>{record.ownr_ph1}</PhoneFormatter>
        ) : (
          t("general.labels.unknown")
        );
      }
    },
    {
      title: t("jobs.fields.ownr_ph2"),
      dataIndex: "ownr_ph2",
      key: "ownr_ph2",
      width: "12%",
      ellipsis: true,
      render: (text, record) => {
        return record.ownr_ph2 ? (
          <PhoneFormatter type={record.ownr_ph2_ty}>{record.ownr_ph2}</PhoneFormatter>
        ) : (
          t("general.labels.unknown")
        );
      }
    },
    {
      title: t("jobs.fields.status"),
      dataIndex: "status",
      key: "status",
      width: "10%",
      ellipsis: true,
      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) => (
        <Link to={"/manage/vehicles/" + record.vehicleid}>
          {`${record.v_model_yr || ""} ${record.v_make_desc || ""} ${record.v_model_desc || ""}`}
        </Link>
      )
    },
    {
      title: t("vehicles.fields.plate_no"),
      dataIndex: "plate_no",
      key: "plate_no",
      width: "8%",
      ellipsis: true,
      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,
      render: (text, record) => {
        return record.clm_no ? <span>{record.clm_no}</span> : t("general.labels.unknown");
      }
    }
  ];

  const handleOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        setSelectedJob(record.id);
        if (record.actual_in && record.scheduled_completion) {
          setSchComp({
            ...updateSchComp,
            actual_in: record.actual_in,
            scheduled_completion: record.scheduled_completion
          });
        } else {
          if (record.actual_in && !record.scheduled_completion) {
            setSchComp({
              ...updateSchComp,
              actual_in: record.actual_in,
              scheduled_completion: dayjs()
            });
          }
          if (!record.actual_in && record.scheduled_completion) {
            setSchComp({
              ...updateSchComp,
              actual_in: dayjs(),
              scheduled_completion: dayjs(record.scheduled_completion)
            });
          }
          if (!record.actual_in && !record.scheduled_completion) {
            setSchComp({
              ...updateSchComp,
              actual_in: dayjs(),
              scheduled_completion: dayjs()
            });
          }
        }
        return;
      }
    }
    setSelectedJob(null);
  };

  return (
    <div>
      <ResponsiveTable
        title={() => (
          <div style={{ display: "flex" }}>
            {t("jobs.labels.existing_jobs")}
            <Button
              onClick={() => {
                jobsListRefetch();
              }}
              icon={<SyncOutlined />}
            />
            <Input
              value={modalSearch}
              onChange={(e) => {
                setModalSearch(e.target.value);
              }}
            />
          </div>
        )}
        pagination={{ placement: "bottom" }}
        columns={columns}
        mobileColumnKeys={["ro_number", "owner", "status", "vehicle"]}
        rowKey="id"
        loading={jobsListLoading}
        dataSource={jobsList}
        rowSelection={{
          onSelect: (props) => {
            setSelectedJob(props.id);
            if (props.actual_in && props.scheduled_completion) {
              setSchComp({
                ...updateSchComp,
                actual_in: props.actual_in,
                scheduled_completion: props.scheduled_completion
              });
            } else {
              if (props.actual_in && !props.scheduled_completion) {
                setSchComp({
                  ...updateSchComp,
                  actual_in: props.actual_in,
                  scheduled_completion: dayjs()
                });
              }
              if (!props.actual_in && props.scheduled_completion) {
                setSchComp({
                  ...updateSchComp,
                  actual_in: dayjs(),
                  scheduled_completion: dayjs(props.scheduled_completion)
                });
              }
              if (!props.actual_in && !props.scheduled_completion) {
                setSchComp({
                  ...updateSchComp,
                  actual_in: dayjs(),
                  scheduled_completion: dayjs()
                });
              }
            }
          },
          type: "radio",
          selectedRowKeys: [selectedJob]
        }}
        onRow={(record) => {
          return {
            onClick: () => {
              handleOnRowClick(record);
            }
          };
        }}
      />
      <Divider />
      <Space>
        <Checkbox
          defaultChecked={importOptions.overrideHeader}
          onChange={(e) =>
            setImportOptions({
              ...importOptions,
              overrideHeaders: e.target.checked
            })
          }
          id="override_header"
        >
          {t("jobs.labels.override_header")}
        </Checkbox>
        <Checkbox
          checked={partsQueueToggle}
          onChange={(e) => setPartsQueueToggle(e.target.checked)}
          id="parts_queue_toggle"
        >
          {t("bodyshop.fields.md_functionality_toggles.parts_queue_toggle")}
        </Checkbox>
        <Checkbox
          checked={updateSchComp.checked}
          onChange={(e) => setSchComp({ ...updateSchComp, checked: e.target.checked })}
          id="update_scheduled_completion"
        >
          {t("jobs.labels.update_scheduled_completion")}
        </Checkbox>
        {updateSchComp.checked === true ? (
          <>
            {checkUTT === false ? (
              <FormDateTimePickerComponent
                value={updateSchComp.scheduled_completion}
                onChange={(e) => {
                  setSchComp({ ...updateSchComp, scheduled_completion: e });
                }}
                id="scheduled_completion_date_time_picker"
              />
            ) : null}
            <Checkbox
              checked={checkUTT}
              onChange={(e) => {
                setCheckUTT(e.target.checked);
                setSchComp({
                  ...updateSchComp,
                  scheduled_completion: null,
                  automatic: true
                });
              }}
              id="calculate_scheduled_completion"
            >
              {t("jobs.labels.calc_scheuled_completion")}
            </Checkbox>
          </>
        ) : null}
      </Space>
    </div>
  );
}
