'use client';

import { useEffect, useState } from 'react';
import DashboardRefreshBar from './DashboardRefreshBar';
import type { User } from '@/types';
import { motion } from 'framer-motion';
import { useAuth } from '@/components/auth-context';
import { hasAnyDjangoPermission } from '@/lib/permissions';
import { api } from '@/lib/api';
import StatsCard from './StatsCard';
import SimpleBarChart from './SimpleBarChart';
import RecruitmentFunnel from './RecruitmentFunnel';
import AgeingCard from './AgeingCard';
import QuickActions from './QuickActions';
import RecentActivity, { type Activity } from './RecentActivity';
import TALiveAnalytics from './TALiveAnalytics';
import RecruiterWorkTable from './RecruiterWorkTable';

type Period = 'monthly' | 'quarterly' | 'halfyearly' | 'yearly';

// UI period keys -> backend period params
const API_PERIOD: Record<Period, string> = {
  monthly: 'monthly', quarterly: 'quarterly', halfyearly: 'half_yearly', yearly: 'annually',
};

const PERIOD_LABELS: Record<Period, string> = {
  monthly: 'Monthly', quarterly: 'Quarterly', halfyearly: 'Half-Yearly', yearly: 'Yearly',
};

interface PipelineData {
  submitted: number;
  shortlisted: number;
  offered: number;
  joined: number;
  offer_rejected: number;
  rejected: number;
  hold: number;
  trend: { label: string; value: number }[];
}

interface RequirementsData {
  total: number;
  change_pct: number;
  pending: number;
}

interface PendingRow {
  created_date: string;
}

const QUICK_ACTIONS = [
  { label: 'New JD Mapping',  icon: 'fa-solid fa-file-circle-plus', href: '/jobs?createJob=true',            color: 'border-indigo-200 bg-indigo-50 text-indigo-700 hover:bg-indigo-100 dark:border-indigo-800 dark:bg-indigo-950/30 dark:text-indigo-300' },
  { label: 'Assign Recruiter',icon: 'fa-solid fa-user-plus',        href: '/jobs?assignRecruiter=true', color: 'border-teal-200 bg-teal-50 text-teal-700 hover:bg-teal-100 dark:border-teal-800 dark:bg-teal-950/30 dark:text-teal-300' },
  { label: 'View Candidates', icon: 'fa-solid fa-users',            href: '/candidates',                 color: 'border-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-300' },
  { label: 'Reports',         icon: 'fa-solid fa-file-lines',       href: '/reports',                    color: 'border-purple-200 bg-purple-50 text-purple-700 hover:bg-purple-100 dark:border-purple-800 dark:bg-purple-950/30 dark:text-purple-300' },
];

const ACTIVITY: Activity[] = [
  { id: 1, type: 'create', message: 'Live activity feed arrives with the platform WebSocket phase', time: 'Info' },
];

/** Bucket open-JD ages (days since created) into the ageing bands. */
function ageingFromPending(rows: PendingRow[]) {
  const now = Date.now();
  const buckets = [0, 0, 0, 0];
  rows.forEach((r) => {
    const days = Math.floor((now - new Date(r.created_date).getTime()) / 86400000);
    if (days <= 15) buckets[0] += 1;
    else if (days <= 30) buckets[1] += 1;
    else if (days <= 60) buckets[2] += 1;
    else buckets[3] += 1;
  });
  return [
    { label: 'Fresh',    range: '0–15 Days',  count: buckets[0], color: 'bg-emerald-50 dark:bg-emerald-950/30', textColor: 'text-emerald-700 dark:text-emerald-300' },
    { label: 'Active',   range: '16–30 Days', count: buckets[1], color: 'bg-amber-50 dark:bg-amber-950/30',     textColor: 'text-amber-700 dark:text-amber-300'    },
    { label: 'Ageing',   range: '31–60 Days', count: buckets[2], color: 'bg-orange-50 dark:bg-orange-950/30',   textColor: 'text-orange-700 dark:text-orange-300'  },
    { label: 'Critical', range: '60+ Days',   count: buckets[3], color: 'bg-rose-50 dark:bg-rose-950/30',       textColor: 'text-rose-700 dark:text-rose-300'      },
  ];
}

export default function TADashboard({ user }: { user: User }) {
  const { user: authUser } = useAuth();
  const [period, setPeriod] = useState<Period>('monthly');
  const [pipe, setPipe] = useState<PipelineData | null>(null);
  const [reqs, setReqs] = useState<RequirementsData | null>(null);
  const [pending, setPending] = useState<PendingRow[] | null>(null);
  const name = user.full_name || user.email.split('@')[0];

  // Opens the destination page in a NEW TAB with the filter already resolved
  // into the URL (so the backend applies it fresh on load) — same pattern as
  // the PM dashboard. `params` are query params the destination page reads
  // synchronously on first render (e.g. `pm_metric`/`period`, `pending=1`).
  const openInNewTab = (route: string, perms?: string[], params?: Record<string, string>) => {
    if (!hasAnyDjangoPermission(authUser, perms)) return;
    const qs = params ? new URLSearchParams(params).toString() : '';
    window.open(qs ? `${route}?${qs}` : route, '_blank', 'noopener,noreferrer');
  };

  // Bumped by the refresh bar (manual + auto) to re-run the fetches below.
  const [refreshTick, setRefreshTick] = useState(0);

  // Period-scoped data — refetches when the filter changes or on refresh.
  useEffect(() => {
    const p = API_PERIOD[period];
    (api.get(`/dashboard/ta/pipeline-summary/?period=${p}`) as Promise<{ data: PipelineData }>)
      .then((r) => setPipe(r.data)).catch(() => {});
    (api.get(`/dashboard/ta/requirements-summary/?period=${p}`) as Promise<{ data: RequirementsData }>)
      .then((r) => setReqs(r.data)).catch(() => {});
  }, [period, refreshTick]);

  // Ageing buckets from the live pending-requirements list
  useEffect(() => {
    (api.get('/dashboard/ta/pending-requirements/') as Promise<{ data: { requirements: PendingRow[] } }>)
      .then((r) => setPending(r.data.requirements)).catch(() => setPending([]));
  }, [refreshTick]);

  const funnel = pipe ? [
    { label: 'Submitted',   value: pipe.submitted,   color: '#405189' },
    { label: 'Shortlisted', value: pipe.shortlisted, color: '#3577f1' },
    { label: 'Offered',     value: pipe.offered,     color: '#f7b84b' },
    { label: 'Joined',      value: pipe.joined,      color: '#0ab39c' },
  ] : [];
  const offerRate = pipe && pipe.submitted > 0 ? ((pipe.offered / pipe.submitted) * 100).toFixed(1) : '0';
  const ageing = ageingFromPending(pending ?? []);
  const critical = ageing[3].count;

  return (
    <div className="space-y-5">
      {/* Header — neutral card, matching the Admin Command Center style */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none p-6 shadow-sm flex flex-col md:flex-row md:items-center md:justify-between gap-4"
      >
        <div>
          <p className="text-xs uppercase tracking-wider text-vz-muted font-semibold">Talent Acquisition</p>
          <h1 className="text-xl font-bold text-[#495057] dark:text-white mt-1">{name} 👋</h1>
          <p className="text-xs text-vz-muted mt-1">{new Date().toLocaleDateString('en-IN', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })}</p>
        </div>
        <DashboardRefreshBar onRefresh={() => setRefreshTick((t) => t + 1)} />
      </motion.div>

      {/* Period Filter — drives every card and chart below */}
      <div className="flex items-center gap-1 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-1 w-fit shadow-sm">
        {(Object.keys(PERIOD_LABELS) as Period[]).map(p => (
          <button
            key={p}
            onClick={() => setPeriod(p)}
            className={`px-3 py-1.5 rounded-none text-xs font-semibold transition-all cursor-pointer ${
              period === p
                ? 'bg-[#405189] text-white shadow-sm'
                : 'text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200'
            }`}
          >
            {PERIOD_LABELS[p]}
          </button>
        ))}
      </div>

      {/* Total Requirements + Core KPIs (live) */}
      {pipe && reqs ? (
        <>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <StatsCard title="Total Requirements" value={reqs.total}      icon="fa-solid fa-file-lines"    color="indigo" delay={0} change={reqs.change_pct}
              onClick={() => openInNewTab('/jobs', ['jobs.view_jobdescription'], { period: API_PERIOD[period], label: 'Total Requirements' })}
            />
            <StatsCard title="Pending"            value={reqs.pending}    icon="fa-solid fa-hourglass"     color="amber"  delay={1}
              onClick={() => openInNewTab('/jobs', ['jobs.view_jobdescription'], { pending: '1', label: 'Pending' })}
            />
            <StatsCard title="Submitted"          value={pipe.submitted}  icon="fa-solid fa-paper-plane"   color="blue"   delay={2}
              onClick={() => openInNewTab('/candidates', ['candidates.view_candidate'], { pm_metric: 'submitted', period: API_PERIOD[period], label: 'Submitted' })}
            />
            <StatsCard title="Shortlisted"        value={pipe.shortlisted}icon="fa-solid fa-star"          color="teal"   delay={3}
              onClick={() => openInNewTab('/candidates', ['candidates.view_candidate'], { pm_metric: 'shortlisted', period: API_PERIOD[period], label: 'Shortlisted' })}
            />
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <StatsCard title="Offered"        value={pipe.offered}        icon="fa-solid fa-envelope-open" color="purple" delay={0}
              onClick={() => openInNewTab('/candidates', ['candidates.view_candidate'], { pm_metric: 'offered', period: API_PERIOD[period], label: 'Offered' })}
            />
            <StatsCard title="Joined"         value={pipe.joined}         icon="fa-solid fa-user-check"    color="green"  delay={1}
              onClick={() => openInNewTab('/candidates', ['candidates.view_candidate'], { pm_metric: 'joined', period: API_PERIOD[period], label: 'Joined' })}
            />
            <StatsCard title="Offer Rejected" value={pipe.offer_rejected} icon="fa-solid fa-user-xmark"    color="orange" delay={2}
              onClick={() => openInNewTab('/candidates', ['candidates.view_candidate'], { pm_metric: 'offer_rejected', period: API_PERIOD[period], label: 'Offer Rejected' })}
            />
            <StatsCard title="Rejected"       value={pipe.rejected}       icon="fa-solid fa-circle-xmark"  color="red"    delay={3}
              onClick={() => openInNewTab('/candidates', ['candidates.view_candidate'], { pm_metric: 'rejected', period: API_PERIOD[period], label: 'Rejected' })}
            />
          </div>
        </>
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {[...Array(8)].map((_, i) => <div key={i} className="h-36 bg-slate-100 dark:bg-slate-800 rounded-none animate-pulse" />)}
        </div>
      )}

      {/* Charts (live) */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 shadow-sm">
          <h3 className="text-sm font-bold text-slate-800 dark:text-white mb-1">Candidates Added Trend</h3>
          <p className="text-xs text-slate-400 mb-3">{PERIOD_LABELS[period]} breakdown</p>
          {pipe ? (
            pipe.trend.some((t) => t.value > 0) ? (
              <SimpleBarChart data={pipe.trend} primaryColor="#405189" />
            ) : (
              <p className="text-sm text-slate-400 dark:text-slate-500 text-center py-8">No candidates added in this period.</p>
            )
          ) : (
            <div className="h-32 bg-slate-100 dark:bg-slate-800 rounded-none animate-pulse" />
          )}
        </div>
        <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 shadow-sm">
          <h3 className="text-sm font-bold text-slate-800 dark:text-white mb-1">Overall Funnel</h3>
          <p className="text-xs text-slate-400 mb-3">End-to-end · {offerRate}% offer rate</p>
          {pipe ? (
            pipe.submitted > 0 ? (
              <RecruitmentFunnel stages={funnel} />
            ) : (
              <p className="text-sm text-slate-400 dark:text-slate-500 text-center py-8">No submissions in this period yet.</p>
            )
          ) : (
            <div className="h-32 bg-slate-100 dark:bg-slate-800 rounded-none animate-pulse" />
          )}
        </div>
      </div>

      {/* Ageing + Actions */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 shadow-sm">
          <h3 className="text-sm font-bold text-slate-800 dark:text-white mb-3">Open JD Ageing</h3>
          {pending === null ? (
            <div className="h-32 bg-slate-100 dark:bg-slate-800 rounded-none animate-pulse" />
          ) : (
            <>
              <AgeingCard data={ageing} />
              <p className="text-xs text-slate-500 dark:text-slate-400 mt-4 pt-4 border-t border-slate-100 dark:border-slate-800">
                <i className="fa-solid fa-circle-info mr-1.5 text-indigo-400" />
                {critical > 0
                  ? `${critical} JD${critical === 1 ? ' is' : 's are'} critical (>60 days open) and need${critical === 1 ? 's' : ''} escalation.`
                  : 'No JDs older than 60 days — pipeline is healthy.'}
              </p>
            </>
          )}
        </div>
        <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 shadow-sm">
          <h3 className="text-sm font-bold text-slate-800 dark:text-white mb-3">Quick Actions</h3>
          <QuickActions actions={QUICK_ACTIONS} />
          <div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-800">
            <h4 className="text-xs font-bold text-slate-700 dark:text-slate-300 mb-2">Recent Activity</h4>
            <RecentActivity activities={ACTIVITY} />
          </div>
        </div>
      </div>

      {/* Requirement tables + pipeline detail drill-downs (live) */}
      <TALiveAnalytics />

      {/* Recruiter-wise work — per-recruiter workload & pipeline metrics */}
      <RecruiterWorkTable />
    </div>
  );
}
