"use client";

import { useEffect, useState, type ReactNode } from "react";
import DashboardLayout from "@/components/DashboardLayout";
import NotificationItem, {
  type NotificationsResponse,
} from "@/components/notifications/NotificationItem";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { refreshUnreadNotificationCount } from "@/lib/notifications/count";
import { toast } from "sonner";

const NOTIFICATION_SKELETON_KEYS = [
  "notification-skeleton-1",
  "notification-skeleton-2",
  "notification-skeleton-3",
  "notification-skeleton-4",
  "notification-skeleton-5",
] as const;

/** Skeleton rows for the loading state. */
function NotificationsSkeleton() {
  return (
    <div className="space-y-4">
      {NOTIFICATION_SKELETON_KEYS.map((skeletonKey) => (
        <div key={skeletonKey} className="p-5 rounded-2xl bg-[#1E2128] flex items-start gap-4 animate-pulse">
          <div className="w-12 h-12 rounded-xl bg-white/5 flex-shrink-0" />
          <div className="flex-1 min-w-0 pr-2">
            <div className="flex justify-between items-start mb-2">
              <div className="h-4 w-1/3 bg-white/10 rounded" />
              <div className="h-3 w-16 bg-white/5 rounded" />
            </div>
            <div className="space-y-2">
              <div className="h-3 w-full bg-white/5 rounded" />
              <div className="h-3 w-2/3 bg-white/5 rounded" />
            </div>
          </div>
          <div className="w-9 h-9 rounded-xl bg-white/5 flex-shrink-0" />
        </div>
      ))}
    </div>
  );
}

function renderNotificationsContent({
  loading,
  error,
  data,
  onDeleteOptimistic,
  onReadOptimistic,
}: {
  loading: boolean;
  error: string;
  data: NotificationsResponse["notifications"] | null;
  onDeleteOptimistic: (id: string) => void;
  onReadOptimistic: (id: string) => void;
}): ReactNode {
  if (loading) {
    return <NotificationsSkeleton />;
  }

  if (error) {
    return (
      <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-8 text-center">
        <i className="ri-error-warning-line text-red-400 text-3xl mb-3 block" />
        <p className="text-red-400 text-sm">{error}</p>
      </div>
    );
  }

  if (!data || data.data.length === 0) {
    return (
      <div className="bg-[#1E2128] rounded-2xl p-12 text-center">
        <i className="ri-notification-badge-line text-gray-600 text-5xl mb-4 block" />
        <p className="text-gray-400 text-sm">لا توجد إشعارات حالياً</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {data.data.map((notification) => (
        <NotificationItem
          key={notification.id}
          notification={notification}
          onDeleteOptimistic={onDeleteOptimistic}
          onReadOptimistic={onReadOptimistic}
        />
      ))}
    </div>
  );
}

export default function NotificationsPage() {
  const [data, setData] = useState<NotificationsResponse["notifications"] | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [page, setPage] = useState(1);

  const fetchNotifications = (pageNum: number) => {
    let active = true;
    setLoading(true);
    setError("");

    apiFetch<NotificationsResponse>(`/provider/notifications?page=${pageNum}`, {
      method: "GET",
      successCase: (res) => {
        if (active && res.data) {
          setData(res.data.notifications);
        }
      },
      errorCase: (res) => {
        if (active) {
          setError(formatApiMsg(res.msg) || "تعذّر تحميل الإشعارات، حاول مرة أخرى");
        }
      },
    }).finally(() => {
      if (active) setLoading(false);
    });

    return () => {
      active = false;
    };
  };

  // Initial fetch and on page change
  useEffect(() => {
    return fetchNotifications(page);
  }, [page]);

  // Actions
  const handleMarkAllRead = () => {
    // Button is disabled until data is loaded with unread items.
    const updatedData = { ...data! };
    updatedData.data = updatedData.data.map((item) => ({
      ...item,
      is_read: true,
    }));
    setData(updatedData);

    apiFetch("/provider/notifications/read-all", {
      method: "PATCH",
      successCase: () => {
        toast.success("تم تعليم الكل كمقروء");
        void refreshUnreadNotificationCount();
      },
      errorCase: (res) => {
        toast.error(formatApiMsg(res.msg) || "حدث خطأ أثناء التحديث");
        // Revert optimistic update by refetching
        fetchNotifications(page);
      },
    });
  };

  const handleDeleteAll = () => {
    // FLAG: The provided endpoint provider/delete-notification/{notification_id} is for a
    // single item. We don't have the correct delete-all endpoint.
    toast.error("لم يتم توفير الرابط الصحيح لحذف الكل من قِبل واجهة برمجة التطبيقات (API).", {
      duration: 5000,
    });
  };

  // Optimistic updates — only wired from rendered list items (data is non-null).
  const handleItemDeleted = (id: string) => {
    setData((current) => ({
      ...current!,
      data: current!.data.filter((item) => item.id !== id),
    }));
  };

  const handleItemRead = (id: string) => {
    setData((current) => ({
      ...current!,
      data: current!.data.map((item) =>
        item.id === id ? { ...item, is_read: true } : item,
      ),
    }));
  };

  const pagination = data?.pagination;
  const showPagination = pagination && pagination.total_pages > 1;

  // Unread count just for the header action button logic (optional, we can just check if any are unread)
  const hasUnread = data?.data.some(item => !item.is_read) ?? false;

  return (
    <DashboardLayout title="الإشعارات" subtitle="إدارة إشعارات النظام الخاصة بك">
      <div className="max-w-4xl mx-auto">
        {/* Header Actions */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <h2 className="text-white font-bold text-lg">أحدث الإشعارات</h2>
            {!loading && data?.pagination && (
              <span className="bg-white/5 text-gray-400 text-xs font-semibold px-2.5 py-1 rounded-md">
                {data.pagination.total_items}
              </span>
            )}
          </div>
          
          <div className="flex items-center gap-2">
            <button
              onClick={handleMarkAllRead}
              disabled={loading || !data || data.data.length === 0 || !hasUnread}
              className="flex items-center gap-2 px-4 py-2 bg-white/5 hover:bg-white/10 text-white rounded-xl text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i className="ri-check-double-line text-lg" />
              <span>تعليم الكل كمقروء</span>
            </button>
            <button
              onClick={handleDeleteAll}
              disabled={loading || !data || data.data.length === 0}
              className="flex items-center gap-2 px-4 py-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 rounded-xl text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i className="ri-delete-bin-line text-lg" />
              <span>حذف الكل</span>
            </button>
          </div>
        </div>

        {/* List Content */}
        {renderNotificationsContent({
          loading,
          error,
          data,
          onDeleteOptimistic: handleItemDeleted,
          onReadOptimistic: handleItemRead,
        })}

        {/* Pagination */}
        {showPagination && (
          <div className="flex items-center justify-between mt-8 p-4 bg-[#1E2128] rounded-2xl">
            <p className="text-gray-500 text-xs">
              إجمالي {pagination.total_items} إشعار
            </p>
            <div className="flex items-center gap-1">
              <button
                onClick={() => setPage(Math.max(1, page - 1))}
                disabled={pagination.current_page <= 1 || loading}
                className="w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 hover:bg-white/5 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                aria-label="الصفحة السابقة"
              >
                <i className="ri-arrow-right-s-line text-lg" />
              </button>
              
              {/* Pagination numbered buttons. 
                  Note: The total_pages in API might be large, so we cap displayed pages to max 5 around current 
              */}
              {Array.from(
                { length: Math.min(5, pagination.total_pages) },
                (_, i) => {
                  // Logic to center the current page
                  let startPage = Math.max(1, pagination.current_page - 2);
                  const endPage = Math.min(pagination.total_pages, startPage + 4);
                  if (endPage - startPage < 4) {
                    startPage = Math.max(1, endPage - 4);
                  }
                  return startPage + i;
                }
              ).map((p) => (
                <button
                  key={p}
                  onClick={() => setPage(p)}
                  disabled={loading}
                  className={`w-8 h-8 flex items-center justify-center rounded-lg text-sm font-medium transition-colors disabled:cursor-not-allowed ${
                    p === pagination.current_page
                      ? "bg-[#FCD704] text-[#13151A]"
                      : "text-gray-400 hover:bg-white/5 hover:text-white"
                  }`}
                >
                  {p}
                </button>
              ))}

              <button
                onClick={() => setPage(Math.min(pagination.total_pages, page + 1))}
                disabled={pagination.current_page >= pagination.total_pages || loading}
                className="w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 hover:bg-white/5 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                aria-label="الصفحة التالية"
              >
                <i className="ri-arrow-left-s-line text-lg" />
              </button>
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}
