import React, { useState, useEffect, useCallback } from 'react';
import { X, Info, AlertTriangle, AlertCircle } from 'lucide-react';
import { adminService } from '@/services/adminService';
import { cn } from '@/lib/utils';

interface Announcement {
  id: string;
  title: string;
  content: string;
  type: string;
}

const DISMISSED_KEY = 'veza-dismissed-announcements';

function loadDismissed(): Set<string> {
  try {
    const raw = localStorage.getItem(DISMISSED_KEY);
    return raw ? new Set(JSON.parse(raw)) : new Set();
  } catch {
    return new Set();
  }
}

function saveDismissed(ids: Set<string>) {
  try {
    localStorage.setItem(DISMISSED_KEY, JSON.stringify([...ids]));
  } catch { /* ignore */ }
}

const defaultConfig = { icon: Info, className: 'bg-primary/10 border-[var(--sumi-border-faint)] text-foreground' };

const typeConfig: Record<string, { icon: React.ElementType; className: string }> = {
  info: defaultConfig,
  warning: { icon: AlertTriangle, className: 'bg-warning/10 border-warning/30 text-foreground' },
  error: { icon: AlertCircle, className: 'bg-destructive/10 border-destructive/30 text-foreground' },
};

export function AnnouncementBanner() {
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);
  const [dismissed, setDismissed] = useState<Set<string>>(loadDismissed);
  const [showAll, setShowAll] = useState(false);

  useEffect(() => {
    adminService.getActiveAnnouncements().then(setAnnouncements).catch(() => {});
  }, []);

  const dismiss = useCallback((id: string) => {
    setDismissed((prev) => {
      const next = new Set(prev).add(id);
      saveDismissed(next);
      return next;
    });
  }, []);

  const visible = announcements.filter((a) => !dismissed.has(a.id));
  if (visible.length === 0) return null;

  const shown = showAll ? visible : visible.slice(0, 1);
  const remaining = showAll ? 0 : visible.length - shown.length;

  return (
    <div className="space-y-2 px-4 pt-2">
      {shown.map((a) => {
        const config = typeConfig[a.type] ?? defaultConfig;
        const Icon = config.icon;
        return (
          <div
            key={a.id}
            className={cn(
              'flex items-start gap-3 rounded-sm border p-3 text-sm',
              config.className,
            )}
            role="alert"
          >
            <Icon className="mt-0.5 h-4 w-4 shrink-0 opacity-60" />
            <div className="min-w-0 flex-1">
              <span className="font-heading" style={{ fontWeight: 400 }}>{a.title}</span>
              <span className="mx-2 text-muted-foreground/30">—</span>
              <span className="text-muted-foreground/60 font-heading" style={{ fontWeight: 300 }}>{a.content}</span>
            </div>
            <button
              type="button"
              onClick={() => dismiss(a.id)}
              className="shrink-0 rounded-sm p-1 opacity-40 hover:opacity-100 transition-opacity"
              aria-label="Dismiss announcement"
            >
              <X className="h-3.5 w-3.5" />
            </button>
          </div>
        );
      })}
      {remaining > 0 && (
        <button
          type="button"
          onClick={() => setShowAll(true)}
          className="text-[10px] text-muted-foreground/50 hover:text-foreground text-center tracking-[0.1em] font-heading py-1 px-3 rounded-md bg-muted/30 border border-border/30 mx-auto w-fit block cursor-pointer transition-colors"
          style={{ fontWeight: 300 }}
        >
          +{remaining} more
        </button>
      )}
    </div>
  );
}
