'use client';
import { useState, useRef, useEffect } from 'react';
import { useLeaveStore } from './leaveStore';
import { useTrainingStore } from './trainingStore';
import { useAuth } from './authContext';
import { initialAppraisals } from '../app/hr/performance/performanceData';

interface NotifItem {
  id: string;
  title: string;
  desc: string;
  time: string;
  read: boolean;
}

export default function NotificationBell() {
  const { user } = useAuth();
  const { requests } = useLeaveStore();
  const { trainingReqs } = useTrainingStore();
  const [open, setOpen] = useState(false);
  const [readIds, setReadIds] = useState<Set<string>>(new Set());
  const [todayStr, setTodayStr] = useState('');
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  useEffect(() => {
    setTodayStr(new Date().toISOString().split('T')[0]);
  }, []);

  if (!user) return null;

  const notifs: NotifItem[] = [];

  if (user.role === 'hod') {
    const pending = requests.filter(r => r.dept === user.dept && r.status === 'Pending');
    pending.forEach(r => notifs.push({
      id: `leave-${r.id}`,
      title: 'Leave Request Pending',
      desc: `${r.employee} submitted a ${r.days}-day leave request`,
      time: r.submittedOn,
      read: readIds.has(`leave-${r.id}`),
    }));
    const myApproved = requests.filter(r => {
      const hodId = `HOD-${user.id}`;
      return r.employeeId === hodId && (r.status === 'Approved' || r.status === 'Rejected');
    });
    myApproved.forEach(r => notifs.push({
      id: `myLeave-${r.id}`,
      title: r.status === 'Approved' ? 'Leave Approved' : 'Leave Rejected',
      desc: `Your leave request has been ${r.status.toLowerCase()} by HR`,
      time: r.approvedOn || r.submittedOn,
      read: readIds.has(`myLeave-${r.id}`),
    }));
  }

  if (user.role === 'hos') {
    const pending = requests.filter(r => r.status === 'HOD Approved');
    pending.forEach(r => notifs.push({
      id: `hos-leave-${r.id}`,
      title: 'HOD-Approved Leave Awaiting Review',
      desc: `${r.employee} (${r.dept}) — ${r.days} day(s) leave`,
      time: r.hodApprovedOn || r.submittedOn,
      read: readIds.has(`hos-leave-${r.id}`),
    }));
    const pendingTraining = trainingReqs.filter(r => r.currentStage === 'HOS');
    pendingTraining.forEach(r => notifs.push({
      id: `hos-train-${r.id}`,
      title: 'Training Request Awaiting Review',
      desc: `${r.employeeName} — ${r.courseRequested}`,
      time: r.dateSubmitted,
      read: readIds.has(`hos-train-${r.id}`),
    }));
  }

  if (user.role === 'hr' || user.role === 'admin') {
    const pending = requests.filter(r => r.status === 'HOS Approved');
    pending.forEach(r => notifs.push({
      id: `hr-leave-${r.id}`,
      title: 'Leave Awaiting Final Approval',
      desc: `${r.employee} (${r.dept}) — HOS approved, needs HR final`,
      time: r.hosApprovedOn || r.submittedOn,
      read: readIds.has(`hr-leave-${r.id}`),
    }));
    const pendingTraining = trainingReqs.filter(r => r.currentStage === 'HR');
    pendingTraining.forEach(r => notifs.push({
      id: `hr-train-${r.id}`,
      title: 'Training Request Pending',
      desc: `${r.employeeName} — ${r.courseRequested}`,
      time: r.dateSubmitted,
      read: readIds.has(`hr-train-${r.id}`),
    }));
  }

  if (user.role === 'finance') {
    const pendingTraining = trainingReqs.filter(r => r.currentStage === 'Finance');
    pendingTraining.forEach(r => notifs.push({
      id: `fin-train-${r.id}`,
      title: 'Training Budget Awaiting Approval',
      desc: `${r.employeeName} — KES ${r.estimatedCost?.toLocaleString() || '0'}`,
      time: r.dateSubmitted,
      read: readIds.has(`fin-train-${r.id}`),
    }));
  }

  if (user.role === 'employee' || user.role === 'intern') {
    const myReqs = requests.filter(r => r.employeeId === user.employeeId);
    myReqs.forEach(r => {
      if (r.status === 'Approved') notifs.push({
        id: `emp-${r.id}`,
        title: 'Leave Approved',
        desc: `Your ${r.days}-day leave has been fully approved`,
        time: r.approvedOn || r.submittedOn,
        read: readIds.has(`emp-${r.id}`),
      });
      if (r.status === 'Rejected') notifs.push({
        id: `emp-rej-${r.id}`,
        title: 'Leave Rejected',
        desc: `Your leave request was rejected: ${r.rejectionReason || 'See details'}`,
        time: r.submittedOn,
        read: readIds.has(`emp-rej-${r.id}`),
      });
      if (r.status === 'Pending' && r.reviewRequested) notifs.push({
        id: `emp-review-${r.id}`,
        title: 'Review Requested',
        desc: `Your leave request requires changes. Review: ${r.reviewComment?.slice(0, 60) || 'See details'}`,
        time: r.submittedOn,
        read: readIds.has(`emp-review-${r.id}`),
      });
      // Stage sent notifications
      const stageMsgs: Record<string, string> = {
        'Pending': 'Your request has been successfully sent to your HOD for approval.',
        'HOD Approved': 'Your leave has been approved by your HOD and forwarded to HOS.',
        'HOS Approved': 'Your leave has been approved by HOS and forwarded to HR for final approval.',
      };
      if (r.status in stageMsgs) notifs.push({
        id: `emp-stage-${r.status}-${r.id}`,
        title: 'Request Update',
        desc: stageMsgs[r.status],
        time: r.hodApprovedOn || r.hosApprovedOn || r.submittedOn,
        read: readIds.has(`emp-stage-${r.status}-${r.id}`),
      });
    });

    // Training request stage notifications
    const myTraining = trainingReqs.filter(r => r.employeeId === user.employeeId);
    myTraining.forEach(r => {
      if (r.status === 'Submitted' || r.currentStage === 'HR') notifs.push({
        id: `emp-train-${r.id}`,
        title: 'Training Request Submitted',
        desc: 'Your training request has been sent to HR for initial review.',
        time: r.dateSubmitted,
        read: readIds.has(`emp-train-${r.id}`),
      });
    });
  }

  if (user.role === 'hod' || user.role === 'hr' || user.role === 'admin') {
    // Safely check if initialAppraisals exists and has items
    const lowPerformers = initialAppraisals?.filter(a => a.overallRating > 0 && a.overallRating < 2.5) || [];
    lowPerformers.forEach(a => notifs.push({
      id: `perf-low-${a.id}`,
      title: 'Low Performance Alert',
      desc: `${a.name} (${a.dept}) — Rating ${a.overallRating} below threshold. PIP may be required.`,
      time: a.submittedDate || a.createdDate || new Date().toISOString(),
      read: readIds.has(`perf-low-${a.id}`),
    }));
  }

  if ((user.role === 'hod' || user.role === 'hr' || user.role === 'admin') && todayStr) {
    const overdueTasks = [
      { employee: 'Peter Otieno', dept: 'ICT', task: 'Digitize training management system', dueDate: '2026-04-15', planId: 'WP1' },
      { employee: 'Grace Wanjiku', dept: 'Operations', task: 'Support 500 youth enterprises', dueDate: '2026-04-01', planId: 'WP2' },
    ].filter(t => t.dueDate < todayStr);
    overdueTasks.forEach(t => notifs.push({
      id: `task-overdue-${t.planId}`,
      title: 'Work Plan Task Overdue',
      desc: `${t.employee} (${t.dept}) — "${t.task}" was due ${t.dueDate}`,
      time: t.dueDate,
      read: readIds.has(`task-overdue-${t.planId}`),
    }));
  }

  const unread = notifs.filter(n => !n.read).length;

  const markAllRead = () => {
    setReadIds(new Set(notifs.map(n => n.id)));
  };

  return (
    <div className="relative" ref={ref}>
      <button
        onClick={() => setOpen(v => !v)}
        className="relative w-9 h-9 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer transition-all"
      >
        <i className="ri-notification-3-line text-xl text-gray-500"></i>
        {unread > 0 && (
          <span className="absolute -top-0.5 -right-0.5 w-5 h-5 rounded-full text-white text-[10px] font-bold flex items-center justify-center" style={{ background: '#B22698' }}>
            {unread > 9 ? '9+' : unread}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-11 w-80 bg-white rounded-2xl shadow-2xl border border-gray-100 z-50 overflow-hidden">
          <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100">
            <div className="flex items-center gap-2">
              <h3 className="font-bold text-gray-800 text-sm">Notifications</h3>
              {unread > 0 && (
                <span className="text-xs px-2 py-0.5 rounded-full text-white font-bold" style={{ background: '#B22698' }}>{unread}</span>
              )}
            </div>
            {unread > 0 && (
              <button onClick={markAllRead} className="text-xs cursor-pointer hover:underline" style={{ color: '#B22698' }}>
                Mark all read
              </button>
            )}
          </div>
          <div className="max-h-80 overflow-y-auto">
            {notifs.length === 0 ? (
              <div className="py-10 text-center text-gray-400">
                <i className="ri-notification-off-line text-3xl block mb-2 text-gray-200"></i>
                <p className="text-sm">No notifications</p>
              </div>
            ) : (
              notifs.slice(0, 10).map(n => (
                <div key={n.id} onClick={() => setReadIds(prev => new Set([...prev, n.id]))}
                  className={`px-4 py-3 border-b border-gray-50 cursor-pointer hover:bg-gray-50 transition-all ${!n.read ? 'bg-pink-50/40' : ''}`}>
                  <div className="flex items-start gap-2">
                    <div className="w-2 h-2 rounded-full mt-1.5 flex-shrink-0" style={{ background: n.read ? '#d1d5db' : '#B22698' }}></div>
                    <div className="flex-1 min-w-0">
                      <p className={`text-sm ${n.read ? 'text-gray-600' : 'text-gray-800 font-semibold'}`}>{n.title}</p>
                      <p className="text-xs text-gray-400 mt-0.5 truncate">{n.desc}</p>
                      <p className="text-xs text-gray-300 mt-0.5">{n.time}</p>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
          {notifs.length > 10 && (
            <div className="px-4 py-2 text-center border-t border-gray-50">
              <p className="text-xs text-gray-400">+{notifs.length - 10} more notifications</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}