import { AutoComplete, Divider, Input, Space } from "antd";
import axios from "axios";
import _ from "lodash";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import PhoneNumberFormatter from "../../utils/PhoneFormatter";
import OwnerNameDisplay, { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";
import VehicleVinDisplay from "../vehicle-vin-display/vehicle-vin-display.component";
import { logImEXEvent } from "../../firebase/firebase.utils";

export default function GlobalSearchOs() {
  const { t } = useTranslation();
  const navigate = useNavigate();

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(false);

  const executeSearch = async (v) => {
    if (v && v && v !== "" && v.length >= 3) {
      try {
        setLoading(true);
        logImEXEvent("global_search", { search: v });

        const searchData = await axios.post("/search", {
          search: v
        });

        const resultsByType = {
          payments: [],
          jobs: [],
          bills: [],
          owners: [],
          vehicles: []
        };

        searchData.data.hits.hits.forEach((hit) => {
          resultsByType[hit._index].push(hit._source);
        });
        setData([
          {
            label: renderTitle(t("menus.header.search.jobs")),
            options: resultsByType.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>
                      <span>{`${job.plate_no || ""}`}</span>
                    </Space>
                  </Link>
                )
              };
            })
          },
          {
            label: renderTitle(t("menus.header.search.owners")),
            options: resultsByType.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: resultsByType.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: resultsByType.payments.map((payment) => {
              return {
                key: payment.id,
                value: `${payment.job?.ro_number} ${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: resultsByType.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: resultsByType.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>
          //       ),
          //     };
          //   }),
          // },
        ]);
      } catch (error) {
        console.log("Error while fetching search results", error);
      } finally {
        setLoading(false);
      }
    }
  };
  const debouncedExecuteSearch = _.debounce(executeSearch, 750);

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

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

  return (
    <AutoComplete
      options={data}
      defaultActiveFirstOption
      onKeyDown={(e) => {
        if (e.key !== "Enter") return;
        const firstUrlForSearch = data?.[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}
        onChange={(e) => {
          const value = e.target.value;
          if (!value) {
            setData([]);
          } else {
            handleSearch(value);
          }
        }}
      />
    </AutoComplete>
  );
}
