import { useMemo, useState, type ReactNode } from 'react';
import { usePage } from '@inertiajs/react';

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

export type DashboardNewsFeedItem = {
  id: number;
  title: string;
  body: string;
  imagePath: string | null;
  isImportant: boolean;
  template?: string;
  accentColor: string;
  read?: boolean;
  createdAt: string;
};

type FeedItem = {
  key: string;
  source: 'announcement' | 'news';
  id: number;
  title: string;
  body: string;
  color: string;
  icon: string;
  imagePath?: string | null;
  isImportant: boolean;
  hasPulse: boolean;
  createdAt?: string;
  read?: boolean;
};

function csrf(): string {
  return (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content ?? '';
}

function post(url: string) {
  fetch(url, {
    method: 'POST',
    headers: { 'X-CSRF-TOKEN': csrf(), 'Content-Type': 'application/json', Accept: 'application/json' },
    credentials: 'same-origin',
  }).catch(() => {});
}

function renderNewsText(text: string): ReactNode[] {
  const nodes: ReactNode[] = [];
  const pattern = /(\*\*([^*]+)\*\*)|(\[([^\]]+)\]\((https?:\/\/[^)\s]+)\))/g;
  let lastIndex = 0;
  let match: RegExpExecArray | null;

  while ((match = pattern.exec(text)) !== null) {
    if (match.index > lastIndex) nodes.push(text.slice(lastIndex, match.index));
    if (match[2]) nodes.push(<strong key={`b-${match.index}`}>{match[2]}</strong>);
    if (match[4] && match[5]) {
      nodes.push(<a key={`a-${match.index}`} href={match[5]} target="_blank" rel="noreferrer">{match[4]}</a>);
    }
    lastIndex = pattern.lastIndex;
  }

  if (lastIndex < text.length) nodes.push(text.slice(lastIndex));
  return nodes;
}

function iconForTemplate(template?: string): string {
  if (template === 'warning') return 'bi-exclamation-triangle-fill';
  if (template === 'danger') return 'bi-x-octagon-fill';
  if (template === 'success') return 'bi-check-circle-fill';
  if (template === 'custom') return 'bi-palette-fill';
  return 'bi-info-circle-fill';
}

export function DashboardFeed({ news = [] }: { news?: DashboardNewsFeedItem[] }) {
  const { props } = usePage<{ activeAnnouncements?: ActiveAnnouncement[] }>();
  const activeAnnouncements = props.activeAnnouncements ?? [];
  const [hiddenKeys, setHiddenKeys] = useState<string[]>([]);
  const [expandedKey, setExpandedKey] = useState<string | null>(null);

  const items = useMemo<FeedItem[]>(() => {
    const announcementItems = activeAnnouncements.map((item): FeedItem => ({
      key: `announcement-${item.id}`,
      source: 'announcement',
      id: item.id,
      title: item.title,
      body: item.body,
      color: item.color || '#d97706',
      icon: item.isImportant ? 'bi-megaphone-fill' : 'bi-megaphone',
      isImportant: item.isImportant,
      hasPulse: item.hasPulse,
    }));

    const newsItems = news.map((item): FeedItem => ({
      key: `news-${item.id}`,
      source: 'news',
      id: item.id,
      title: item.title,
      body: item.body,
      color: item.accentColor || '#0EA678',
      icon: iconForTemplate(item.template),
      imagePath: item.imagePath,
      isImportant: item.isImportant,
      hasPulse: item.isImportant,
      createdAt: item.createdAt,
      read: item.read,
    }));

    return [...announcementItems, ...newsItems]
      .sort((a, b) => Number(b.isImportant) - Number(a.isImportant))
      .filter((item) => !hiddenKeys.includes(item.key));
  }, [activeAnnouncements, hiddenKeys, news]);

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

  const expanded = expandedKey ? items.find((item) => item.key === expandedKey) : items[0];
  const visibleExpanded = expanded ?? items[0];

  function dismiss(item: FeedItem) {
    if (item.source === 'announcement') {
      post(`/api/announcements/${item.id}/dismiss`);
    } else if (!item.read) {
      post(`/news/${item.id}/read`);
    }
    setHiddenKeys((current) => [...current, item.key]);
    if (expandedKey === item.key) setExpandedKey(null);
  }

  function dismissAll() {
    items.forEach((item) => {
      if (item.source === 'news' && !item.read) post(`/news/${item.id}/read`);
    });
    if (items.some((item) => item.source === 'announcement')) post('/api/announcements/dismiss-all');
    setHiddenKeys((current) => [...current, ...items.map((item) => item.key)]);
    setExpandedKey(null);
  }

  return (
    <section className="panel-card dashboard-feed-panel">
      <div className="dashboard-feed-head">
        <div>
          <span className="dashboard-feed-kicker">مرکز اطلاع‌رسانی</span>
          <h2>اطلاعیه‌ها و اخبار</h2>
        </div>
        <div className="dashboard-feed-actions">
          <span className="dashboard-feed-count">{items.length}</span>
          <button type="button" className="btn btn-ghost btn-sm" onClick={dismissAll}>
            <i className="bi bi-check2-all" /> خواندم
          </button>
        </div>
      </div>

      <div className="dashboard-feed-body">
        <div className="dashboard-feed-list">
          {items.map((item) => (
            <button
              key={item.key}
              type="button"
              className={`dashboard-feed-tab${visibleExpanded.key === item.key ? ' is-active' : ''}${item.isImportant ? ' is-important' : ''}`}
              style={{ '--feed-color': item.color } as React.CSSProperties}
              onClick={() => setExpandedKey(item.key)}
            >
              <span className="dashboard-feed-tab-icon">
                <i className={`bi ${item.icon}`} />
              </span>
              <span className="dashboard-feed-tab-text">
                <strong>{item.title}</strong>
                <small>{item.source === 'news' ? 'خبر داشبورد' : 'اطلاعیه مدرسه'}{item.createdAt ? ` · ${item.createdAt}` : ''}</small>
              </span>
            </button>
          ))}
        </div>

        <article
          className={`dashboard-feed-card${visibleExpanded.hasPulse && visibleExpanded.isImportant ? ' dashboard-feed-card--pulse' : ''}`}
          style={{ '--feed-color': visibleExpanded.color } as React.CSSProperties}
        >
          {visibleExpanded.imagePath && (
            <img className="dashboard-feed-image" src={`/storage/${visibleExpanded.imagePath}`} alt="" />
          )}
          <div className="dashboard-feed-card-top">
            <span className="dashboard-feed-card-icon"><i className={`bi ${visibleExpanded.icon}`} /></span>
            {visibleExpanded.isImportant && <span className="dashboard-feed-badge">مهم</span>}
            <button type="button" className="dashboard-feed-close" onClick={() => dismiss(visibleExpanded)} aria-label="بستن">
              <i className="bi bi-x-lg" />
            </button>
          </div>
          <h3>{visibleExpanded.title}</h3>
          {visibleExpanded.source === 'announcement' ? (
            <div className="dashboard-feed-text" dangerouslySetInnerHTML={{ __html: visibleExpanded.body }} />
          ) : (
            <p className="dashboard-feed-text">{renderNewsText(visibleExpanded.body)}</p>
          )}
        </article>
      </div>
    </section>
  );
}
