'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import { formatDate } from '@/lib/dates';

// Module-scope cache keyed by client scope ('global' or the client id) —
// lets revisits paint instantly while refreshing silently.
const monitorCache: Record<string, any[]> = {};

// Pass clientId to show only that client's JD approval logs.
export default function JDApprovalMonitoring({ clientId }: { clientId?: string }) {
  const cacheKey = clientId || 'global';
  const [data, setData] = useState<any[]>(monitorCache[cacheKey] ?? []);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const router = useRouter();

  const loadData = () => {
    setLoading(true);
    api.get(`/admin/jd-approval-monitoring/${clientId ? `?client=${encodeURIComponent(clientId)}` : ''}`)
      .then((res: any) => {
        monitorCache[cacheKey] = res.data || res;
        setData(monitorCache[cacheKey] ?? []);
        setCurrentPage(1);
      })
      .catch((err) => {
        console.error('Failed to load JD approval monitoring logs:', err);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    setData(monitorCache[cacheKey] ?? []);
    loadData();

    const handleWSEvent = (e: Event) => {
      const customEvent = e as CustomEvent;
      const eventName = customEvent.detail?.event;
      if (['jd_submitted', 'jd_pending_approval', 'jd_approved', 'jd_rejected'].includes(eventName)) {
        loadData();
      }
    };

    window.addEventListener('ws-event', handleWSEvent);
    return () => {
      window.removeEventListener('ws-event', handleWSEvent);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [clientId]);

  if (loading && data.length === 0) {
    return null;
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'APPROVED':
        return 'bg-green-500/10 text-green-500';
      case 'PENDING_APPROVAL':
        return 'bg-yellow-500/10 text-yellow-600';
      case 'REJECTED':
        return 'bg-red-500/10 text-red-500';
      case 'PUBLISHED':
        return 'bg-blue-500/10 text-blue-500';
      default:
        return 'bg-slate-100 text-slate-500';
    }
  };

  return (
    <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 p-5 shadow-sm space-y-4">
      <div>
        <h4 className="text-xs font-bold text-[#495057] dark:text-white uppercase tracking-wider">JD Approval Monitoring Logs</h4>
        <p className="text-[10px] text-vz-muted mt-0.5">Read-only system log track of all Job Description workflows.</p>
      </div>

      <div className="overflow-x-auto max-h-[360px] overflow-y-auto custom-scrollbar border border-slate-100 dark:border-slate-800">
        <table className="w-full text-xs text-left border-collapse">
          <thead className="sticky top-0 z-10 bg-white dark:bg-slate-900 shadow-[0_1px_0_0_rgba(226,232,240,1)] dark:shadow-[0_1px_0_0_rgba(30,41,59,1)]">
            <tr className="bg-slate-50 dark:bg-slate-950 border-b border-vz-border dark:border-slate-800 text-vz-muted">
              <th className="px-3 py-2 font-semibold">JD Code</th>
              <th className="px-3 py-2 font-semibold">JD Title</th>
              <th className="px-3 py-2 font-semibold">Created By</th>
              <th className="px-3 py-2 font-semibold">Hiring Manager</th>
              <th className="px-3 py-2 font-semibold text-center">Approval Status</th>
              <th className="px-3 py-2 font-semibold">Submitted Date</th>
              <th className="px-3 py-2 font-semibold">Approved Date</th>
              <th className="px-3 py-2 font-semibold">Rejected Date</th>
              <th className="px-3 py-2 font-semibold">Reason</th>
              <th className="px-3 py-2 font-semibold text-center">Action</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
            {data.length === 0 ? (
              <tr>
                <td colSpan={10} className="p-6 text-center text-vz-muted">No JDs found for monitoring.</td>
              </tr>
            ) : (
              data.slice((currentPage - 1) * 5, currentPage * 5).map((jd) => (
                <tr key={jd.id} className="hover:bg-slate-50/50 dark:hover:bg-slate-800/10">
                  <td className="px-3 py-2 font-bold text-[#405189] dark:text-indigo-300">{jd.jd_code}</td>
                  <td className="px-3 py-2 font-semibold text-slate-800 dark:text-slate-150">{jd.title}</td>
                  <td className="px-3 py-2 text-vz-muted">{jd.created_by_name}</td>
                  <td className="px-3 py-2 text-vz-muted">{jd.hiring_manager_name}</td>
                  <td className="px-3 py-2 text-center">
                    <span className={`px-2 py-0.5 text-[9px] font-bold uppercase ${getStatusBadge(jd.approval_status)}`}>
                      {jd.approval_status}
                    </span>
                  </td>
                  <td className="px-3 py-2 text-vz-muted">{jd.submitted_for_approval_at ? formatDate(jd.submitted_for_approval_at) : '—'}</td>
                  <td className="px-3 py-2 text-vz-muted">{jd.approved_at ? formatDate(jd.approved_at) : '—'}</td>
                  <td className="px-3 py-2 text-vz-muted">{jd.rejected_at ? formatDate(jd.rejected_at) : '—'}</td>
                  <td className="px-3 py-2 text-red-500 italic max-w-xs truncate" title={jd.rejection_reason}>
                    {jd.rejection_reason ? `"${jd.rejection_reason}"` : '—'}
                  </td>
                  <td className="px-3 py-2 text-center">
                    <button
                      onClick={() => router.push(`/jobs/${jd.id}`)}
                      className="px-2.5 py-1 bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-[10px] font-semibold text-slate-700 dark:text-slate-200 border border-vz-border dark:border-slate-800 transition"
                    >
                      View Details
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
      {(() => {
        const totalPages = Math.ceil(data.length / 5);
        if (totalPages <= 1) return null;
        return (
          <div className="flex items-center justify-between border-t border-slate-150 dark:border-slate-850 px-4 py-2 bg-slate-50/50 dark:bg-slate-950/20 text-xs font-semibold">
            <span className="text-slate-500">Page {currentPage} of {totalPages}</span>
            <div className="flex gap-1.5">
              <button
                type="button"
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={currentPage <= 1}
                className="px-2 py-1 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 disabled:opacity-40 font-bold transition cursor-pointer text-slate-700 dark:text-slate-355"
              >
                &larr; Prev
              </button>
              <button
                type="button"
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                disabled={currentPage >= totalPages}
                className="px-2 py-1 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 disabled:opacity-40 font-bold transition cursor-pointer text-slate-700 dark:text-slate-355"
              >
                Next &rarr;
              </button>
            </div>
          </div>
        );
      })()}
    </div>
  );
}
