import React from "react";
import {CloseButton, Dialog, Heading, Portal, Stack,} from "@chakra-ui/react";
import {OpenChangeDetails} from "@chakra-ui/react/dist/types/components/dialog/namespace";
import {useAppStore} from "../appstore";
import {SearchDialogContent} from "./searchDialogContent";

type SearchDialogProps = {
  open: boolean;
  onClose: () => void;
};

export function SearchDialog({open, onClose}: SearchDialogProps) {
  const {searchTerm, clearSearchResults} = useAppStore();

  return (
    <Dialog.Root
      size={{md: "xl"}}
      open={open}
      onOpenChange={(e: OpenChangeDetails) => {
        // @ts-expect-error
        if (!e.open) {
          onClose();
        }
      }}
      closeOnInteractOutside={false}
      closeOnEscape={false}
      onEscapeKeyDown={() => {
        if (searchTerm) {
          clearSearchResults();
        } else {
          onClose();
        }
      }}
    >
      <Portal>
        <Dialog.Backdrop/>
        {/* @ts-expect-error chakra dialog typing issue */}
        <Dialog.Positioner>
          {/* @ts-expect-error chakra dialog typing issue */}
          <Dialog.Content>
            <Dialog.Body>
              <Stack gap="1rem" margin="1rem 0">
                <Heading size="3xl">Store items lookup</Heading>
                <SearchDialogContent/>
              </Stack>
            </Dialog.Body>

            {/* @ts-expect-error chakra dialog typing issue */}
            <Dialog.CloseTrigger asChild>
              <CloseButton size="sm"/>
            </Dialog.CloseTrigger>
          </Dialog.Content>
        </Dialog.Positioner>
      </Portal>
    </Dialog.Root>
  );
}
