import { useCallback, useEffect, useState } from 'react';
import { Archive, Bell, CheckCheck, ChevronLeft, ChevronRight, RotateCcw, Trash2 } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '../services/api';
import { formatJalaliDateTime } from '../utils/date';
import useBidirectionalNotificationSwipe from '../pwa/useBidirectionalNotificationSwipe';

function NotificationRow({ notification, archived, onOpen, onRemove, onRestore }) {
  const runAction = async (action) => {
    try {
      if (action === 'archive') {
        await api.patch(`/notifications/${notification.id}/archive`);
        toast.success('اعلان آرشیو شد');
      } else if (action === 'delete') {
        await api.delete(`/notifications/${notification.id}`);
        toast.success('اعلان حذف شد');
      }
      onRemove(notification.id);
    } catch {
      toast.error('انجام عملیات اعلان ناموفق بود');
    }
  };

  const swipe = useBidirectionalNotificationSwipe({
    rightAction: 'archive',
    leftAction: 'delete',
    onExitComplete: runAction,
  });

  return (
    <div
      className={`notification-swipe-row ${swipe.direction || ''} ${swipe.dragging ? 'dragging' : ''} ${swipe.exiting ? 'exiting' : ''}`}
      style={{
        '--notification-translate': `${swipe.translateX}px`,
        '--notification-progress': swipe.progress,
      }}
      {...swipe.swipeHandlers}
    >
      <div className="notification-swipe-action archive"><Archive size={18} /><span>آرشیو</span></div>
      <div className="notification-swipe-action delete"><Trash2 size={18} /><span>حذف</span></div>
      <div className={`notification-center-item ${notification.read_at ? '' : 'unread'}`}>
        <button type="button" className="notification-center-main" onClick={() => onOpen(notification)}>
          <span className="notification-center-icon"><Bell size={17} /></span>
          <span>
            <strong>{notification.title || notification.message || 'اعلان'}</strong>
            <small>{notification.body || notification.preview?.body || formatJalaliDateTime(notification.created_at)}</small>
          </span>
        </button>
        <div className="notification-center-actions">
          {archived ? (
            <button type="button" onClick={() => onRestore(notification)} title="بازیابی" aria-label="بازیابی اعلان"><RotateCcw size={15} /></button>
          ) : (
            <button type="button" onClick={() => runAction('archive')} title="آرشیو" aria-label="آرشیو اعلان"><Archive size={15} /></button>
          )}
          <button type="button" className="danger" onClick={() => runAction('delete')} title="حذف" aria-label="حذف اعلان"><Trash2 size={15} /></button>
        </div>
      </div>
    </div>
  );
}

export default function NotificationCenter({ onOpenNotification, onCountChange }) {
  const [tab, setTab] = useState('unread');
  const [notifications, setNotifications] = useState([]);
  const [meta, setMeta] = useState({});
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);
  const pageSize = 4;

  const fetchNotifications = useCallback(async () => {
    setLoading(true);
    try {
      const params = { per_page: 20 };
      if (tab === 'unread') params.unread = 1;
      if (tab === 'archived') params.archived = 1;
      const { data } = await api.get('/notifications', { params });
      setNotifications(data.data || []);
      setMeta(data.meta || {});
      onCountChange?.(data.meta?.unread_count || 0);
    } catch {
      toast.error('دریافت اعلان‌ها ناموفق بود');
    } finally {
      setLoading(false);
    }
  }, [tab, onCountChange]);

  useEffect(() => { fetchNotifications(); }, [fetchNotifications]);
  useEffect(() => { setPage(0); }, [tab]);

  const pageCount = Math.max(1, Math.ceil(notifications.length / pageSize));
  const visibleNotifications = notifications.slice(page * pageSize, page * pageSize + pageSize);

  const markAllRead = async () => {
    try {
      await api.post('/notifications/read-all');
      toast.success('همه اعلان‌ها خوانده شدند');
      fetchNotifications();
    } catch {
      toast.error('به‌روزرسانی اعلان‌ها ناموفق بود');
    }
  };

  const openNotification = async (notification) => {
    try {
      const { data } = await api.get(`/notifications/${notification.id}/preview`);
      setNotifications((current) => current.map((item) => item.id === notification.id ? { ...item, read_at: new Date().toISOString() } : item));
      onCountChange?.(Math.max(0, (meta.unread_count || 0) - (notification.read_at ? 0 : 1)));
      onOpenNotification(data.data);
    } catch {
      onOpenNotification(notification);
    }
  };

  const restore = async (notification) => {
    try {
      await api.patch(`/notifications/${notification.id}/restore`);
      setNotifications((current) => current.filter((item) => item.id !== notification.id));
      toast.success('اعلان بازیابی شد');
    } catch {
      toast.error('بازیابی اعلان ناموفق بود');
    }
  };

  return (
    <section className="notification-center" aria-label="مرکز اعلان‌ها">
      <header className="notification-center-head">
        <div>
          <strong>اعلان‌ها</strong>
          <span>{meta.unread_count || 0} خوانده‌نشده</span>
        </div>
        {(meta.unread_count || 0) > 0 && (
          <button type="button" className="btn btn-sm btn-outline" onClick={markAllRead}><CheckCheck size={15} /> خواندن همه</button>
        )}
      </header>
      <div className="notification-center-tabs" role="tablist">
        <button type="button" className={tab === 'unread' ? 'active' : ''} onClick={() => setTab('unread')}>جدید</button>
        <button type="button" className={tab === 'all' ? 'active' : ''} onClick={() => setTab('all')}>همه</button>
        <button type="button" className={tab === 'archived' ? 'active' : ''} onClick={() => setTab('archived')}>آرشیو</button>
      </div>
      <div className="notification-center-list">
        {loading ? (
          Array.from({ length: 4 }).map((_, index) => <div key={index} className="skeleton notification-center-skeleton" />)
        ) : notifications.length === 0 ? (
          <div className="notification-center-empty"><Bell size={24} /><strong>اعلانی در این بخش نیست</strong></div>
        ) : visibleNotifications.map((notification) => (
          <NotificationRow
            key={notification.id}
            notification={notification}
            archived={tab === 'archived'}
            onOpen={openNotification}
            onRemove={(id) => setNotifications((current) => current.filter((item) => item.id !== id))}
            onRestore={restore}
          />
        ))}
      </div>
      {!loading && notifications.length > pageSize && (
        <div className="popover-pagination notification-pagination">
          <button type="button" disabled={page === 0} onClick={() => setPage((current) => Math.max(0, current - 1))}><ChevronRight size={16} /> قبلی</button>
          <span>{page + 1} از {pageCount}</span>
          <button type="button" disabled={page >= pageCount - 1} onClick={() => setPage((current) => Math.min(pageCount - 1, current + 1))}>بعدی <ChevronLeft size={16} /></button>
        </div>
      )}
      <footer className="notification-center-hint">برای آرشیو به راست و برای حذف به چپ بکشید؛ دکمه‌ها نیز همیشه در دسترس‌اند.</footer>
    </section>
  );
}
