import React, { useState } from "react";
import CloseIcon from "@mui/icons-material/Close";
import { Alert, Button, IconButton, Stack, Typography } from "@mui/material";
import { useOptionalI18n } from "../i18n/I18nProvider";

type Props = {
  featureKey: string;
  title: string;
  children: React.ReactNode;
};

function storageKey(featureKey: string) {
  return `jobtracker.proNoticeDismissed.${featureKey}`;
}

export default function ProFeatureNotice({ featureKey, title, children }: Props) {
  const i18n = useOptionalI18n();
  const [dismissed, setDismissed] = useState(() => {
    if (typeof window === "undefined") return false;
    try {
      return window.sessionStorage.getItem(storageKey(featureKey)) === "true";
    } catch {
      return false;
    }
  });

  if (dismissed) return null;

  const dismiss = () => {
    try {
      window.sessionStorage.setItem(storageKey(featureKey), "true");
    } catch {
      // The notice can still be dismissed for this render when storage is unavailable.
    }
    setDismissed(true);
  };

  return (
    <Alert
      severity="info"
      action={(
        <Stack direction="row" spacing={0.5} alignItems="center">
          <Button href="/settings" size="small">{i18n?.t("proFeatureView") ?? "View Pro"}</Button>
          <IconButton size="small" aria-label={i18n?.t("proFeatureDismiss", { title }) ?? `Dismiss ${title}`} onClick={dismiss}>
            <CloseIcon fontSize="small" />
          </IconButton>
        </Stack>
      )}
    >
      <Typography component="span" sx={{ fontWeight: 800 }}>{title}</Typography>{" "}
      {children}
    </Alert>
  );
}
