import type { SubscribableForm } from "@/components/form-common/types";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { getErrorMessage } from "@/lib/errors";
import { type ReactNode, useEffect, useState } from "react";

export interface FormServerErrorsProps {
  title: ReactNode;
  beforeMessage?: ReactNode;
  message?: (message: string) => ReactNode;
  afterMessage?: ReactNode;
  formApi: SubscribableForm<{ errorMap: { onServer?: unknown } }>;
}

export function FormServerErrors({
  title,
  message,
  beforeMessage,
  afterMessage,
  formApi,
}: FormServerErrorsProps) {
  const [errorMessage, setErrorMessageMessage] = useState<string | undefined>(
    undefined
  );
  useEffect(() => {
    return formApi.store.subscribe((state) => {
      const error = state.currentVal.errorMap.onServer;
      if (error != null) {
        setErrorMessageMessage(getErrorMessage(error));
      } else {
        setErrorMessageMessage(undefined);
      }
    });
  }, [formApi]);

  if (errorMessage == null) {
    return null;
  }

  return (
    <Alert variant="destructive">
      <AlertTitle>{title}</AlertTitle>
      <AlertDescription className="whitespace-pre-wrap break-all text-wrap">
        {beforeMessage && (
          <>
            {beforeMessage}
            <br />
          </>
        )}
        {message ? message(errorMessage) : errorMessage}
        {afterMessage && (
          <>
            <br />
            {afterMessage}
          </>
        )}
      </AlertDescription>
    </Alert>
  );
}
