'use client';

import { Suspense, useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import Cookies from 'js-cookie';
import { api } from '@/lib/api';
import type { User } from '@/types';
import { useAuth } from '@/components/auth-context';
import RoleDashboard, { type DashboardStats } from '@/components/RoleDashboard';
import AdminDashboard from '@/components/dashboard/AdminDashboard';
import RecruiterDashboard from '@/components/dashboard/RecruiterDashboard';
import HiringManagerDashboard from '@/components/dashboard/HiringManagerDashboard';
import JDApprovalMonitoring from '@/components/dashboard/JDApprovalMonitoring';
import TADashboard from '@/components/dashboard/TADashboard';
import ProjectManagerDashboard from '@/components/dashboard/ProjectManagerDashboard';
import ClientFilterSelect from '@/components/dashboard/ClientFilterSelect';

function countOf(res: unknown): number | undefined {
  const data = (res as { data?: unknown })?.data;
  if (Array.isArray(data)) return data.length;
  const d = data as { count?: number; results?: unknown[] } | undefined;
  if (d && typeof d.count === 'number') return d.count;
  if (d && Array.isArray(d.results)) return d.results.length;
  return undefined;
}

function DashboardContent() {
  const { user } = useAuth();
  const [stats, setStats] = useState<DashboardStats>({});
  // Client filter — set by the "Clients" dropdown in the sidebar. When present
  // (and the user isn't a candidate) the dashboard switches to the
  // client-scoped view without a reload.
  const selectedClient = useSearchParams().get('client');

  // Set while an admin is impersonating another role (their own tokens are stashed).
  // The role switcher itself now lives in the Header, available on every page.
  const impersonating = typeof window !== 'undefined' && !!Cookies.get('admin_access_token');
  const impersonatedRole = user?.role || '';

  const returnToAdmin = () => {
    const access = Cookies.get('admin_access_token');
    const refresh = Cookies.get('admin_refresh_token');
    if (access) Cookies.set('access_token', access);
    if (refresh) Cookies.set('refresh_token', refresh);
    Cookies.remove('admin_access_token');
    Cookies.remove('admin_refresh_token');
    window.location.reload();
  };

  const loadStats = (u: User) => {
    const perms = u.permissions || [];
    const isAdmin = u.role === 'ADMIN';
    if (isAdmin || perms.includes('jobs.view_jobdescription')) {
      api.get('/jobs/').then((r) => setStats((s) => ({ ...s, jobs: countOf(r) }))).catch(() => {});
    };
    if (isAdmin || perms.includes('clients.view_client')) {
      api.get('/clients/').then((r) => setStats((s) => ({ ...s, clients: countOf(r) }))).catch(() => {});
    }
  if (isAdmin) {
    api.get('/users/admin/roles/')
      .then((r: any) => {
        const total = (r.data || []).reduce(
          (sum: number, x: { user_count?: number }) => sum + (x.user_count || 0),
          0
        );
        setStats((s) => ({ ...s, users: total }));
      })
      .catch((err) => {
        console.error(err);
      });
  }
};

  // `stats` is read by RoleDashboard only. Roles that render their own
  // dashboard component below (and the client-scoped view) never display it, so
  // fetching it for them was pure waste — two requests per load. Skipping it
  // changes nothing on screen; RoleDashboard roles still get their counts.
  const usesRoleDashboard =
    !selectedClient &&
    !['ADMIN', 'RECRUITER', 'HIRING_MANAGER', 'TA_MANAGER', 'PROJECT_MANAGER'].includes(
      impersonatedRole,
    );

  useEffect(() => {
    if (user && usesRoleDashboard) loadStats(user);
  }, [user, usesRoleDashboard]);

  if (!user) return null;

  return (
        <main className="flex-1 p-4 sm:p-8 overflow-y-auto w-full">
          <div className="max-w-5xl w-full mx-auto space-y-6">
            {/* Active impersonation banner — the whole ATS is running as this role */}
            {impersonating && (
              <div className="bg-amber-50 dark:bg-amber-950/30 border border-amber-300 dark:border-amber-800 p-4 flex flex-wrap items-center justify-between rounded-none shadow-sm gap-3">
                <div className="flex items-center gap-2">
                  <i className="fa-solid fa-user-secret text-amber-600 dark:text-amber-400 text-base"></i>
                  <div>
                    <span className="text-amber-800 dark:text-amber-200 text-sm font-semibold">
                      Viewing the ATS as {user.full_name || user.email} ({user.role})
                    </span>
                    <p className="text-[10px] text-amber-600/80 dark:text-amber-400/80 mt-0.5">
                      Sidebar, permissions and every page reflect this role until you return.
                    </p>
                  </div>
                </div>
                <button
                  onClick={returnToAdmin}
                  className="px-3 py-1.5 bg-[#405189] hover:bg-[#354575] text-white text-xs font-semibold flex items-center gap-1.5 transition shadow-sm cursor-pointer"
                >
                  <i className="fa-solid fa-arrow-left"></i> Return to Admin
                </button>
              </div>
            )}

            {/* Client filter for non-admin roles' global dashboards — the admin
                dashboard and the client-scoped view carry it in their own banner.
                RECRUITER is excluded here because its dashboard renders this same
                filter inline, to the right of its Job Description filter, so both
                sit on one aligned row. */}
            {!selectedClient && impersonatedRole !== 'ADMIN' && impersonatedRole !== 'CANDIDATE'
              && impersonatedRole !== 'RECRUITER' && (
              <div className="flex justify-end">
                <ClientFilterSelect />
              </div>
            )}

            {/* Client-scoped view — any role except candidates. Shows only the
                KPI cards, Open JDs and JD approval logs for that client. */}
            {selectedClient && impersonatedRole !== 'CANDIDATE' ? (
              <>
                <AdminDashboard user={user} clientId={selectedClient} />
                <div className="mt-6">
                  <JDApprovalMonitoring clientId={selectedClient} />
                </div>
              </>
            ) : impersonatedRole === 'ADMIN' ? (
              <>
                <AdminDashboard user={user} />
                <div className="mt-6">
                  <JDApprovalMonitoring />
                </div>
              </>
            ) : impersonatedRole === 'RECRUITER' ? (
              <RecruiterDashboard user={user} />
            ) : impersonatedRole === 'HIRING_MANAGER' ? (
              <HiringManagerDashboard user={user} />
            ) : impersonatedRole === 'TA_MANAGER' ? (
              <TADashboard user={user} />
            ) : impersonatedRole === 'PROJECT_MANAGER' ? (
              <ProjectManagerDashboard user={user} />
            ) : (
              <RoleDashboard user={user} stats={stats} />
            )}
          </div>
        </main>
  );
}

export default function DashboardPage() {
  // useSearchParams (client filter) requires a Suspense boundary.
  return (
    <Suspense fallback={null}>
      <DashboardContent />
    </Suspense>
  );
}
