'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { useApi } from '@/hooks/useApi';
import { useAuthStore } from '@/store/authStore';
import { Skeleton } from 'primereact/skeleton';
import {
  getDashboardNotificationHref,
  isDashboardNotificationUnread,
} from '@/app/dashboard/notificationRoutes';

interface NotificationApiItem {
  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;
}

interface NotificationsApiResponse {
  data?: {
    data?: NotificationApiItem[];
  };
}

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

function extractItems(payload: NotificationsApiResponse | null): NotificationApiItem[] {
  const source = payload?.data?.data;
  return Array.isArray(source) ? source : [];
}

function toUi(item: NotificationApiItem, index: number): NotificationUi {
  const id = item.id != null ? String(item.id) : `notif-${index}`;
  const text = item.title ?? item.message ?? item.body ?? item.description ?? 'إشعار جديد';
  const time = item.time_ago ?? item.created_at_human ?? item.created_at ?? '';
  const unread = isDashboardNotificationUnread(item);
  const href = getDashboardNotificationHref(item.type);
  return { id, text, time, unread, href };
}

export default function DashboardTopBar({ title, subtitle }: { title: string; subtitle?: string }) {
  const [showNotif, setShowNotif] = useState(false);
  const { request, loading, data } = useApi<NotificationsApiResponse>();
  const user = useAuthStore((s) => s.user);
  const allItems = useMemo(() => extractItems(data), [data]);
  const notifs = useMemo(() => allItems.slice(0, 4).map(toUi), [allItems]);
  /** من قائمة الإشعارات فقط — لا نستدعي count-unread حتى لا يعلّم السيرفر مقروء بدون مشاهدة */
  const unreadCount = useMemo(
    () => allItems.filter(isDashboardNotificationUnread).length,
    [allItems],
  );
  const unreadBadgeLabel = unreadCount > 99 ? '99+' : String(unreadCount);
  const companyName = user?.companyName || user?.name || '—';
  const companyImage = user?.image || user?.avatar || '';

  useEffect(() => {
    request('/account/notifications?paginate=20');
  }, [request]);

  return (
    <header
      className="flex items-center justify-between px-8 border-b"
      style={{ height: '72px', background: 'white', borderColor: '#E2E8F0' }}
      dir="rtl"
    >
      <div>
        <h1 className="text-xl font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{title}</h1>
        {subtitle && <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{subtitle}</p>}
      </div>

      <div className="flex items-center gap-3">
        {/* Search */}
        {/* <div className="relative">
          <input
            type="text"
            placeholder="بحث..."
            className="h-9 bg-slate-50 border border-slate-200 rounded-xl pr-9 pl-4 text-sm outline-none text-slate-700"
            style={{ width: '200px', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
          />
          <div className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center">
            <i className="ri-search-line text-slate-400 text-sm"></i>
          </div>
        </div> */}

        {/* Notifications */}
        <div className="relative">
          <button
            onClick={() => setShowNotif(!showNotif)}
            className="relative w-9 h-9 bg-slate-50 border border-slate-200 rounded-xl flex items-center justify-center cursor-pointer"
          >
            <i className="ri-notification-3-line text-slate-600 text-lg"></i>
            <span
              className="absolute -top-1.5 -right-1.5 min-w-[1.125rem] h-[1.125rem] px-0.5 rounded-full text-[10px] leading-none font-bold flex items-center justify-center tabular-nums"
              style={{
                background: unreadCount > 0 ? '#EF4444' : '#94A3B8',
                color: '#FFFFFF',
              }}
            >
              {unreadBadgeLabel}
            </span>
          </button>

          {showNotif && (
            <div
              className="absolute top-12 left-0 bg-white rounded-2xl shadow-2xl z-50 overflow-hidden"
              style={{ width: '320px', border: '1px solid #E2E8F0' }}
            >
              <div className="flex items-center justify-between px-4 py-3 border-b" style={{ borderColor: '#F1F5F9' }}>
                <span className="font-bold text-slate-800 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>الإشعارات</span>
                <Link href="/dashboard/notifications" className="text-xs font-semibold cursor-pointer" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  عرض الكل
                </Link>
              </div>
              <div className="divide-y divide-[#F8FAFC]">
                {loading
                  ? Array.from({ length: 4 }).map((_, i) => (
                      <div key={`s-${i}`} className="flex items-start gap-3 px-4 py-3">
                        <Skeleton width="2.25rem" height="2.25rem" borderRadius="10px" />
                        <div className="flex-1 space-y-2">
                          <Skeleton width="95%" height="0.75rem" />
                          <Skeleton width="40%" height="0.6rem" />
                        </div>
                      </div>
                    ))
                  : notifs.length > 0
                    ? notifs.map((n) => {
                        const rowClass =
                          'flex items-start gap-3 px-4 py-3 transition-colors' +
                          (n.href ? ' cursor-pointer hover:bg-slate-50' : '');

                        const inner = (
                          <>
                            <div className="w-9 h-9 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">
                              <p className="text-xs text-slate-700 leading-relaxed" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{n.text}</p>
                              <p className="text-[10px] text-slate-400 mt-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{n.time || '—'}</p>
                            </div>
                            {n.unread && <span className="w-2 h-2 rounded-full mt-1 flex-shrink-0" style={{ background: '#1E3A8A' }}></span>}
                          </>
                        );

                        return (
                          <div key={n.id}>
                            {n.href ? (
                              <Link
                                href={n.href}
                                onClick={() => setShowNotif(false)}
                                className={`${rowClass} no-underline text-inherit block`}
                              >
                                {inner}
                              </Link>
                            ) : (
                              <div className={rowClass}>{inner}</div>
                            )}
                          </div>
                        );
                      })
                    : (
                      <p className="px-4 py-6 text-center text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        لا توجد إشعارات حالياً
                      </p>
                    )}
              </div>
            </div>
          )}
        </div>

        {/* Profile */}
        <div className="flex items-center gap-2 cursor-pointer">
          {companyImage ? (
            <img
              src={companyImage}
              alt={companyName}
              className="w-9 h-9 rounded-xl overflow-hidden flex-shrink-0 object-cover"
            />
          ) : (
            <div className="w-9 h-9 rounded-xl overflow-hidden flex-shrink-0 bg-slate-200" />
          )}
          <div className="hidden md:block">
            <p className="text-xs font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{companyName}</p>
            <p className="text-[10px] text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>شركة</p>
          </div>
        </div>
      </div>
    </header>
  );
}
