'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import apis from '@/utils/apis';
import { Wrench, ShieldCheck } from 'lucide-react';
import dayjs from 'dayjs';

interface NotificationItem {
  _id?: string;
  id?: string;
  notification?: {
    title?: string;
    body?: string;
  };
  title?: string;
  body?: string;
  type?: string;
  createdAt?: string;
  created_at?: string;
}

const AnnouncementsSection = () => {
  const router = useRouter();
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const fetchedRef = React.useRef(false);

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;

    const fetchNotifications = async () => {
      setLoading(true);
      try {
        const res: any = await apis.NotificationVendor.listing('pageNumber=1&count=5');
        const list =
          res?.unread?.data ||
          res?.data?.unread?.data ||
          res?.data ||
          res?.read?.data ||
          [];
        setNotifications(Array.isArray(list) ? list.slice(0, 5) : []);
      } catch (error) {
        console.error('Error fetching notifications for announcements:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchNotifications();
  }, []);

  return (
    <div className="w-full bg-white rounded-2xl p-6 border border-[#F0F0F2] shadow-sm flex flex-col justify-between h-[440px]">
      <div className="flex flex-col h-full">
        {/* Header */}
        <div className="flex items-center justify-between pb-3 flex-shrink-0">
          <h3 className="text-base font-bold text-gray-900">Announcements</h3>
          <button
            type="button"
            onClick={() => router.push('/notifications/page/1')}
            className="text-xs font-semibold text-[#FF7400] hover:underline cursor-pointer"
          >
            View All
          </button>
        </div>

        <p className="text-xs font-semibold text-gray-700 mt-2 mb-4 flex-shrink-0">Today</p>

        {/* List Content */}
        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <div className="w-6 h-6 border-2 border-[var(--primary-brand)] border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : notifications.length === 0 ? (
          <div className="flex-1 flex items-center justify-center text-xs text-gray-400">
            No announcements yet
          </div>
        ) : (
          <div className="flex-1 overflow-y-auto pr-2 relative pl-6 space-y-6 custom-scrollbar">
            {/* Vertical timeline line */}
            <div className="absolute left-[17px] top-3 bottom-3 w-[1.5px] bg-gray-100" />

            {notifications.map((item: any, idx) => {
              const title = item.notification?.title || item.title || 'System Notification';
              const body = item.notification?.body || item.body || '';
              const timeStr = item.createdAt || item.created_at
                ? dayjs(item.createdAt || item.created_at).format('h:mm A')
                : '';

              const redirectPath =
                item?.data?.redirectPath ||
                item?.redirectPath ||
                item?.data?.redirect_path;
              const hasRedirect = Boolean(redirectPath && typeof redirectPath === 'string' && redirectPath.trim());

              const isPolicy =
                item.type === 'policy' ||
                title.toLowerCase().includes('policy') ||
                title.toLowerCase().includes('cancellation');

              const handleItemClick = () => {
                if (!hasRedirect || typeof redirectPath !== 'string') return;
                let targetPath = redirectPath.trim();
                if (targetPath.startsWith('orderDetail')) {
                  const queryString = targetPath.includes('?') ? targetPath.substring(targetPath.indexOf('?')) : '';
                  const params = new URLSearchParams(queryString);
                  const orderId = params.get('id') || params.get('order_id') || item?.data?.order_id;
                  targetPath = orderId ? `/orders/ongoing?id=${orderId}` : `/orders/ongoing`;
                } else if (!targetPath.startsWith('/')) {
                  targetPath = `/${targetPath}`;
                }
                router.push(targetPath);
              };

              return (
                <div
                  key={item._id || item.id || idx}
                  onClick={handleItemClick}
                  className={`relative flex items-start gap-3 ${
                    hasRedirect ? 'cursor-pointer hover:bg-slate-50/80 p-2 rounded-xl transition-all' : ''
                  }`}
                >
                  {/* Timeline Icon */}
                  <div
                    className={`absolute -left-[25px] top-0 w-8 h-8 rounded-full flex items-center justify-center border-2 border-white shadow-xs z-10 ${
                      isPolicy
                        ? 'bg-orange-50 text-orange-500'
                        : 'bg-sky-50 text-sky-500'
                    }`}
                  >
                    {isPolicy ? <ShieldCheck size={16} /> : <Wrench size={16} />}
                  </div>

                  <div className="pl-3 space-y-1">
                    <h4 className="text-xs font-bold text-gray-900 leading-snug">
                      {title}
                    </h4>
                    {body && (
                      <p className="text-xs text-gray-400 leading-relaxed max-w-[260px]">
                        {body}
                      </p>
                    )}
                    {timeStr && (
                      <p className="text-[11px] font-medium text-gray-400 pt-0.5">
                        {timeStr}
                      </p>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

export default AnnouncementsSection;
