import { LoadingOutlined } from "@ant-design/icons";
import { useLazyQuery } from "@apollo/client/react";
import { Select, Space, Spin, Tag } from "antd";
import _ from "lodash";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { SEARCH_JOBS_BY_ID_FOR_AUTOCOMPLETE, SEARCH_JOBS_FOR_AUTOCOMPLETE } from "../../graphql/jobs.queries";
import AlertComponent from "../alert/alert.component";
import { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";

const JobSearchSelect = ({
  disabled,
  convertedOnly = false,
  notInvoiced = false,
  notExported = true,
  clm_no = false,
  ref,
  ...restProps
}) => {
  const { t } = useTranslation();
  const [theOptions, setTheOptions] = useState([]);

  const [callSearch, { loading, error, data }] = useLazyQuery(SEARCH_JOBS_FOR_AUTOCOMPLETE);
  const [callIdSearch, { loading: idLoading, error: idError, data: idData }] = useLazyQuery(
    SEARCH_JOBS_BY_ID_FOR_AUTOCOMPLETE
  );

  const debouncedExecuteSearch = useMemo(() => {
    return _.debounce((value) => {
      if (value == null || value === "" || value.length < 2) return;

      const variables = {
        search: value,
        ...(convertedOnly || notExported
          ? {
              ...(convertedOnly ? { isConverted: true } : {}),
              ...(notExported ? { notExported: true } : {}),
              ...(notInvoiced ? { notInvoiced: true } : {})
            }
          : {})
      };

      callSearch({ variables });
    }, 500);
  }, [callSearch, convertedOnly, notExported, notInvoiced]);

  useEffect(() => {
    return () => {
      debouncedExecuteSearch.cancel();
    };
  }, [debouncedExecuteSearch]);

  const handleSearch = (value) => {
    debouncedExecuteSearch(value);
  };

  useEffect(() => {
    // Keep OLD "truthy" semantics (only fetch by id when value is truthy)
    if (restProps.value) {
      callIdSearch({ variables: { id: restProps.value } });
    }
  }, [restProps.value, callIdSearch]);

  useEffect(() => {
    setTheOptions(
      _.uniqBy(
        [...(idData?.jobs_by_pk ? [idData.jobs_by_pk] : []), ...(data?.search_jobs ? data.search_jobs : [])],
        "id"
      )
    );
  }, [data, idData]);

  return (
    <div>
      <Select
        {...restProps}
        ref={ref}
        disabled={disabled}
        showSearch={{
          filterOption: false,
          onSearch: handleSearch
        }}
        autoFocus
        allowClear={!loading} // matches OLD
        style={{ width: "100%" }}
        suffixIcon={(loading || idLoading) && <Spin />} // matches OLD spinner semantics
        notFoundContent={loading ? <LoadingOutlined /> : null} // matches OLD (loading only)
        options={theOptions?.map((o) => ({
          key: o.id,
          value: o.id,
          status: o.status,
          label: (
            <Space align="center">
              <span>
                {`${clm_no && o.clm_no ? `${o.clm_no} | ` : ""}${o.ro_number || t("general.labels.na")} | ${OwnerNameDisplayFunction(
                  o
                )} | ${o.v_model_yr || ""} ${o.v_make_desc || ""} ${o.v_model_desc || ""}`}
              </span>
              <Tag>
                <strong>{o.status}</strong>
              </Tag>
            </Space>
          )
        }))}
      />

      {error ? <AlertComponent title={error.message} type="error" /> : null}
      {idError ? <AlertComponent title={idError.message} type="error" /> : null}
    </div>
  );
};

export default JobSearchSelect;
