import { useState } from 'react';
import { Alert, AlertTitle, Box, IconButton, Collapse } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { useQuery } from '@tanstack/react-query';
import { bannerApi } from '../../services/banners';
import type { Banner, BannerLevel } from '../../types/banner.types';

const DISMISSED_KEY = 'dismissed_banners'; // sessionStorage key

function getDismissed(): string[] {
  try { return JSON.parse(sessionStorage.getItem(DISMISSED_KEY) ?? '[]'); } catch { return []; }
}
function addDismissed(id: string) {
  const list = getDismissed();
  if (!list.includes(id)) sessionStorage.setItem(DISMISSED_KEY, JSON.stringify([...list, id]));
}

const LEVEL_MAP: Record<BannerLevel, 'info' | 'warning' | 'error'> = {
  info: 'info',
  important: 'warning',
  critical: 'error',
};

const LEVEL_TITLE: Record<BannerLevel, string> = {
  info: 'Information',
  important: 'Wichtig',
  critical: 'Kritisch',
};

export default function AnnouncementBanner({ gridColumn }: { gridColumn?: string }) {
  const [dismissed, setDismissed] = useState<string[]>(() => getDismissed());

  const { data: banners = [] } = useQuery({
    queryKey: ['banners', 'active'],
    queryFn: bannerApi.getActive,
    refetchInterval: 60_000,
    retry: 1,
  });

  const visible = banners.filter(b => b.show_as !== 'widget' && (!dismissed.includes(b.id) || b.level === 'critical'));

  const handleDismiss = (banner: Banner) => {
    if (banner.level === 'critical') return; // never dismiss critical
    addDismissed(banner.id);
    setDismissed(getDismissed());
  };

  if (visible.length === 0) return null;

  return (
    <Box sx={{ mb: 0, display: 'flex', flexDirection: 'column', gap: 1, ...(gridColumn ? { gridColumn } : {}) }}>
      {visible.map(banner => (
        <Collapse key={banner.id} in>
          <Alert
            severity={LEVEL_MAP[banner.level]}
            variant="filled"
            action={
              banner.level !== 'critical' ? (
                <IconButton size="small" color="inherit" onClick={() => handleDismiss(banner)}>
                  <CloseIcon fontSize="small" />
                </IconButton>
              ) : undefined
            }
          >
            <AlertTitle sx={{ fontWeight: 700 }}>{LEVEL_TITLE[banner.level]}</AlertTitle>
            {banner.message}
          </Alert>
        </Collapse>
      ))}
    </Box>
  );
}
