import { useState } from 'react';
import { usePage } from '@inertiajs/react';

type Announcement = {
  id: number;
  title: string;
  body: string;
  color: string;
  hasPulse: boolean;
  isImportant: boolean;
};

function hexToRgb(hex: string): string {
  const h = hex.replace('#', '');
  const r = parseInt(h.substring(0, 2), 16);
  const g = parseInt(h.substring(2, 4), 16);
  const b = parseInt(h.substring(4, 6), 16);
  return `${r}, ${g}, ${b}`;
}

async function postDismiss(id: number | 'all', csrfToken: string) {
  const url = id === 'all' ? '/api/announcements/dismiss-all' : `/api/announcements/${id}/dismiss`;
  await fetch(url, {
    method: 'POST',
    headers: { 'X-CSRF-TOKEN': csrfToken, 'Content-Type': 'application/json' },
    credentials: 'same-origin',
  });
}

export function AnnouncementBanner() {
  const { props } = usePage<{ activeAnnouncements?: Announcement[] }>();
  const initial = (props.activeAnnouncements ?? []) as Announcement[];
  const [items, setItems] = useState<Announcement[]>(initial);
  const [expanded, setExpanded] = useState<number | null>(null);

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

  const csrf = (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content ?? '';

  function dismiss(id: number) {
    postDismiss(id, csrf);
    setItems((prev) => prev.filter((a) => a.id !== id));
    if (expanded === id) setExpanded(null);
  }

  function dismissAll() {
    postDismiss('all', csrf);
    setItems([]);
    setExpanded(null);
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem', marginBottom: '0.75rem' }}>
      {items.map((ann, idx) => {
        const isOpen = expanded === ann.id;
        const rgb = hexToRgb(ann.color);
        const isStacked = !isOpen && idx > 0;

        return (
          <div
            key={ann.id}
            style={{
              position: 'relative',
              background: `rgba(${rgb}, 0.08)`,
              border: `1.5px solid rgba(${rgb}, 0.35)`,
              borderRadius: 'var(--radius-md)',
              overflow: 'hidden',
              ...(isStacked ? { opacity: 0.85 } : {}),
            }}
          >
            {/* Pulse ring on important */}
            {ann.hasPulse && ann.isImportant && (
              <span style={{
                position: 'absolute',
                top: 10, right: 10,
                width: 10, height: 10,
                borderRadius: '50%',
                background: ann.color,
                boxShadow: `0 0 0 4px rgba(${rgb},0.25)`,
                animation: 'pulse-ring 1.5s ease-in-out infinite',
              }} />
            )}

            <div
              style={{ display: 'flex', alignItems: 'flex-start', gap: '0.6rem', padding: '0.65rem 0.9rem', cursor: 'pointer' }}
              onClick={() => setExpanded(isOpen ? null : ann.id)}
            >
              {ann.hasPulse && !ann.isImportant && (
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: ann.color, flexShrink: 0, marginTop: 5 }} />
              )}
              <i className={`bi ${ann.isImportant ? 'bi-megaphone-fill' : 'bi-info-circle'}`} style={{ color: ann.color, fontSize: '1rem', flexShrink: 0, marginTop: 1 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: '0.875rem', color: ann.color }}>{ann.title}</div>
                {isOpen && (
                  <div
                    style={{ fontSize: '0.875rem', color: 'var(--color-text)', marginTop: '0.35rem', lineHeight: 1.6 }}
                    dangerouslySetInnerHTML={{ __html: ann.body }}
                  />
                )}
              </div>
              <div style={{ display: 'flex', gap: '0.35rem', flexShrink: 0 }}>
                <button
                  type="button"
                  title={isOpen ? 'بستن' : 'بیشتر'}
                  onClick={(e) => { e.stopPropagation(); setExpanded(isOpen ? null : ann.id); }}
                  style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-text-muted)', fontSize: '0.85rem', padding: '0 0.2rem' }}
                >
                  <i className={`bi bi-chevron-${isOpen ? 'up' : 'down'}`} />
                </button>
                <button
                  type="button"
                  title="بستن اطلاعیه"
                  onClick={(e) => { e.stopPropagation(); dismiss(ann.id); }}
                  style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-text-muted)', fontSize: '0.9rem', padding: '0 0.2rem' }}
                >
                  <i className="bi bi-x" />
                </button>
              </div>
            </div>
          </div>
        );
      })}

      {items.length > 1 && (
        <div style={{ textAlign: 'left', direction: 'ltr' }}>
          <button
            type="button"
            onClick={dismissAll}
            style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-text-muted)', fontSize: '0.78rem', textDecoration: 'underline', padding: '0.1rem 0.3rem' }}
          >
            بستن همه ({items.length})
          </button>
        </div>
      )}

      <style>{`
        @keyframes pulse-ring {
          0% { opacity: 1; transform: scale(1); }
          70% { opacity: 0.25; transform: scale(1.8); }
          100% { opacity: 1; transform: scale(1); }
        }
      `}</style>
    </div>
  );
}
