import React from "react";

import { Alert, Box, Button, CircularProgress, Typography } from "@mui/material";

import type { ViewResourceError } from "../hooks/useViewResource";

type Props = {
  loading?: boolean;
  error?: ViewResourceError | null;
  title: string;
  description?: string;
  retryLabel?: string;
  onRetry?: () => void | Promise<void>;
  compact?: boolean;
};

export default function ViewStateNotice({ loading = false, error = null, title, description, retryLabel = "Retry", onRetry, compact = false }: Props) {
  if (loading) {
    return (
      <Box sx={{ py: compact ? 3 : 6, display: "flex", justifyContent: "center" }}>
        <CircularProgress size={compact ? 24 : 28} />
      </Box>
    );
  }

  if (!error) return null;

  const severity = error.kind === "unauthorized" ? "warning" : error.kind === "unavailable" ? "error" : "error";

  return (
    <Alert
      severity={severity}
      sx={{
        mb: compact ? 1.5 : 2,
        alignItems: "flex-start",
        borderRadius: 3,
      }}
      action={error.retryable && onRetry ? <Button color="inherit" size="small" onClick={() => void onRetry()}>{retryLabel}</Button> : undefined}
    >
      <Typography sx={{ fontWeight: 800, mb: 0.35 }}>{title}</Typography>
      {description ? <Typography variant="body2">{description}</Typography> : null}
      {error.message ? <Typography variant="body2" sx={{ mt: 0.5 }}>{error.message}</Typography> : null}
    </Alert>
  );
}
