import { useLazyQuery } from "@apollo/client/react";
import { AutoComplete, Divider, Input, Space } from "antd";
import _ from "lodash";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import { GLOBAL_SEARCH_QUERY } from "../../graphql/search.queries";
import PhoneNumberFormatter from "../../utils/PhoneFormatter";
import AlertComponent from "../alert/alert.component";
import OwnerNameDisplay, { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";
import VehicleVinDisplay from "../vehicle-vin-display/vehicle-vin-display.component";

export default function GlobalSearch() {
  const { t } = useTranslation();
  const [callSearch, { loading, error, data }] = useLazyQuery(GLOBAL_SEARCH_QUERY);
  const navigate = useNavigate();

  const executeSearch = (variables) => {
    if (variables?.search !== "" && variables?.search?.length >= 3)
      callSearch({
        variables
      });
  };
  const debouncedExecuteSearch = _.debounce(executeSearch, 750);

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

  const renderTitle = (title) => {
    return <span>{title}</span>;
  };

  const options = data
    ? [
        {
          label: renderTitle(t("menus.header.search.jobs")),
          options: data.search_jobs.map((job) => {
            return {
              key: job.id,
              value: job.ro_number || "N/A",
              label: (
                <Link to={`/manage/jobs/${job.id}`}>
                  <Space size="small" separator={<Divider orientation="vertical" />}>
                    <strong>{job.ro_number || t("general.labels.na")}</strong>
                    <span>{`${job.status || ""}`}</span>
                    <span>
                      <OwnerNameDisplay ownerObject={job} />
                    </span>
                    <span>{`${job.v_model_yr || ""} ${job.v_make_desc || ""} ${job.v_model_desc || ""}`}</span>
                    <span>{`${job.clm_no || ""}`}</span>
                  </Space>
                </Link>
              )
            };
          })
        },
        {
          label: renderTitle(t("menus.header.search.owners")),
          options: data.search_owners.map((owner) => {
            return {
              key: owner.id,
              value: OwnerNameDisplayFunction(owner),
              label: (
                <Link to={`/manage/owners/${owner.id}`}>
                  <Space size="small" separator={<Divider orientation="vertical" />} wrap>
                    <span>
                      <OwnerNameDisplay ownerObject={owner} />
                    </span>
                    <PhoneNumberFormatter type={owner.ownr_ph1_ty}>{owner.ownr_ph1}</PhoneNumberFormatter>
                    <PhoneNumberFormatter type={owner.ownr_ph2_ty}>{owner.ownr_ph2}</PhoneNumberFormatter>
                  </Space>
                </Link>
              )
            };
          })
        },
        {
          label: renderTitle(t("menus.header.search.vehicles")),
          options: data.search_vehicles.map((vehicle) => {
            return {
              key: vehicle.id,
              value: `${vehicle.v_model_yr || ""} ${vehicle.v_make_desc || ""} ${vehicle.v_model_desc || ""}`,
              label: (
                <Link to={`/manage/vehicles/${vehicle.id}`}>
                  <Space size="small" separator={<Divider orientation="vertical" />}>
                    <span>
                      {`${vehicle.v_model_yr || ""} ${vehicle.v_make_desc || ""} ${vehicle.v_model_desc || ""}`}
                    </span>
                    <span>{vehicle.plate_no || ""}</span>
                    <span>
                      <VehicleVinDisplay>{vehicle.v_vin || ""}</VehicleVinDisplay>
                    </span>
                  </Space>
                </Link>
              )
            };
          })
        },
        {
          label: renderTitle(t("menus.header.search.payments")),
          options: data.search_payments.map((payment) => {
            return {
              key: payment.id,
              value: `${payment.job.ro_number} ${payment.payer} ${payment.amount}`,
              label: (
                <Link to={`/manage/jobs/${payment.job.id}`}>
                  <Space size="small" separator={<Divider orientation="vertical" />}>
                    <span>{payment.paymentnum}</span>
                    <span>{payment.job.ro_number}</span>
                    <span>{payment.memo || ""}</span>
                    <span>{payment.amount || ""}</span>
                    <span>{payment.transactionid || ""}</span>
                  </Space>
                </Link>
              )
            };
          })
        },
        {
          label: renderTitle(t("menus.header.search.bills")),
          options: data.search_bills.map((bill) => {
            return {
              key: bill.id,
              value: `${bill.invoice_number} - ${bill.vendor.name}`,
              label: (
                <Link to={`/manage/bills?billid=${bill.id}`}>
                  <Space size="small" separator={<Divider orientation="vertical" />}>
                    <span>{bill.invoice_number}</span>
                    <span>{bill.vendor.name}</span>
                    <span>{bill.date}</span>
                  </Space>
                </Link>
              )
            };
          })
        },
        {
          label: renderTitle(t("menus.header.search.phonebook")),
          options: data.search_phonebook.map((pb) => {
            return {
              key: pb.id,
              value: `${pb.firstname || ""} ${pb.lastname || ""} ${pb.company || ""}`,
              label: (
                <Link to={`/manage/phonebook?phonebookentry=${pb.id}`}>
                  <Space size="small" separator={<Divider orientation="vertical" />}>
                    <span>{`${pb.firstname || ""} ${pb.lastname || ""} ${pb.company || ""}`}</span>
                    <PhoneNumberFormatter>{pb.phone1}</PhoneNumberFormatter>
                    <span>{pb.email}</span>
                  </Space>
                </Link>
              )
            };
          })
        }
      ]
    : [];

  if (error) return <AlertComponent title={error.message} type="error" />;

  return (
    <AutoComplete
      options={options}
      showSearch={{
        onSearch: handleSearch,
        filterOption: false
      }}
      defaultActiveFirstOption
      onKeyDown={(e) => {
        if (e.key !== "Enter") return;
        const firstUrlForSearch = options?.[0]?.options?.[0]?.label?.props?.to;
        if (!firstUrlForSearch) return;
        navigate(firstUrlForSearch);
      }}
    >
      <Input.Search
        className="global-search-autocomplete-fix"
        size="large"
        placeholder={t("general.labels.globalsearch")}
        enterButton
        allowClear
        loading={loading}
      />
    </AutoComplete>
  );
}
