'use client';

import { useEffect, useState } from 'react';
import DashboardRefreshBar from './DashboardRefreshBar';
import { useRouter } from 'next/navigation';
import type { ColumnDef } from '@tanstack/react-table';
import { api } from '@/lib/api';
import { toast } from 'react-toastify';
import type { User } from '@/types';
import { DataTable } from '@/components/data-table/DataTable';
import { formatDate } from '@/lib/dates';
import RecruiterWorkTable from './RecruiterWorkTable';
import ActionPointsCard, { type ActionPoint } from './ActionPointsCard';

interface DashboardStats {
  pending_approvals: number;
  approved_jds: number;
  rejected_jds: number;
}

// Module-scope cache — lets revisits paint instantly while refreshing silently.
let hmCache: {
  stats: DashboardStats | null;
  pendingJDs: any[];
  approvedJDs: any[];
  rejectedJDs: any[];
} | null = null;
// Action Points are fetched separately (their own cache) so a failure there can
// never take down the approval queue, and vice versa.
let hmActionPointsCache: ActionPoint[] | null = null;

export default function HiringManagerDashboard({ user }: { user: User }) {
  const [stats, setStats] = useState<DashboardStats | null>(hmCache?.stats ?? null);
  const [pendingJDs, setPendingJDs] = useState<any[]>(hmCache?.pendingJDs ?? []);
  const [approvedJDs, setApprovedJDs] = useState<any[]>(hmCache?.approvedJDs ?? []);
  const [rejectedJDs, setRejectedJDs] = useState<any[]>(hmCache?.rejectedJDs ?? []);
  const [loading, setLoading] = useState(true);
  const [rejectingJdId, setRejectingJdId] = useState<number | null>(null);
  const [rejectionReason, setRejectionReason] = useState('');
  // Full-text viewer for long remarks / rejection reasons (kept out of the table).
  const [reasonModal, setReasonModal] = useState<{ title: string; label: string; reason: string } | null>(null);
  // Action Points — additive, read-only. Scoped server-side to the JDs routed
  // to this HM and already RBAC-filtered, so nothing here widens visibility.
  const [actionPoints, setActionPoints] = useState<ActionPoint[] | null>(hmActionPointsCache);
  const [actionsLoading, setActionsLoading] = useState(hmActionPointsCache === null);
  const router = useRouter();

  const loadActionPoints = () => {
    (api.get('/dashboard/hiring-manager/action-points/') as Promise<{ data?: { action_points?: ActionPoint[] } }>)
      .then((res) => {
        hmActionPointsCache = res?.data?.action_points ?? [];
        setActionPoints(hmActionPointsCache);
      })
      // A failed call leaves the approval dashboard fully usable.
      .catch(() => setActionPoints(hmActionPointsCache ?? []))
      .finally(() => setActionsLoading(false));
  };

  const loadData = () => {
    loadActionPoints();
    setLoading(true);
    Promise.all([
      api.get('/dashboard/hiring-manager/'),
      api.get('/jds/pending-approvals/'),
      api.get('/jds/approval-history/')
    ]).then(([statsRes, pendingRes, historyRes]: any) => {
      setStats(statsRes.data || statsRes);
      setPendingJDs(pendingRes.data || pendingRes);
      
      const history = historyRes.data || historyRes;
      // Filter approved JDs and rejected JDs lists from history or JDs
      // Wait! We can show approved JDs from history actions
      const approved = history.filter((h: any) => h.action === 'APPROVED');
      const rejected = history.filter((h: any) => h.action === 'REJECTED');

      hmCache = {
        stats: statsRes.data || statsRes,
        pendingJDs: pendingRes.data || pendingRes,
        approvedJDs: approved,
        rejectedJDs: rejected,
      };
      setApprovedJDs(approved);
      setRejectedJDs(rejected);
    }).catch((err) => {
      console.error('Failed to load hiring manager dashboard data:', err);
      toast.error('Failed to retrieve approval dashboard items.');
    }).finally(() => {
      setLoading(false);
    });
  };

  useEffect(() => {
    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);
    };
    // Mount-only load + subscription, as before (loadData is re-created each
    // render but must not re-run this effect).
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleApprove = (id: number) => {
    api.post(`/jds/${id}/approve/`, {})
      .then(() => {
        toast.success('Job description approved successfully!');
        loadData();
      })
      .catch((err: any) => {
        toast.error(err.response?.data?.message || 'Approval failed.');
      });
  };

  const handleRejectSubmit = () => {
    if (!rejectionReason.trim()) {
      toast.warn('Please provide a rejection reason.');
      return;
    }
    api.post(`/jds/${rejectingJdId}/reject/`, { reason: rejectionReason })
      .then(() => {
        toast.success('Job description rejected.');
        setRejectingJdId(null);
        setRejectionReason('');
        loadData();
      })
      .catch((err: any) => {
        toast.error(err.response?.data?.message || 'Rejection failed.');
      });
  };

  const scrollToSection = (id: string) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth' });
  };

  if (loading && !stats) {
    return (
      <div className="flex items-center justify-center min-h-[300px]">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-[#405189]"></div>
      </div>
    );
  }

  const cards = [
    { label: 'Pending Approvals', value: stats?.pending_approvals ?? 0, icon: 'fa-solid fa-clock-rotate-left', color: 'bg-yellow-500/10 text-yellow-600', targetId: 'pending-approvals-section' },
    { label: 'Approved JDs', value: stats?.approved_jds ?? 0, icon: 'fa-solid fa-circle-check', color: 'bg-green-500/10 text-green-600', targetId: 'approved-history-section' },
    { label: 'Rejected JDs', value: stats?.rejected_jds ?? 0, icon: 'fa-solid fa-circle-xmark', color: 'bg-red-500/10 text-red-600', targetId: 'rejected-history-section' },
  ];

  // Reusable DataTable columns (pending queue + approval history views)
  const pendingColumns: ColumnDef<any>[] = [
    { accessorKey: 'jd_code', header: 'JD Code', cell: ({ getValue }) => <span className="font-bold text-[#405189] dark:text-indigo-300">{getValue() as string}</span> },
    {
      accessorKey: 'title',
      header: 'JD Title',
      cell: ({ getValue }) => (
        <span className="inline-flex items-center gap-1.5 font-semibold text-slate-800 dark:text-slate-150">
          {getValue() as string}
          <span className="text-[9px] px-1.5 py-0.5 font-black uppercase tracking-wider bg-orange-500 text-white animate-pulse" title="Awaiting your review">
            NEW
          </span>
        </span>
      ),
    },
    { accessorKey: 'department', header: 'Department', cell: ({ getValue }) => (getValue() as string) || '—' },
    { accessorKey: 'client_name', header: 'Client', cell: ({ getValue }) => (getValue() as string) || '—' },
    { accessorKey: 'created_by_name', header: 'Created By', cell: ({ getValue }) => (getValue() as string) || '—' },
    {
      accessorKey: 'submitted_for_approval_at',
      header: 'Submitted Date',
      cell: ({ getValue }) => (getValue() ? formatDate(getValue() as string) : '—'),
    },
    {
      accessorKey: 'priority',
      header: 'Priority',
      cell: ({ getValue }) => {
        const p = getValue() as string;
        return (
          <span className={`px-2 py-0.5 text-[9px] font-bold uppercase ${
            p === 'High' ? 'bg-red-500/10 text-red-500' :
            p === 'Medium' ? 'bg-orange-500/10 text-orange-500' : 'bg-green-500/10 text-green-500'
          }`}>
            {p}
          </span>
        );
      },
    },
    {
      id: 'actions',
      header: () => <div className="text-center">Actions</div>,
      enableSorting: false,
      cell: ({ row }) => {
        const jd = row.original;
        return (
          <div className="flex gap-1 justify-center">
            <button
              onClick={() => router.push(`/jobs/${jd.id}`)}
              className="px-2 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-250 border border-vz-border dark:border-slate-750 transition cursor-pointer"
            >
              View
            </button>
            <button
              onClick={() => handleApprove(jd.id)}
              className="px-2 py-1 bg-green-650 hover:bg-green-755 text-white text-[10px] font-semibold transition cursor-pointer"
            >
              Approve
            </button>
            <button
              onClick={() => setRejectingJdId(jd.id)}
              className="px-2 py-1 bg-red-650 hover:bg-red-755 text-white text-[10px] font-semibold transition cursor-pointer"
            >
              Reject
            </button>
          </div>
        );
      },
    },
  ];

  const historyColumns = (kind: 'approved' | 'rejected'): ColumnDef<any>[] => [
    { accessorKey: 'jd_code', header: 'JD Code', cell: ({ getValue }) => <span className="font-bold text-slate-700 dark:text-slate-350">{getValue() as string}</span> },
    { accessorKey: 'job_title', header: 'JD Title', cell: ({ getValue }) => <span className="font-semibold text-slate-800 dark:text-slate-150">{getValue() as string}</span> },
    {
      accessorKey: 'remarks',
      header: kind === 'approved' ? 'Remarks' : 'Rejection Reason',
      cell: ({ getValue, row }) => {
        const label = kind === 'approved' ? 'Remarks' : 'Rejection Reason';
        const text = ((getValue() as string) || (kind === 'approved' ? 'Approved' : '')).trim();
        if (!text) return <span className="text-vz-muted">—</span>;
        // Truncate to 2 lines in the table (fixed row height, no overflow);
        // full text stays available via hover tooltip + "Read more" modal.
        const isLong = text.length > 120;
        return (
          <div className="max-w-[260px]">
            <p
              title={text}
              className={`italic line-clamp-2 break-words ${kind === 'rejected' ? 'text-red-500' : 'text-vz-muted'}`}
            >
              &quot;{text}&quot;
            </p>
            {isLong && (
              <button
                type="button"
                onClick={() => setReasonModal({
                  title: `${row.original.jd_code ?? ''} ${row.original.job_title ?? ''}`.trim() || label,
                  label,
                  reason: text,
                })}
                className="mt-0.5 text-[10px] font-bold text-indigo-600 dark:text-indigo-400 hover:underline cursor-pointer"
              >
                Read more
              </button>
            )}
          </div>
        );
      },
    },
    { accessorKey: 'action_by_name', header: kind === 'approved' ? 'Action By' : 'Rejected By', cell: ({ getValue }) => (getValue() as string) || '—' },
    {
      accessorKey: 'created_at',
      header: kind === 'approved' ? 'Date Approved' : 'Date Rejected',
      cell: ({ getValue }) => formatDate(getValue() as string),
    },
    {
      id: 'status',
      header: () => <div className="text-center">Status</div>,
      enableSorting: false,
      cell: () => (
        <div className="text-center">
          <span className={`px-2 py-0.5 text-[9px] font-bold uppercase ${
            kind === 'approved' ? 'bg-green-500/10 text-green-500' : 'bg-red-500/10 text-red-500'
          }`}>
            {kind === 'approved' ? 'Approved' : 'Rejected'}
          </span>
        </div>
      ),
    },
  ];

  const approvedColumns = historyColumns('approved');
  const rejectedColumns = historyColumns('rejected');

  return (
    <div className="space-y-6">
      {/* Title + KPI cards (left, unchanged) with the Action Points card in the
          dashboard's top-right corner. Stacks to full width below xl. */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 items-start">
        <div className="xl:col-span-2 space-y-4">
          {/* Title */}
          <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
            <div>
              <h3 className="text-base font-bold text-[#495057] dark:text-white uppercase tracking-wider">Hiring Manager Approval Dashboard</h3>
              <p className="text-xs text-vz-muted mt-0.5">Review and approve job descriptions submitted for your alignment.</p>
            </div>
            <DashboardRefreshBar onRefresh={() => { loadData(); loadActionPoints(); }} />
          </div>

          {/* Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {cards.map((c) => (
              <div
                key={c.label}
                onClick={() => scrollToSection(c.targetId)}
                className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 p-4 flex items-center justify-between shadow-sm cursor-pointer hover:shadow-md transition-shadow"
              >
                <div>
                  <p className="text-[11px] uppercase tracking-wider text-vz-muted font-bold">{c.label}</p>
                  <p className="text-2xl font-black text-[#495057] dark:text-white mt-2">{c.value}</p>
                </div>
                <span className={`w-11 h-11 rounded-full flex items-center justify-center text-lg ${c.color}`}>
                  <i className={c.icon}></i>
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* headingOutside lifts the title alongside the dashboard title so both
            panels' top edges line up exactly; mb-4 matches the column's space-y-4. */}
        <ActionPointsCard
          points={actionPoints}
          loading={actionsLoading}
          headingOutside
          headingClassName="mb-4"
          subtitle="Pending items on the JDs routed to you."
          emptyDescription="No pending actions on your JDs right now."
          className="xl:col-span-1"
        />
      </div>

      {/* Rejection Modal/Popup */}
      {rejectingJdId !== null && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 max-w-md w-full p-6 space-y-4 shadow-xl">
            <h4 className="text-sm font-bold uppercase tracking-wider text-[#495057] dark:text-white">Reject Job Description</h4>
            <div className="space-y-1">
              <label className="text-xs text-vz-muted font-semibold">Reason for Rejection</label>
              <textarea
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                rows={3}
                placeholder="Specify what needs adjustments (e.g. experience range, CTC)..."
                className="w-full text-xs p-2 border border-vz-border dark:border-slate-800 bg-white dark:bg-slate-950 text-slate-800 dark:text-white focus:outline-none"
              />
            </div>
            <div className="flex gap-2 justify-end">
              <button
                onClick={() => { setRejectingJdId(null); setRejectionReason(''); }}
                className="px-3 py-1.5 bg-slate-100 dark:bg-slate-850 hover:bg-slate-200 text-slate-700 dark:text-slate-200 text-xs font-semibold border border-vz-border dark:border-slate-800 transition"
              >
                Cancel
              </button>
              <button
                onClick={handleRejectSubmit}
                className="px-3 py-1.5 bg-red-650 hover:bg-red-750 text-white text-xs font-semibold transition"
              >
                Confirm Rejection
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Full rejection reason / remarks viewer (opened from "Read more") */}
      {reasonModal !== null && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
          onClick={() => setReasonModal(null)}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 max-w-lg w-full p-6 space-y-3 shadow-xl"
          >
            <div className="flex items-start justify-between gap-3">
              <div className="min-w-0">
                <h4 className="text-sm font-bold uppercase tracking-wider text-[#495057] dark:text-white">{reasonModal.label}</h4>
                {reasonModal.title && (
                  <p className="text-[11px] text-vz-muted font-semibold mt-0.5 truncate">{reasonModal.title}</p>
                )}
              </div>
              <button
                onClick={() => setReasonModal(null)}
                aria-label="Close"
                className="shrink-0 w-7 h-7 flex items-center justify-center text-slate-400 hover:text-slate-700 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer"
              >
                <i className="fa-solid fa-xmark" />
              </button>
            </div>
            <p className="text-xs leading-relaxed text-slate-700 dark:text-slate-200 whitespace-pre-line break-words max-h-[60vh] overflow-y-auto">
              {reasonModal.reason}
            </p>
            <div className="flex justify-end">
              <button
                onClick={() => setReasonModal(null)}
                className="px-3 py-1.5 bg-slate-100 dark:bg-slate-850 hover:bg-slate-200 text-slate-700 dark:text-slate-200 text-xs font-semibold border border-vz-border dark:border-slate-800 transition cursor-pointer"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Pending Approvals — reusable DataTable (search, sort, pagination, sticky header, h-scroll) */}
      <div id="pending-approvals-section" className="space-y-2">
        <h4 className="text-xs font-bold text-[#495057] dark:text-white uppercase tracking-wider">Pending JD Approvals</h4>
        <DataTable
          columns={pendingColumns}
          data={pendingJDs}
          loading={loading}
          compact
          searchPlaceholder="Search pending JDs…"
          emptyStateTitle="No pending job descriptions"
          emptyStateDescription="JDs submitted for your approval will appear here."
        />
      </div>

      {/* Approved JD History — reusable DataTable */}
      <div id="approved-history-section" className="space-y-2">
        <h4 className="text-xs font-bold text-[#495057] dark:text-white uppercase tracking-wider">Approved JD History</h4>
        <DataTable
          columns={approvedColumns}
          data={approvedJDs}
          loading={loading}
          compact
          searchPlaceholder="Search approved history…"
          emptyStateTitle="No approved history logs"
          emptyStateDescription="Approved JDs will be listed here."
        />
      </div>

      {/* Rejected JD History — reusable DataTable */}
      <div id="rejected-history-section" className="space-y-2">
        <h4 className="text-xs font-bold text-[#495057] dark:text-white uppercase tracking-wider">Rejected JD History</h4>
        <DataTable
          columns={rejectedColumns}
          data={rejectedJDs}
          loading={loading}
          compact
          searchPlaceholder="Search rejected history…"
          emptyStateTitle="No rejected history logs"
          emptyStateDescription="Rejected JDs will be listed here."
        />
      </div>

      {/* Recruiter-wise work — only recruiters working on THIS HM's JDs
          (server-side scoped by the logged-in user). */}
      <RecruiterWorkTable title="Recruiter-wise Work (Your JDs)" />
    </div>
  );
}
