"use client"

import { RestErrorResponse } from "@/back-api";
import {
  Toaster as ChakraToaster,
  Portal,
  Spinner,
  Stack,
  Toast,
  createToaster,
} from "@chakra-ui/react"
import { useCallback } from "react";

export const toaster = createToaster({
  duration: 3000,
  placement: 'top-end',
  // offset: { top: '50px' },
  // variant: 'solid',
})

export const toasterAPIError = (error: RestErrorResponse) => {
  toaster.create({
    title: `[${error.status}] ${error.statusMessage}`,
    description: error.message,
  });
};

export const Toaster = () => {
  return (
    <Portal>
      <ChakraToaster
        toaster={toaster}
        insetInline={{ mdDown: "1rem" }}
        width={{ md: "356px" }}
      >
        {(toast) => (
          <Toast.Root>
            {toast.type === "loading" ? (
              <Spinner size="sm" color="blue.solid" />
            ) : (
              <Toast.Indicator />
            )}
            <Stack gap="1" flex="1" maxWidth="100%">
              {toast.title && <Toast.Title>{toast.title}</Toast.Title>}
              {toast.description && (
                <Toast.Description>{toast.description}</Toast.Description>
              )}
            </Stack>
            {toast.action && (
              <Toast.ActionTrigger>{toast.action.label}</Toast.ActionTrigger>
            )}
            {toast.meta?.closable && <Toast.CloseTrigger />}
          </Toast.Root>
        )}
      </ChakraToaster>
    </Portal>
  )
}
