'use client';

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

export interface AssignedJD {
  jd_id: number;
  title: string;
  location: string;
  client_name: string | null;
  priority: 'High' | 'Medium' | 'Low';
  status: 'Draft' | 'Published' | 'Closed';
  assigned_at: string;
}

// Underlying JD statuses → recruiter-facing labels.
// Retained (not deleted) after the table's Status column was replaced by
// Opening Progress — the JD status itself is still returned by the API and
// these keep the mapping available if the column is reinstated.
/* eslint-disable @typescript-eslint/no-unused-vars */
const STATUS_LABEL: Record<AssignedJD['status'], string> = {
  Published: 'Open',
  Draft: 'On Hold',
  Closed: 'Closed',
};

const STATUS_BADGE: Record<AssignedJD['status'], string> = {
  Published: 'bg-emerald-50 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-900/40',
  Draft: 'bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-900/40',
  Closed: 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 border-slate-200 dark:border-slate-700',
};
/* eslint-enable @typescript-eslint/no-unused-vars */

const PRIORITY_BADGE: Record<AssignedJD['priority'], string> = {
  High: 'bg-rose-50 dark:bg-rose-950/40 text-rose-700 dark:text-rose-300 border-rose-200 dark:border-rose-900/40',
  Medium: 'bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-900/40',
  Low: 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 border-slate-200 dark:border-slate-700',
};

function formatDate(iso: string) {
  const d = new Date(iso);
  return isNaN(d.getTime()) ? '—' : d.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' });
}

/** Per-JD opening progress + candidate funnel, from the recruiter overview API. */
export interface JdBreakdown {
  jd_id: number;
  openings_total: number;
  openings_filled: number;
  openings_remaining: number;
  applied: number;
  ai_screened: number;
  shortlisted: number;
  submitted: number;
  interviewed: number;
  offered: number;
  joined: number;
  rejected: number;
  remaining: number;
  rejection_reasons: { reason: string; count: number }[];
}

interface MyAssignedJDsProps {
  /**
   * Pre-fetched assigned JDs. When supplied (together with `jdBreakdown`) this
   * component makes no requests of its own — the parent dashboard already has
   * the data from its single consolidated call. Omit both props and it fetches
   * exactly as it always did, which is how RoleDashboard still uses it.
   */
  jds?: AssignedJD[];
  jdBreakdown?: JdBreakdown[];
  /** Parent-driven loading flag, used only in the supplied-data mode. */
  loading?: boolean;
}

export default function MyAssignedJDs({
  jds: providedJds,
  jdBreakdown: providedBreakdown,
  loading: providedLoading,
}: MyAssignedJDsProps = {}) {
  const router = useRouter();
  const supplied = providedJds !== undefined;
  const [fetchedJds, setFetchedJds] = useState<AssignedJD[]>([]);
  const [fetchedLoading, setFetchedLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [fetchedBreakdown, setFetchedBreakdown] = useState<Record<number, JdBreakdown>>({});

  const jds = supplied ? providedJds! : fetchedJds;
  const loading = supplied ? (providedLoading ?? false) : fetchedLoading;
  const breakdown = useMemo(() => {
    if (!supplied) return fetchedBreakdown;
    const map: Record<number, JdBreakdown> = {};
    (providedBreakdown ?? []).forEach((r) => { map[r.jd_id] = r; });
    return map;
  }, [supplied, providedBreakdown, fetchedBreakdown]);
  // Drives the candidate-progress / rejection-matrix panel. Its "Progress"
  // trigger button was removed from the UI, so nothing sets this today — the
  // state and the panel are retained so the section can be re-enabled without
  // rebuilding it.
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [openJd, setOpenJd] = useState<number | null>(null);

  // Both fetches below are skipped entirely when the parent supplies the data
  // (see the props doc) — that is what keeps the Recruiter Dashboard down to a
  // single request. Standalone usage is unchanged.
  useEffect(() => {
    if (supplied) return;
    let alive = true;
    (async () => {
      try {
        const res = (await api.get('/jobs/my-assigned/')) as { data?: AssignedJD[] };
        if (alive) setFetchedJds(Array.isArray(res.data) ? res.data : []);
      } catch (e) {
        if (alive) setError(e instanceof Error ? e.message : 'Failed to load assigned JDs');
      } finally {
        if (alive) setFetchedLoading(false);
      }
    })();
    return () => { alive = false; };
  }, [supplied]);

  // Opening progress / candidate funnel / rejection reasons per JD. Read from
  // the existing recruiter-overview service (additive endpoint) so the JD list
  // API stays untouched; a failure here just leaves the table as it was.
  useEffect(() => {
    if (supplied) return;
    let alive = true;
    api.get('/dashboard/recruiter/overview/')
      .then((res: unknown) => {
        const rows = (res as { data?: { jd_breakdown?: JdBreakdown[] } })?.data?.jd_breakdown ?? [];
        if (!alive) return;
        const map: Record<number, JdBreakdown> = {};
        rows.forEach((r) => { map[r.jd_id] = r; });
        setFetchedBreakdown(map);
      })
      .catch(() => { /* progress columns simply stay blank */ });
    return () => { alive = false; };
  }, [supplied]);

  const total = jds.length;
  // The JD status breakdown (On Hold / Closed) is shown in the dashboard's
  // Quick Overview section, so this section goes straight to the JD table.
  // `total` still drives the empty state below, and the status data itself is
  // untouched — it remains available from the API and used elsewhere.

  return (
    <div className="space-y-4">
      <h3 className="text-xs font-semibold uppercase tracking-wider text-vz-muted">My Assigned JDs</h3>

      {/* Table */}
      <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-sm overflow-hidden">
        {loading ? (
          <div className="p-5 space-y-2">
            {Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="h-10 bg-slate-100 dark:bg-slate-800/60 rounded-none animate-pulse" />
            ))}
          </div>
        ) : error ? (
          <div className="py-10 text-center px-4">
            <i className="fa-solid fa-triangle-exclamation text-rose-400 text-2xl mb-2" />
            <p className="text-sm text-rose-600 dark:text-rose-400 font-semibold">{error}</p>
          </div>
        ) : total === 0 ? (
          <div className="py-14 text-center px-4">
            <div className="w-12 h-12 mx-auto bg-slate-50 dark:bg-slate-950/40 rounded-none border border-slate-100 dark:border-slate-800 flex items-center justify-center text-slate-400 mb-3">
              <i className="fa-solid fa-folder-open text-xl" />
            </div>
            <h4 className="font-bold text-slate-800 dark:text-white text-sm">No JDs assigned yet</h4>
            <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">A manager hasn&apos;t assigned any job descriptions to you.</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse text-xs min-w-[620px]">
              <thead>
                <tr className="bg-slate-50 dark:bg-slate-950/40 border-b border-slate-200 dark:border-slate-800/80">
                  {['JD ID', 'Job Title', 'Client', 'Priority', 'Opening Progress', 'Assigned Date', 'Actions'].map((h) => (
                    <th key={h} className="py-2.5 px-4 text-[10px] tracking-wider uppercase font-black text-slate-400 dark:text-slate-500 whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                {jds.map((jd) => (
                  <tr key={jd.jd_id} className="hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition text-slate-700 dark:text-slate-300">
                    <td className="py-2.5 px-4 font-bold text-slate-500 dark:text-slate-400">#{jd.jd_id}</td>
                    <td className="py-2.5 px-4 font-semibold text-slate-800 dark:text-slate-200 max-w-[220px] truncate">{jd.title}</td>
                    <td className="py-2.5 px-4 text-slate-500 dark:text-slate-400">{jd.client_name || <span className="italic text-slate-400">Internal</span>}</td>
                    <td className="py-2.5 px-4">
                      <span className={`px-2 py-0.5 rounded-full text-[9px] font-bold border ${PRIORITY_BADGE[jd.priority] ?? PRIORITY_BADGE.Medium}`}>{jd.priority}</span>
                    </td>
                    {/* Opening Progress — replaces the old Status column.
                        Filled tracks candidates who reached the joined stage. */}
                    <td className="py-2.5 px-4 min-w-[150px]">
                      {(() => {
                        const b = breakdown[jd.jd_id];
                        if (!b || !b.openings_total) {
                          return (
                            <span className="text-[10px] text-slate-400 dark:text-slate-500 italic">
                              {b ? `${b.openings_filled} filled · openings not set` : '—'}
                            </span>
                          );
                        }
                        const pct = Math.min(100, Math.round((b.openings_filled / b.openings_total) * 100));
                        return (
                          <div>
                            <div className="flex items-center justify-between gap-2 mb-1">
                              <span className="text-[11px] font-bold text-slate-700 dark:text-slate-200">
                                {b.openings_filled} / {b.openings_total} Filled
                              </span>
                              <span className="text-[10px] font-semibold text-amber-600 dark:text-amber-400">
                                {b.openings_remaining} left
                              </span>
                            </div>
                            <div className="h-1.5 w-full bg-slate-200 dark:bg-slate-800 overflow-hidden">
                              <div
                                className={`h-full transition-all duration-300 ${pct >= 100 ? 'bg-emerald-500' : 'bg-[#405189]'}`}
                                style={{ width: `${pct}%` }}
                              />
                            </div>
                          </div>
                        );
                      })()}
                    </td>
                    <td className="py-2.5 px-4 text-slate-500 dark:text-slate-400 whitespace-nowrap">{formatDate(jd.assigned_at)}</td>
                    <td className="py-2.5 px-4">
                      <button
                        onClick={() => window.open(`/jobs/${jd.jd_id}`, '_blank', 'noopener,noreferrer')}
                        title="View Job Description"
                        className="inline-flex items-center gap-2 rounded-none border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-950 px-3 py-2 text-xs font-semibold text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-900 transition"
                      >
                        <i className="fa-solid fa-eye text-[11px]"></i>
                        View JD
                      </button>
                      {/* The "Progress" expander button was removed from the UI.
                          The candidate-progress / rejection-matrix panel below
                          and its data (breakdown) are left intact — re-add a
                          control that calls setOpenJd(jd.jd_id) to surface it. */}
                    </td>
                  </tr>
                ))}
                {/* Candidate progress + rejection matrix for the expanded JD */}
                {jds.map((jd) => {
                  const b = breakdown[jd.jd_id];
                  if (!b || openJd !== jd.jd_id) return null;
                  return (
                    <tr key={`${jd.jd_id}-detail`} className="bg-slate-50/60 dark:bg-slate-950/40">
                      <td colSpan={7} className="px-4 py-4">
                        <p className="text-[10px] uppercase tracking-wider font-black text-slate-400 mb-2">
                          Candidate Progress — {jd.title}
                        </p>
                        <div className="grid grid-cols-3 sm:grid-cols-5 lg:grid-cols-9 gap-2">
                          {([
                            ['Applied', b.applied], ['AI Screened', b.ai_screened],
                            ['Shortlisted', b.shortlisted], ['Submitted', b.submitted],
                            ['Interviewed', b.interviewed], ['Offered', b.offered],
                            ['Joined', b.joined], ['Rejected', b.rejected],
                            ['Remaining', b.remaining],
                          ] as [string, number][]).map(([label, val]) => (
                            <div key={label} className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 px-2.5 py-2">
                              <p className="text-[9px] uppercase tracking-wider text-vz-muted font-bold truncate">{label}</p>
                              <p className="text-base font-bold text-[#495057] dark:text-white mt-0.5">{val}</p>
                            </div>
                          ))}
                        </div>

                        <p className="text-[10px] uppercase tracking-wider font-black text-slate-400 mt-4 mb-2">
                          Rejection Matrix — {b.rejected} rejected
                        </p>
                        {b.rejection_reasons.length === 0 ? (
                          <p className="text-[11px] text-vz-muted italic">No rejections recorded for this JD yet.</p>
                        ) : (
                          <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 max-w-md">
                            <table className="w-full text-xs">
                              <thead>
                                <tr className="border-b border-vz-border dark:border-slate-800">
                                  <th className="text-left py-2 px-3 text-[10px] font-extrabold uppercase tracking-wider text-vz-muted">Rejection Reason</th>
                                  <th className="text-right py-2 px-3 text-[10px] font-extrabold uppercase tracking-wider text-vz-muted">Count</th>
                                </tr>
                              </thead>
                              <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                                {b.rejection_reasons.map((r) => (
                                  <tr key={r.reason}>
                                    <td className="py-2 px-3 font-semibold text-slate-700 dark:text-slate-300">{r.reason}</td>
                                    <td className="py-2 px-3 text-right font-bold text-[#495057] dark:text-white">{r.count}</td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
