"use client";
import { api } from "@/trpc/react";
import React from "react";
import { Combobox, ComboboxProps } from "../combobox";
import { Icons } from "../icons";

function CategorySelect(props: Partial<ComboboxProps>) {
  const { data: categories } = api.category.getMany.useQuery();
  const initialValue = categories?.find(
    (c) => c.id === props?.initialValue,
  )?.slug;

  return (
    <Combobox
      {...(props as ComboboxProps)}
      initialValue={initialValue}
      messageUi={{
        select: "Kategorie auswählen...",
        selectIcon: Icons.category,
        placeholder: "Kategorie suchen...",
        empty: "Keine Kategorien gefunden",
      }}
      onSelect={(value) => {
        const id = categories?.find((c) => {
          return c.slug === value;
        })?.id!;
        props?.onSelect?.(id);
      }}
      data={
        categories?.map(({ name, slug }) => ({
          label: name,
          value: slug,
        })) ?? []
      }
    />
  );
}

export default CategorySelect;
