import { Alert } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";

import { apiErrorMessage } from "@/auth/http";

/**
 * Surfaces the SERVER's message rather than "Request failed with status code
 * NNN" — the API's validation and conflict errors say exactly what is wrong
 * ("Employee number EMP-00007 is already in use"), and that is what the user
 * needs to see.
 */
export function ApiErrorAlert({
  error,
  title = "Something went wrong",
}: {
  error: unknown;
  title?: string;
}) {
  if (!error) return null;
  return (
    <Alert
      color="red"
      icon={<IconAlertTriangle size={18} />}
      title={title}
      mb="md"
      styles={{ message: { whiteSpace: "pre-line" } }}
    >
      {apiErrorMessage(error)}
    </Alert>
  );
}
