import { useLazyQuery } from "@apollo/client";
import { AutoComplete, Divider, Space } from "antd";
import _ from "lodash";
import React from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { GLOBAL_SEARCH_QUERY } from "../../graphql/search.queries";
import PhoneNumberFormatter from "../../utils/PhoneFormatter";
import AlertComponent from "../alert/alert.component";

export default function GlobalSearch() {
  const { t } = useTranslation();

  const [callSearch, { error, data }] = useLazyQuery(GLOBAL_SEARCH_QUERY);

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

  const handleSearch = (value) => {
    debouncedExecuteSearch({ variables: { 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,
              label: (
                <Link to={`/manage/jobs/${job.id}`}>
                  <Space size="small" split={<Divider type="vertical" />}>
                    <strong>{job.ro_number || t("general.labels.na")}</strong>
                    <span>{`${job.ownr_fn || ""} ${job.ownr_ln || ""} ${
                      job.ownr_co_nm || ""
                    }`}</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: `${owner.ownr_fn || ""} ${owner.ownr_ln || ""} ${
                owner.ownr_co_nm || ""
              }`,
              label: (
                <Link to={`/manage/owners/${owner.id}`}>
                  <Space size="small" split={<Divider type="vertical" />} wrap>
                    <span>{`${owner.ownr_fn || ""} ${owner.ownr_ln || ""} ${
                      owner.ownr_co_nm || ""
                    }`}</span>
                    <PhoneNumberFormatter>
                      {owner.ownr_ph1}
                    </PhoneNumberFormatter>
                    <PhoneNumberFormatter>
                      {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" split={<Divider type="vertical" />}>
                    <span>
                      {`${vehicle.v_model_yr || ""} ${
                        vehicle.v_make_desc || ""
                      } ${vehicle.v_model_desc || ""}`}
                    </span>
                    <span>{vehicle.plate_no || ""}</span>
                    <span> {vehicle.v_vin || ""}</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" split={<Divider type="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" split={<Divider type="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" split={<Divider type="vertical" />}>
                    <span>{`${pb.firstname || ""} ${pb.lastname || ""} ${
                      pb.company || ""
                    }`}</span>
                    <PhoneNumberFormatter>{pb.phone1}</PhoneNumberFormatter>
                    <span>{pb.email}</span>
                  </Space>
                </Link>
              ),
            };
          }),
        },
      ]
    : [];

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

  return (
    <AutoComplete
      options={options}
      onSearch={handleSearch}
      placeholder={t("general.labels.globalsearch")}
      allowClear
    ></AutoComplete>
  );
}
