'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { api, apiPaths } from '@/lib/api';
import { useAuthGuard } from '@/lib/useAuthGuard';

type Notification = {
  /** Laravel notifications تستخدم UUID نصي */
  id: string | number;
  title: string;
  message: string;
  created_at?: string;
  is_read?: boolean | number;
  /** يطابق قيم `NotificationTypeEnum` في الباكند */
  type?: string;
  /** مسار Next.js للتوجيه عند الضغط (من `UserNotificationActionPath` في الـ API) */
  action_path?: string | null;
};

/** Laravel NotificationsCollection wraps items in { pagination, data: [...] } */
function parseNotificationsList(raw: unknown): Notification[] {
  if (Array.isArray(raw)) {
    return raw.map(normalizeNotificationRow);
  }
  if (raw && typeof raw === 'object' && 'data' in raw && Array.isArray((raw as { data: unknown }).data)) {
    return (raw as { data: unknown[] }).data.map(normalizeNotificationRow);
  }
  return [];
}

function normalizeNotificationRow(row: unknown): Notification {
  const n = row as Record<string, unknown>;
  const id = n.id != null ? String(n.id) : '';
  const body = n.body ?? n.message;
  const rawRead = n.is_read;
  const ap = n.action_path;
  return {
    id,
    title: String(n.title ?? ''),
    message: typeof body === 'string' ? body : '',
    created_at: typeof n.created_at === 'string' ? n.created_at : undefined,
    is_read: rawRead === undefined ? false : Boolean(rawRead),
    type: typeof n.type === 'string' ? n.type : undefined,
    action_path: typeof ap === 'string' && ap.startsWith('/') ? ap : null,
  };
}

export default function NotificationsPage() {
  const router = useRouter();
  const { checked, authenticated } = useAuthGuard();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState('الكل');

  const fetchNotifications = async () => {
    setLoading(true);
    const res = await api.get<{ notifications?: unknown }>(apiPaths.user.notifications);
    if (res.key === 'success' && res.data) {
      const payload = res.data as { notifications?: unknown };
      const list = parseNotificationsList(payload.notifications);
      setNotifications(list);
    }
    setLoading(false);
  };

  useEffect(() => {
    if (!authenticated) return;
    fetchNotifications();
  }, [authenticated]);

  if (!checked) return null;

  const list = Array.isArray(notifications) ? notifications : [];
  const unreadCount = list.filter((n) => !n.is_read).length;

  const filteredNotifications = list.filter((n) => {
    if (filterType === 'الكل') return true;
    if (filterType === 'غير مقروءة') return !n.is_read;
    return true;
  });

  const markAllAsRead = async () => {
    await api.patch(apiPaths.user.notificationSwitch);
    fetchNotifications();
  };

  const handleDelete = async (id: string | number, e?: React.MouseEvent) => {
    e?.stopPropagation();
    await api.delete(apiPaths.user.deleteNotification(String(id)));
    setNotifications((prev) => prev.filter((n) => n.id !== id));
  };

  const goToNotificationTarget = (n: Notification) => {
    if (n.action_path) {
      router.push(n.action_path);
    }
  };

  const filterOptions = ['الكل', 'غير مقروءة'];

  return (
    <div dir="rtl" className="flex flex-col flex-1 bg-gradient-to-br from-blue-50 via-white to-gray-50">
      <main className="max-w-4xl mx-auto px-6 py-10 flex-1 w-full">
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-4">
            <Link href="/" className="w-10 h-10 flex items-center justify-center bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer">
              <i className="ri-arrow-right-line text-xl text-gray-700"></i>
            </Link>
            <div>
              <h1 className="text-3xl font-bold text-gray-900">الإشعارات</h1>
              <p className="text-gray-500 mt-1">
                {unreadCount > 0 ? `لديك ${unreadCount} إشعارات غير مقروءة` : 'جميع الإشعارات مقروءة'}
              </p>
            </div>
          </div>
          {unreadCount > 0 && (
            <button
              onClick={markAllAsRead}
              className="flex items-center gap-2 px-4 py-2 text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors cursor-pointer whitespace-nowrap text-sm font-semibold"
            >
              <i className="ri-check-double-line text-lg"></i>
              <span>تحديد الكل كمقروء</span>
            </button>
          )}
        </div>

        {/* Filter Tabs */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-6">
          <div className="flex items-center gap-3 flex-wrap">
            {filterOptions.map((option) => (
              <button
                key={option}
                onClick={() => setFilterType(option)}
                className={`px-4 py-2 rounded-full text-sm font-semibold transition-colors cursor-pointer whitespace-nowrap ${filterType === option ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
              >
                {option}
              </button>
            ))}
          </div>
        </div>

        {/* Notifications List */}
        {loading ? (
          <div className="flex justify-center py-16">
            <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : (
          <div className="space-y-3">
            {filteredNotifications.map((notification) => (
              <div
                key={notification.id}
                role={notification.action_path ? 'button' : undefined}
                tabIndex={notification.action_path ? 0 : undefined}
                onClick={() => goToNotificationTarget(notification)}
                onKeyDown={(e) => {
                  if (notification.action_path && (e.key === 'Enter' || e.key === ' ')) {
                    e.preventDefault();
                    goToNotificationTarget(notification);
                  }
                }}
                className={`bg-white rounded-xl shadow-sm border p-5 transition-all text-right w-full ${
                  notification.action_path
                    ? 'cursor-pointer hover:shadow-md hover:border-blue-200'
                    : 'cursor-default'
                } ${!notification.is_read ? 'border-blue-200 bg-blue-50/30' : 'border-gray-100 hover:border-gray-200'}`}
              >
                <div className="flex items-start gap-4">
                  <div className="w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0 bg-blue-100 text-blue-600">
                    <i className="ri-notification-3-line text-2xl"></i>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-1">
                      <h3 className={`text-base font-bold ${!notification.is_read ? 'text-gray-900' : 'text-gray-700'}`}>
                        {notification.title}
                      </h3>
                      {!notification.is_read && (
                        <span className="w-2.5 h-2.5 bg-blue-600 rounded-full flex-shrink-0"></span>
                      )}
                    </div>
                    <p className="text-gray-600 text-sm leading-relaxed mb-3">{notification.message}</p>
                    {notification.created_at && (
                      <span className="text-xs text-gray-400 flex items-center gap-1">
                        <i className="ri-calendar-line w-3.5 h-3.5 flex items-center justify-center"></i>
                        {notification.created_at}
                      </span>
                    )}
                    {notification.action_path && (
                      <span className="text-xs text-blue-600 mt-2 inline-flex items-center gap-1 font-semibold">
                        <i className="ri-arrow-left-line"></i>
                        اضغط للانتقال
                      </span>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={(e) => handleDelete(notification.id, e)}
                    className="text-red-400 hover:text-red-600 transition-colors cursor-pointer p-1 z-10"
                    title="حذف الإشعار"
                  >
                    <i className="ri-delete-bin-line text-lg"></i>
                  </button>
                </div>
              </div>
            ))}

            {filteredNotifications.length === 0 && (
              <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-16 text-center">
                <div className="w-20 h-20 flex items-center justify-center bg-gray-100 rounded-full mx-auto mb-4">
                  <i className="ri-notification-off-line text-3xl text-gray-400"></i>
                </div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">لا توجد إشعارات</h3>
                <p className="text-gray-500">لا توجد إشعارات حالياً</p>
              </div>
            )}
          </div>
        )}
      </main>
    </div>
  );
}
