import { AlertCircle, Bell, RefreshCcw } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import PwaMarkAllReadButton from './PwaMarkAllReadButton';
import PwaNotificationCard from './PwaNotificationCard';
import PwaNotificationDetailSheet from './PwaNotificationDetailSheet';
import PwaNotificationFilters, { getNotificationFilter } from './PwaNotificationFilters';
import { usePwaNotification } from './PwaNotificationProvider';
import { getPwaNotificationTarget } from './pwaNotificationUtils';
import { hasPermission } from './pwaTaskMeta';

export default function PwaNotificationsPage() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { notify, setUnreadCount, refreshUnreadCount } = usePwaNotification();
  const [notifications, setNotifications] = useState([]);
  const [filter, setFilter] = useState('all');
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState('');
  const [unread, setUnread] = useState(0);
  const [detail, setDetail] = useState(null);
  const canView = useMemo(() => hasPermission(user, 'notifications.view'), [user]);
  const activeFilter = getNotificationFilter(filter);

  const fetchNotifications = async (silent = false) => {
    if (silent) setRefreshing(true);
    else setLoading(true);
    setError('');
    try {
      const { data } = await api.get('/pwa/notifications', { params: { filter, per_page: 30 } });
      setNotifications(data.data || []);
      setUnread(data.meta?.unread_count || 0);
      setUnreadCount(data.meta?.unread_count || 0);
    } catch (err) {
      setError(err.response?.data?.message || 'خطا در دریافت اعلان‌ها. دوباره تلاش کنید.');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => { if (canView) fetchNotifications(); }, [canView, filter]);

  const replaceNotification = (next) => {
    setNotifications((current) => current.map((item) => item.id === next.id ? next : item));
  };

  const markRead = async (notification) => {
    if (notification.is_read || notification.read_at) return notification;
    const { data } = await api.patch(`/pwa/notifications/${notification.id}/read`);
    replaceNotification(data.data);
    setUnread(data.meta?.unread_count || 0);
    setUnreadCount(data.meta?.unread_count || 0);
    return data.data;
  };

  const openNotification = async (notification) => {
    let nextNotification = notification;
    try {
      nextNotification = await markRead(notification);
    } catch {
      notify({ tone: 'error', title: 'اعلان', message: 'اعلان خوانده نشد.' });
    }

    setDetail(nextNotification);
  };

  const markUnread = async (notification) => {
    try {
      const { data } = await api.patch(`/pwa/notifications/${notification.id}/unread`);
      replaceNotification(data.data);
      setUnread(data.meta?.unread_count || 0);
      setUnreadCount(data.meta?.unread_count || 0);
    } catch (err) {
      notify({ tone: 'error', title: 'اعلان', message: err.response?.data?.message || 'تغییر وضعیت اعلان انجام نشد.' });
    }
  };

  const removeFromList = (notification) => {
    setNotifications((current) => current.filter((item) => item.id !== notification.id));
  };

  const archiveNotification = async (notification) => {
    removeFromList(notification);
    try {
      await api.patch(`/notifications/${notification.id}/archive`);
      refreshUnreadCount();
      notify({ tone: 'success', title: 'اعلان', message: 'اعلان آرشیو شد.' });
    } catch (err) {
      notify({ tone: 'error', title: 'اعلان', message: err.response?.data?.message || 'آرشیو اعلان انجام نشد.' });
      fetchNotifications(true);
    }
  };

  const deleteNotification = async (notification) => {
    removeFromList(notification);
    try {
      await api.delete(`/notifications/${notification.id}`);
      refreshUnreadCount();
      notify({ tone: 'success', title: 'اعلان', message: 'اعلان حذف شد.' });
    } catch (err) {
      notify({ tone: 'error', title: 'اعلان', message: err.response?.data?.message || 'حذف اعلان انجام نشد.' });
      fetchNotifications(true);
    }
  };

  const markAllRead = async () => {
    try {
      await api.patch('/pwa/notifications/read-all');
      setNotifications((current) => current.map((item) => ({ ...item, is_read: true, read_at: item.read_at || new Date().toISOString() })));
      setUnread(0);
      setUnreadCount(0);
      refreshUnreadCount();
      notify({ tone: 'success', title: 'اعلان‌ها', message: 'همه اعلان‌ها خوانده شدند.' });
    } catch (err) {
      notify({ tone: 'error', title: 'اعلان‌ها', message: err.response?.data?.message || 'خواندن همه اعلان‌ها انجام نشد.' });
    }
  };

  if (!canView) {
    return (
      <section className="pwa-state-card error">
        <AlertCircle size={28} />
        <strong>شما مجوز مشاهده اعلان‌ها را ندارید.</strong>
      </section>
    );
  }

  return (
    <div className="pwa-notifications-page">
      <section className="pwa-page-actions">
        <div className="pwa-notification-head-actions">
          <button type="button" onClick={() => fetchNotifications(true)} disabled={refreshing}><RefreshCcw size={16} /></button>
          <PwaMarkAllReadButton disabled={!unread} onClick={markAllRead} />
        </div>
      </section>

      <PwaNotificationFilters value={filter} onChange={setFilter} />

      {loading ? (
        <div className="pwa-notification-list">
          {[1, 2, 3, 4].map((item) => <div className="pwa-skeleton notification-card" key={item} />)}
        </div>
      ) : error ? (
        <section className="pwa-state-card error">
          <AlertCircle size={28} />
          <strong>{error}</strong>
          <button type="button" onClick={() => fetchNotifications()}>تلاش دوباره</button>
        </section>
      ) : notifications.length ? (
        <div className="pwa-notification-list">
          {notifications.map((notification) => (
            <PwaNotificationCard
              key={notification.id}
              notification={notification}
              onOpen={openNotification}
              onToggleUnread={markUnread}
              onArchive={archiveNotification}
              onDelete={deleteNotification}
            />
          ))}
        </div>
      ) : (
        <section className="pwa-empty-card">
          <Bell size={28} />
          <strong>{activeFilter.empty}</strong>
        </section>
      )}

      <PwaNotificationDetailSheet
        notification={detail}
        onClose={() => setDetail(null)}
        onNavigate={() => {
          const target = getPwaNotificationTarget(detail);
          if (target.available && target.path) {
            setDetail(null);
            navigate(target.path);
          } else {
            notify({ tone: 'error', title: 'اعلان', message: 'مورد مربوط به این اعلان در دسترس نیست.' });
          }
        }}
      />
    </div>
  );
}
