import { AutoComplete, Divider, Input, Space } from "antd";
import axios from "axios";
import _ from "lodash";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useHistory } 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";

export default function GlobalSearchOs() {
  const { t } = useTranslation();
  const history = useHistory();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(false);

  const executeSearch = async (v) => {
    if (v && v && v !== "" && v.length >= 3) {
      try {
        setLoading(true);
        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" split={<Divider type="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: resultsByType.owners.map((owner) => {
              return {
                key: owner.id,
                value: OwnerNameDisplayFunction(owner),
                label: (
                  <Link to={`/manage/owners/${owner.id}`}>
                    <Space
                      size="small"
                      split={<Divider type="vertical" />}
                      wrap
                    >
                      <span>
                        <OwnerNameDisplay ownerObject={owner} />
                      </span>
                      <PhoneNumberFormatter>
                        {owner.ownr_ph1}
                      </PhoneNumberFormatter>
                      <PhoneNumberFormatter>
                        {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" split={<Divider type="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" 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: 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" 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: 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" split={<Divider type="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}
      onSearch={handleSearch}
      defaultActiveFirstOption
      onSelect={(val, opt) => {
        history.push(opt.label.props.to);
      }}
      onClear={() => setData([])}
    >
      <Input.Search
        size="large"
        placeholder={t("general.labels.globalsearch")}
        enterButton
        allowClear
        loading={loading}
      />
    </AutoComplete>
  );
}
