'use client';

import { useCallback, useEffect, useState } from 'react';
import DashboardRefreshBar from './DashboardRefreshBar';
import { api } from '@/lib/api';
import type { User } from '@/types';
import { motion } from 'framer-motion';
import SimpleBarChart from './SimpleBarChart';
import RecruitmentFunnel from './RecruitmentFunnel';
import QuickActions from './QuickActions';
import RecentActivity, { type Activity } from './RecentActivity';
import PMLiveAnalytics, { type PMDashboardData } from './PMLiveAnalytics';
import ActionPointsCard, { type ActionPoint } from './ActionPointsCard';

const QUICK_ACTIONS = [
  { label: 'Add Requirement', icon: 'fa-solid fa-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',                       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 Pipeline',   icon: 'fa-solid fa-chart-simple',href: '/jobs',                        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' },
];

export default function ProjectManagerDashboard({ user }: { user: User }) {
  const name = user.full_name || user.email.split('@')[0];
  // Fed by PMLiveAnalytics — one fetch (with polling) powers cards, charts and the table
  const [data, setData] = useState<PMDashboardData | null>(null);

  // Action Points — additive, read-only. Scoped server-side to the PM's own
  // requirements and already RBAC-filtered, so nothing here widens visibility.
  const [actionPoints, setActionPoints] = useState<ActionPoint[] | null>(null);
  const [actionsLoading, setActionsLoading] = useState(true);

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

  useEffect(() => {
    loadActionPoints();
    // Reuse the existing refresh signals rather than adding new polling.
    const onWsEvent = (e: Event) => {
      const name = (e as CustomEvent).detail?.event;
      if (['jd_submitted', 'jd_approved', 'jd_rejected', 'jd_pending_approval'].includes(name)) {
        loadActionPoints();
      }
    };
    window.addEventListener('notification-received', loadActionPoints);
    window.addEventListener('ws-event', onWsEvent);
    return () => {
      window.removeEventListener('notification-received', loadActionPoints);
      window.removeEventListener('ws-event', onWsEvent);
    };
  }, [loadActionPoints]);

  const chart = data ? [
    { label: 'Submitted',   value: data.submitted,   color: '#405189' },
    { label: 'Shortlisted', value: data.shortlisted, color: '#3577f1' },
    { label: 'Offered',     value: data.offered,     color: '#f7b84b' },
    { label: 'Joined',      value: data.joined,      color: '#0ab39c' },
    { label: 'Rejected',    value: data.rejected,    color: '#f06548' },
  ] : [];

  const funnel = data ? [
    { label: 'Submitted',   value: data.submitted,   color: '#405189' },
    { label: 'Shortlisted', value: data.shortlisted, color: '#3577f1' },
    { label: 'Offered',     value: data.offered,     color: '#f7b84b' },
    { label: 'Joined',      value: data.joined,      color: '#0ab39c' },
  ] : [];

  return (
    <div className="space-y-5">
      {/* Header greeting (full width) */}
      <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">Project Manager</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={loadActionPoints} />
      </motion.div>

      {/* My Requirements — Live (left) + Action Points (right) — perfectly top-aligned */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 items-start">
        {/* Left side: My Requirements — Live (takes 2/3 width on xl screens) */}
        <div className="xl:col-span-2">
          <PMLiveAnalytics onData={setData} />
        </div>

        {/* Right side: Action Points card (takes 1/3 width on xl screens, top-aligned) */}
        <div className="xl:col-span-1">
          <ActionPointsCard
            points={actionPoints}
            loading={actionsLoading}
            subtitle="Pending items on the requirements you own. Click a row to open the module."
            emptyDescription="No pending actions on your requirements right now."
          />
        </div>
      </div>

      {/* Charts (live, from the same data) */}
      <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">Submission Pipeline</h3>
          <p className="text-xs text-slate-400 mb-3">My requirements · current snapshot</p>
          {!data ? (
            <div className="h-32 bg-slate-100 dark:bg-slate-800 rounded-none animate-pulse" />
          ) : data.submitted > 0 || data.rejected > 0 ? (
            <SimpleBarChart data={chart} />
          ) : (
            <p className="text-sm text-slate-400 dark:text-slate-500 text-center py-8">No pipeline activity on your requirements yet.</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-1">Recruitment Funnel</h3>
          <p className="text-xs text-slate-400 mb-3">
            End-to-end conversion{data && data.submitted > 0 ? ` · ${((data.joined / data.submitted) * 100).toFixed(1)}% join rate` : ''}
          </p>
          {!data ? (
            <div className="h-32 bg-slate-100 dark:bg-slate-800 rounded-none animate-pulse" />
          ) : data.submitted > 0 ? (
            <RecruitmentFunnel stages={funnel} />
          ) : (
            <p className="text-sm text-slate-400 dark:text-slate-500 text-center py-8">No submissions yet.</p>
          )}
        </div>
      </div>

      {/* Activity + 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-4">Recent Activity</h3>
          <RecentActivity activities={ACTIVITY} />
        </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>
      </div>
    </div>
  );
}
