import { useEffect, useState } from 'react';
import { X } from 'lucide-react';
import axios from 'axios';

interface Announcement {
  id: string;
  message: string;
}

export function AnnouncementBanner() {
  const [announcement, setAnnouncement] = useState<Announcement | null>(null);
  const [isVisible, setIsVisible] = useState(true);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchAnnouncement = async () => {
      try {
        const response = await axios.get('/api/announcements/active');
        if (response.data) {
          setAnnouncement(response.data);
        }
      } catch (error) {
        console.error('Failed to fetch announcement:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchAnnouncement();
  }, []);

  if (isLoading || !announcement || !isVisible) {
    return null;
  }

  return (
      <div className="relative bg-gradient-to-r from-blue-600 to-blue-700 text-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between py-3 sm:py-4">
            <div className="flex-1 text-center">
              <p className="text-sm sm:text-base font-medium">
                {announcement.message}
              </p>
            </div>
            <button
                onClick={() => setIsVisible(false)}
                className="ml-4 inline-flex text-white hover:bg-white/20 rounded-full p-1 transition-colors"
                aria-label="Close announcement"
            >
              <X size={20} />
            </button>
          </div>
        </div>
      </div>
  );
}
