/* eslint-disable @next/next/no-img-element */
import "react-cmdk/dist/cmdk.css";
import CommandPalette, { getItemIndex } from "react-cmdk";
import type { JsonStructure } from "react-cmdk";
import styles from "./index.module.scss";

export type SearchProductItem = {
  _id: string;
  title?: string;
  image?: string[];
  [key: string]: any;
};

type DashboardSearchResultsProps = {
  visible: boolean;
  search: string;
  onSearchChange: (value: string) => void;
  products: SearchProductItem[] | false;
  onProductSelect: (id: string) => void;
};

function buildStructure(
  products: SearchProductItem[],
  onSelect: (id: string) => void
): JsonStructure {
  return [
    {
      id: "products",
      heading: "Products",
      items: products.map((p) => ({
        id: p._id,
        children: (
          <>
            {p?.image?.[0] && (
              <img
                src={p.image[0]}
                alt=""
                className={styles.itemImage}
                width={50}
                height={50}
              />
            )}
            <span className={styles.itemTitle}>{p?.title ?? ""}</span>
          </>
        ),
        onClick: () => onSelect(p._id),
        closeOnSelect: true,
        showType: false,
      })),
    },
  ];
}

export default function DashboardSearchResults({
  visible,
  search,
  onSearchChange,
  products,
  onProductSelect,
}: DashboardSearchResultsProps) {
  const hasResults = Array.isArray(products) && products.length > 0;
  const structure = hasResults
    ? buildStructure(products, onProductSelect)
    : [];

  return (
    <div className={styles.wrapper}>
      <CommandPalette
        onChangeSearch={onSearchChange}
        onChangeOpen={(open) => {
          if (!open) onSearchChange("");
        }}
        search={search}
        isOpen={visible}
        page="root"
        placeholder="Search products..."
      >
        <CommandPalette.Page id="root">
          {hasResults ? (
            structure.map((list) => (
              <CommandPalette.List key={list.id} heading={list.heading}>
                {list.items.map(({ id, ...rest }) => (
                  <CommandPalette.ListItem
                    key={id}
                    index={getItemIndex(structure, id)}
                    {...rest}
                  />
                ))}
              </CommandPalette.List>
            ))
          ) : (
            Array.isArray(products) && (
              <CommandPalette.List>
                <div className={styles.noResults}>No Result Found</div>
              </CommandPalette.List>
            )
          )}
        </CommandPalette.Page>
      </CommandPalette>
    </div>
  );
}
