'use client';

import Link from 'next/link';
import { useEffect, useMemo, useRef, useState } from 'react';
import DashboardShell from '../components/DashboardShell';
import { useApi } from '@/hooks/useApi';
import {
  getDashboardNotificationHref,
  isDashboardNotificationUnread,
} from '@/app/dashboard/notificationRoutes';
import { Skeleton } from 'primereact/skeleton';
import { Paginator, type PaginatorPageChangeEvent } from 'primereact/paginator';
import { AppToast } from '@/app/components/AppToast';
import type { Toast } from 'primereact/toast';
import { Dialog } from 'primereact/dialog';

type NotificationRaw = {
  id?: number | string;
  type?: string;
  title?: string;
  message?: string;
  body?: string;
  description?: string;
  created_at?: string;
  time_ago?: string;
  created_at_human?: string;
  is_read?: boolean;
  read?: boolean | number;
  unread?: boolean;
};

type PaginationMeta = {
  current_page?: number;
  total_items?: number;
  per_page?: number;
  total_pages?: number;
};

type NotificationsResponse = {
  data?: {
    data?: NotificationRaw[];
    pagination?: PaginationMeta;
  };
};

type ActionResponse = {
  msg?: string;
  message?: string;
};

type NotificationUi = {
  id: number | string;
  text: string;
  time: string;
  unread: boolean;
  href: string | null;
};

const PAGE_SIZE = 20;

function mapNotification(item: NotificationRaw, index: number): NotificationUi {
  return {
    id: item.id ?? `row-${index}`,
    text: item.title ?? item.message ?? item.body ?? item.description ?? 'إشعار جديد',
    time: item.time_ago ?? item.created_at_human ?? item.created_at ?? '—',
    unread: isDashboardNotificationUnread(item),
    href: getDashboardNotificationHref(item.type),
  };
}

function NotificationSkeletonRow() {
  return (
    <div className="bg-white rounded-2xl p-4 flex items-start gap-4" style={{ border: '1px solid #F1F5F9' }}>
      <Skeleton width="2.5rem" height="2.5rem" borderRadius="12px" />
      <div className="flex-1 space-y-2">
        <Skeleton width="85%" height="0.95rem" borderRadius="6px" />
        <Skeleton width="98%" height="0.75rem" borderRadius="6px" />
        <Skeleton width="40%" height="0.65rem" borderRadius="6px" />
      </div>
      <Skeleton width="2rem" height="2rem" borderRadius="10px" />
    </div>
  );
}

export default function DashboardNotificationsPage() {
  const toastRef = useRef<Toast>(null);
  const [page, setPage] = useState(1);
  const [deleteOneTarget, setDeleteOneTarget] = useState<number | string | null>(null);
  const [showDeleteAllDialog, setShowDeleteAllDialog] = useState(false);

  const listApi = useApi<NotificationsResponse>();
  const deleteOneApi = useApi<ActionResponse, { id: number | string }>();
  const deleteAllApi = useApi<ActionResponse>();

  const notifications = useMemo(() => {
    const rows = listApi.data?.data?.data;
    return Array.isArray(rows) ? rows.map(mapNotification) : [];
  }, [listApi.data]);

  const pagination = listApi.data?.data?.pagination;
  const totalItems = pagination?.total_items ?? 0;
  const perPage = pagination?.per_page ?? PAGE_SIZE;
  const currentPage = pagination?.current_page ?? page;

  const fetchNotifications = (targetPage = 1) => {
    listApi.request(`/account/notifications?paginate=${PAGE_SIZE}&page=${targetPage}`);
  };

  useEffect(() => {
    listApi.request(`/account/notifications?paginate=${PAGE_SIZE}&page=${page}`);
  }, [listApi.request, page]);

  const showSuccess = (message: string) => {
    toastRef.current?.show({
      severity: 'success',
      summary: 'تم بنجاح',
      detail: message,
      life: 2500,
    });
  };

  const showError = (message: string) => {
    toastRef.current?.show({
      severity: 'error',
      summary: 'حدث خطأ',
      detail: message,
      life: 3000,
    });
  };

  const handleDeleteOne = async (id: number | string) => {
    const response = await deleteOneApi.request('/account/notifications/delete', {
      method: 'DELETE',
      body: { id },
    });

    if (!response) {
      showError(deleteOneApi.lastError.current ?? 'تعذر حذف الإشعار.');
      return;
    }

    showSuccess(response.msg ?? response.message ?? 'تم حذف الإشعار.');
    setDeleteOneTarget(null);
    fetchNotifications(currentPage);
  };

  const handleDeleteAll = async () => {
    const response = await deleteAllApi.request('/account/notifications/delete-all', {
      method: 'DELETE',
    });

    if (!response) {
      showError(deleteAllApi.lastError.current ?? 'تعذر حذف جميع الإشعارات.');
      return;
    }

    showSuccess(response.msg ?? response.message ?? 'تم حذف جميع الإشعارات.');
    setShowDeleteAllDialog(false);
    setPage(1);
    fetchNotifications(1);
  };

  const onPaginatorChange = (event: PaginatorPageChangeEvent) => {
    setPage(event.page + 1);
  };

  return (
    <DashboardShell title="الإشعارات" subtitle="عرض وإدارة جميع الإشعارات">
      <AppToast ref={toastRef} position="top-right" />
      <Dialog
        header="تأكيد حذف الإشعار"
        visible={deleteOneTarget !== null}
        onHide={() => {
          if (!deleteOneApi.loading) setDeleteOneTarget(null);
        }}
        style={{ width: '28rem' }}
        draggable={false}
        resizable={false}
      >
        <div className="space-y-5" dir="rtl">
          <p className="text-sm text-slate-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
            هل تريد حذف هذا الإشعار؟ لا يمكن التراجع بعد التنفيذ.
          </p>
          <div className="flex items-center justify-end gap-2">
            <button
              onClick={() => setDeleteOneTarget(null)}
              disabled={deleteOneApi.loading}
              className="px-4 py-2 rounded-xl text-sm font-bold cursor-pointer"
              style={{ background: '#F8FAFC', color: '#475569', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            >
              إلغاء
            </button>
            <button
              onClick={() => {
                if (deleteOneTarget !== null) handleDeleteOne(deleteOneTarget);
              }}
              disabled={deleteOneApi.loading}
              className="px-4 py-2 rounded-xl text-sm font-bold cursor-pointer"
              style={{ background: '#FEE2E2', color: '#DC2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            >
              {deleteOneApi.loading ? 'جاري الحذف...' : 'تأكيد الحذف'}
            </button>
          </div>
        </div>
      </Dialog>

      <Dialog
        header="تأكيد حذف جميع الإشعارات"
        visible={showDeleteAllDialog}
        onHide={() => {
          if (!deleteAllApi.loading) setShowDeleteAllDialog(false);
        }}
        style={{ width: '30rem' }}
        draggable={false}
        resizable={false}
      >
        <div className="space-y-5" dir="rtl">
          <p className="text-sm text-slate-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
            هل تريد حذف جميع الإشعارات؟ هذا الإجراء نهائي ولا يمكن التراجع عنه.
          </p>
          <div className="flex items-center justify-end gap-2">
            <button
              onClick={() => setShowDeleteAllDialog(false)}
              disabled={deleteAllApi.loading}
              className="px-4 py-2 rounded-xl text-sm font-bold cursor-pointer"
              style={{ background: '#F8FAFC', color: '#475569', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            >
              إلغاء
            </button>
            <button
              onClick={handleDeleteAll}
              disabled={deleteAllApi.loading}
              className="px-4 py-2 rounded-xl text-sm font-bold cursor-pointer"
              style={{ background: '#FEE2E2', color: '#DC2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            >
              {deleteAllApi.loading ? 'جاري الحذف...' : 'تأكيد حذف الكل'}
            </button>
          </div>
        </div>
      </Dialog>

      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="w-11 h-11 rounded-2xl flex items-center justify-center" style={{ background: '#EEF2FF' }}>
            <i className="ri-notification-3-fill text-xl" style={{ color: '#1E3A8A' }}></i>
          </div>
          <div>
            <p className="text-2xl font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{totalItems}</p>
            <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إجمالي الإشعارات</p>
          </div>
        </div>

        <button
          onClick={() => setShowDeleteAllDialog(true)}
          disabled={deleteAllApi.loading || notifications.length === 0}
          className="px-4 py-2 rounded-xl text-sm font-bold cursor-pointer transition-opacity"
          style={{
            background: '#FEE2E2',
            color: '#DC2626',
            fontFamily: '"IBM Plex Sans Arabic", sans-serif',
            opacity: deleteAllApi.loading || notifications.length === 0 ? 0.5 : 1,
          }}
        >
          {deleteAllApi.loading ? 'جاري الحذف...' : 'حذف الكل'}
        </button>
      </div>

      <div className="space-y-3">
        {listApi.loading
          ? Array.from({ length: 6 }).map((_, i) => <NotificationSkeletonRow key={`sk-${i}`} />)
          : notifications.length > 0
            ? notifications.map((notification) => {
                const bodyBlock = (
                  <>
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#EEF2FF' }}>
                      <i className="ri-notification-3-fill text-base" style={{ color: '#1E3A8A' }}></i>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <p className="text-sm font-black text-slate-900 leading-relaxed" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          {notification.text}
                        </p>
                        {notification.unread && <span className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: '#2563EB' }}></span>}
                      </div>
                      <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{notification.time}</p>
                    </div>
                  </>
                );

                return (
                  <div
                    key={String(notification.id)}
                    className="bg-white rounded-2xl p-5 flex items-start gap-4"
                    style={{
                      border: `1px solid ${notification.unread ? '#BFDBFE' : '#E2E8F0'}`,
                      background: notification.unread ? '#FAFEFF' : 'white',
                      boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
                    }}
                  >
                    {notification.href ? (
                      <Link
                        href={notification.href}
                        className="flex flex-1 min-w-0 items-start gap-4 no-underline text-inherit rounded-xl -m-1 p-1 transition-colors hover:bg-slate-50/80"
                      >
                        {bodyBlock}
                      </Link>
                    ) : (
                      <div className="flex flex-1 min-w-0 items-start gap-4">{bodyBlock}</div>
                    )}
                    <button
                      type="button"
                      onClick={() => setDeleteOneTarget(notification.id)}
                      disabled={deleteOneApi.loading}
                      className="w-9 h-9 rounded-xl flex items-center justify-center cursor-pointer transition-colors hover:bg-red-50 flex-shrink-0"
                      style={{ border: '1px solid #FECACA' }}
                      aria-label="حذف الإشعار"
                    >
                      <i className="ri-delete-bin-line text-red-500 text-base"></i>
                    </button>
                  </div>
                );
              })
            : (
              <div className="bg-white rounded-2xl py-16 flex flex-col items-center justify-center" style={{ border: '1px solid #F1F5F9' }}>
                <div className="w-16 h-16 rounded-2xl flex items-center justify-center mb-3" style={{ background: '#F1F5F9' }}>
                  <i className="ri-notification-off-line text-2xl text-slate-400"></i>
                </div>
                <p className="text-sm font-bold text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لا توجد إشعارات حالياً</p>
              </div>
            )}
      </div>

      {!listApi.loading && totalItems > 0 && (
        <div className="bg-white rounded-2xl mt-5 p-3" style={{ border: '1px solid #F1F5F9' }}>
          <Paginator
            first={(currentPage - 1) * perPage}
            rows={perPage}
            totalRecords={totalItems}
            onPageChange={onPaginatorChange}
            template="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink"
          />
        </div>
      )}
    </DashboardShell>
  );
}
