import { useCallback, useEffect, useRef, useState } from 'react';
import { api } from '../api.js';
import { useAuth } from '../context/AuthContext.jsx';
import NotifTypeAvatar, { TYPE_META } from '../components/NotifTypeAvatar.jsx';

const PAGE_SIZE = 10;

// Dropdown générique (Status / Type)
function FilterDropdown({ label, value, options, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const current = options.find(o => o.value === value);

  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        className="notif-filter-btn"
        onClick={() => setOpen(o => !o)}
      >
        {label}{current && current.value !== options[0].value ? ` : ${current.label}` : ''}
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ marginLeft: 4 }}>
          <polyline points="6 9 12 15 18 9"/>
        </svg>
      </button>
      {open && (
        <div className="notif-filter-menu">
          {options.map(o => (
            <button
              key={o.value}
              className={`notif-filter-option${value === o.value ? ' active' : ''}`}
              onClick={() => { onChange(o.value); setOpen(false); }}
            >
              {value === o.value && (
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ marginRight: 6, flexShrink: 0 }}>
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              )}
              {value !== o.value && <span style={{ width: 19, flexShrink: 0 }} />}
              {o.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function timeAgo(dateStr) {
  const diff = (Date.now() - new Date(dateStr + 'Z').getTime()) / 1000;
  if (diff < 60)       return 'À l\'instant';
  if (diff < 3600)     return `Il y a ${Math.floor(diff / 60)} min`;
  if (diff < 86400)    return `Il y a ${Math.floor(diff / 3600)} h`;
  if (diff < 86400 * 7) return `Il y a ${Math.floor(diff / 86400)} j`;
  return new Date(dateStr + 'Z').toLocaleDateString('fr-FR', { day: '2-digit', month: 'short', year: 'numeric' });
}

const STATUS_OPTIONS = [
  { value: 'all',    label: 'Tous' },
  { value: 'unread', label: 'Non lus' },
  { value: 'read',   label: 'Lus' },
];

const TYPE_OPTIONS = [
  { value: 'all', label: 'Tous les types' },
  ...Object.entries(TYPE_META).map(([v, m]) => ({ value: v, label: m.label })),
];

export default function Notifications() {
  const { isAdmin }                     = useAuth();
  const [notifs, setNotifs]             = useState([]);
  const [total, setTotal]               = useState(0);
  const [loading, setLoading]           = useState(true);
  const [page, setPage]                 = useState(0);
  const [search, setSearch]             = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterType, setFilterType]     = useState('all');
  const [seeding, setSeeding]           = useState(false);
  const [seedCount, setSeedCount]       = useState(3);

  const fetchNotifs = useCallback(async (p = 0, status = filterStatus, type = filterType) => {
    setLoading(true);
    try {
      const params = { limit: PAGE_SIZE, offset: p * PAGE_SIZE };
      if (status === 'unread') params.unread_only = 'true';
      if (type !== 'all') params.type = type;
      const data = await api.get('/notifications', params);
      setNotifs(data.notifications ?? []);
      setTotal(data.total ?? 0);
    } catch { /* silencieux */ }
    setLoading(false);
  }, [filterStatus, filterType]);

  useEffect(() => {
    fetchNotifs(page, filterStatus, filterType);
  }, [page, filterStatus, filterType]); // eslint-disable-line

  const handleStatus = (v) => { setFilterStatus(v); setPage(0); };
  const handleType   = (v) => { setFilterType(v);   setPage(0); };

  const markRead = async (id) => {
    try {
      await api.patch(`/notifications/${id}/read`);
      setNotifs(prev => prev.map(n => n.id === id ? { ...n, read: 1 } : n));
    } catch { /* silencieux */ }
  };

  const markAll = async () => {
    try {
      await api.patch('/notifications/read-all');
      setNotifs(prev => prev.map(n => ({ ...n, read: 1 })));
    } catch { /* silencieux */ }
  };

  const deleteNotif = async (id) => {
    try {
      await api.del(`/notifications/${id}`);
      setNotifs(prev => prev.filter(n => n.id !== id));
      setTotal(prev => Math.max(0, prev - 1));
    } catch { /* silencieux */ }
  };

  const seedNotifs = async () => {
    setSeeding(true);
    try {
      await api.post('/notifications/seed', { count: seedCount });
      await fetchNotifs(0, filterStatus, filterType);
      setPage(0);
      // Forcer le rafraîchissement du compteur dans la cloche
      window.dispatchEvent(new CustomEvent('notif:refresh'));
    } catch { /* silencieux */ }
    setSeeding(false);
  };

  // Filtrage local par recherche (sur titre + body)
  const visible = search.trim()
    ? notifs.filter(n =>
        n.title.toLowerCase().includes(search.toLowerCase()) ||
        (n.body ?? '').toLowerCase().includes(search.toLowerCase())
      )
    : notifs;

  const unreadTotal = notifs.filter(n => !n.read).length;
  const totalPages  = Math.ceil(total / PAGE_SIZE);
  const from = page * PAGE_SIZE + 1;
  const to   = Math.min((page + 1) * PAGE_SIZE, total);

  return (
    <>
      {/* topbar vide pour respecter le layout (pas de contenu ici) */}
      <div className="topbar" style={{ display: 'none' }} aria-hidden />

      {/* ── Wrapper centré (.main ajoute padding: 0 24px) ── */}
      <div className="notif-center-wrap">

        {/* ── Bloc principal notifications ── */}
        <div className="card notif-block">

          {/* En-tête du bloc */}
          <div className="notif-block-header">
            <h2 className="notif-page-title">Notifications</h2>
            <button
              className="notif-markall-btn"
              onClick={markAll}
              disabled={unreadTotal === 0}
            >
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
              Tout marquer lu
            </button>
          </div>

          {/* Barre recherche + filtres */}
          <div className="notif-toolbar" style={{ borderTop: '1px solid var(--border)' }}>
            <div className="notif-search-wrap">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="notif-search-icon">
                <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
              </svg>
              <input
                className="notif-search-input"
                placeholder="Rechercher des notifications…"
                value={search}
                onChange={e => setSearch(e.target.value)}
              />
            </div>
            <div className="notif-filters">
              <FilterDropdown label="Statut" value={filterStatus} options={STATUS_OPTIONS} onChange={handleStatus} />
              <FilterDropdown label="Type"   value={filterType}   options={TYPE_OPTIONS}   onChange={handleType} />
            </div>
          </div>

          {/* Séparateur */}
          <div style={{ borderTop: '1px solid var(--border)' }} />

          {/* Liste */}
          {loading && (
            <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)', fontSize: 14 }}>
              Chargement…
            </div>
          )}
          {!loading && visible.length === 0 && (
            <div style={{ padding: 56, textAlign: 'center', color: 'var(--text-muted)' }}>
              <div style={{ fontSize: 36, marginBottom: 10 }}>🔔</div>
              <div style={{ fontWeight: 600, marginBottom: 4 }}>Aucune notification</div>
              <div style={{ fontSize: 13 }}>Vous êtes à jour !</div>
            </div>
          )}
          {!loading && visible.map((n, i) => (
            <div
              key={n.id}
              className={`notif-row${!n.read ? ' notif-row-unread' : ''}`}
              style={{ borderTop: i === 0 ? 'none' : '1px solid var(--border)' }}
            >
              <NotifTypeAvatar type={n.type} />
              <div className="notif-row-body">
                <div className="notif-row-title">{n.title}</div>
                {n.body && <div className="notif-row-text">{n.body}</div>}
              </div>
              <span className="notif-type-badge" style={{
                background: (TYPE_META[n.type] ?? TYPE_META.info).bg,
                color: (TYPE_META[n.type] ?? TYPE_META.info).color,
              }}>
                {(TYPE_META[n.type] ?? TYPE_META.info).label}
              </span>
              <span className="notif-row-time">{timeAgo(n.created_at)}</span>
              <div className="notif-row-actions">
                {!n.read && (
                  <button className="btn-icon-sm" title="Marquer comme lu" onClick={() => markRead(n.id)}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
                  </button>
                )}
                <button className="btn-icon-sm" title="Supprimer" onClick={() => deleteNotif(n.id)}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4h6v2"/></svg>
                </button>
                {!n.read && <span className="notif-unread-dot" />}
              </div>
            </div>
          ))}

          {/* Pagination */}
          <div className="notif-pagination">
            <span className="notif-pagination-info">
              {total === 0 ? 'Aucune notification' : `Affichage de ${from} à ${to} sur ${total} notification${total > 1 ? 's' : ''}`}
            </span>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="notif-page-btn" disabled={page === 0} onClick={() => setPage(p => p - 1)}>
                Précédent
              </button>
              <button className="notif-page-btn" disabled={page >= totalPages - 1} onClick={() => setPage(p => p + 1)}>
                Suivant
              </button>
            </div>
          </div>

        </div>{/* fin .notif-block */}

        {/* ── Bloc Simulation (admin uniquement) ── */}
        {isAdmin && (
          <div className="card notif-block" style={{ marginTop: 16 }}>
            <div className="notif-block-header">
              <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: 'var(--text)' }}>
                Simulation
              </h3>
            </div>
            <div className="notif-admin-bar" style={{ borderTop: '1px solid var(--border)' }}>
              <span style={{ color: 'var(--text-muted)', fontSize: 13 }}>Générer des notifications de test :</span>
              <select
                value={seedCount}
                onChange={e => setSeedCount(Number(e.target.value))}
                className="notif-seed-select"
              >
                {[1, 2, 3, 4, 5, 6].map(n => (
                  <option key={n} value={n}>{n} notif{n > 1 ? 's' : ''}</option>
                ))}
              </select>
              <button className="btn btn-sm" onClick={seedNotifs} disabled={seeding} style={{ whiteSpace: 'nowrap' }}>
                {seeding ? 'Création…' : '+ Créer'}
              </button>
            </div>
          </div>
        )}

      </div>{/* fin .notif-center-wrap */}
    </>
  );
}
