'use client';

import {
  Activity,
  Building2,
  Calendar,
  ClipboardCheck,
  FileText,
  GraduationCap,
  LogIn,
  Users,
} from 'lucide-react';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useAdminSession } from '@/components/admin-shell';
import {
  EmptyState,
  ErrorBanner,
  LoadingSkeleton,
  StatCard,
  StatusBadge,
} from '@/components/ui/admin-ui';
import {
  proxyFetch,
  type AcademicOverviewPayload,
  type AdminStudentsResponse,
  type AuditLogEntry,
  type TeacherListItem,
} from '@/lib/proxy-client';

interface DashboardMetricsState {
  loading: boolean;
  studentSummary: AdminStudentsResponse['summary'] | null;
  teacherCount: number | null;
  programsCount: number | null;
  departmentsCount: number | null;
  auditLogs: AuditLogEntry[];
  auditRestricted: boolean;
  errorMessage: string | null;
}

export function DashboardOverview() {
  const { authenticated, sessionChecked, hasPermission } = useAdminSession();
  const [state, setState] = useState<DashboardMetricsState>({
    loading: false,
    studentSummary: null,
    teacherCount: null,
    programsCount: null,
    departmentsCount: null,
    auditLogs: [],
    auditRestricted: false,
    errorMessage: null,
  });

  useEffect(() => {
    if (!sessionChecked || !authenticated) {
      return;
    }

    let cancelled = false;
    void Promise.all([
      hasPermission('student.verify')
        ? proxyFetch<AdminStudentsResponse>('admin/students?limit=1')
        : Promise.resolve(null),
      hasPermission('teacher.manage')
        ? proxyFetch<TeacherListItem[]>('admin/teachers')
        : Promise.resolve(null),
      hasPermission('academic.structure.manage')
        ? proxyFetch<AcademicOverviewPayload>('admin/academics/overview')
        : Promise.resolve(null),
      hasPermission('audit.read')
        ? proxyFetch<AuditLogEntry[]>('admin/audit-logs?limit=8')
        : Promise.resolve(null),
    ]).then(([studentsRes, teachersRes, academicsRes, auditRes]) => {
      if (cancelled) return;

      const auditForbidden =
        auditRes !== null &&
        !auditRes.success &&
        (auditRes.error.code === 'FORBIDDEN' || auditRes.error.code === 'HTTP_403');

      setState({
        loading: false,
        studentSummary: studentsRes?.success ? studentsRes.data.summary : null,
        teacherCount: teachersRes?.success ? teachersRes.data.length : null,
        programsCount: academicsRes?.success ? academicsRes.data.programs.length : null,
        departmentsCount: academicsRes?.success ? academicsRes.data.departments.length : null,
        auditLogs: auditRes?.success ? auditRes.data : [],
        auditRestricted: auditForbidden || !hasPermission('audit.read'),
        errorMessage:
          studentsRes && !studentsRes.success && studentsRes.error.code !== 'HTTP_403'
            ? studentsRes.error.message
            : null,
      });
    });

    return () => {
      cancelled = true;
    };
  }, [authenticated, sessionChecked, hasPermission]);

  if (sessionChecked && !authenticated) {
    return (
      <section className="rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)] p-6">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div>
            <h2 className="text-base font-semibold text-slate-900">
              Administrator Sign In Required
            </h2>
            <p className="mt-1 text-sm text-slate-600">
              Sign in through the same-origin HTTP-only BFF proxy to load live institutional
              metrics, verification queues, and audit trails.
            </p>
          </div>
          <Link
            href="/login"
            className="inline-flex items-center gap-1.5 rounded-lg bg-slate-900 px-4 py-2 text-xs font-medium text-white hover:bg-slate-800"
          >
            <LogIn className="h-4 w-4" aria-hidden="true" />
            <span>Sign In</span>
          </Link>
        </div>
      </section>
    );
  }

  const pendingTotal =
    state.studentSummary !== null
      ? state.studentSummary.pendingVerification + state.studentSummary.underReview
      : '—';

  return (
    <div className="space-y-6">
      {state.errorMessage && <ErrorBanner message={state.errorMessage} />}

      {/* Summary KPI Cards backed strictly by real API responses */}
      <section
        aria-label="Institutional Summary"
        className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4"
      >
        <StatCard
          label="Total Students"
          value={state.studentSummary?.total ?? '—'}
          subtitle={
            state.studentSummary
              ? `${state.studentSummary.verified} verified • ${state.studentSummary.rejected} rejected`
              : state.loading
                ? 'Loading student summary...'
                : 'Metrics unavailable for current role'
          }
          href="/students"
          icon={<GraduationCap className="h-4 w-4 text-slate-500" aria-hidden="true" />}
        />
        <StatCard
          label="Pending Verifications"
          value={pendingTotal}
          subtitle={
            state.studentSummary
              ? `${state.studentSummary.pendingVerification} pending • ${state.studentSummary.underReview} under review`
              : state.loading
                ? 'Loading queue...'
                : 'Queue unavailable'
          }
          href="/verifications"
          icon={<ClipboardCheck className="h-4 w-4 text-slate-500" aria-hidden="true" />}
        />
        <StatCard
          label="Faculty Accounts"
          value={state.teacherCount ?? '—'}
          subtitle="Provisioned teacher profiles"
          href="/teachers"
          icon={<Users className="h-4 w-4 text-slate-500" aria-hidden="true" />}
        />
        <StatCard
          label="Academic Programs"
          value={state.programsCount ?? '—'}
          subtitle={
            state.departmentsCount !== null
              ? `${state.departmentsCount} configured departments`
              : 'Diploma & BSc structures'
          }
          href="/academics"
          icon={<Building2 className="h-4 w-4 text-slate-500" aria-hidden="true" />}
        />
      </section>

      {/* Two-Column Activity + Quick Links / Notices */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-12">
        <section className="rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)] lg:col-span-7">
          <div className="flex items-center justify-between border-b border-[var(--saic-border)] px-5 py-3.5">
            <h2 className="flex items-center gap-2 text-sm font-semibold text-slate-900">
              <Activity className="h-4 w-4 text-slate-600" aria-hidden="true" />
              <span>Recent Administrative Activity</span>
            </h2>
            <span className="text-xs text-slate-500">Audit Log</span>
          </div>
          {state.loading ? (
            <LoadingSkeleton rows={4} />
          ) : state.auditRestricted ? (
            <div className="p-5 text-sm text-slate-600">
              Audit activity requires <code>audit.read</code> permission.
            </div>
          ) : state.auditLogs.length === 0 ? (
            <div className="p-5 text-sm text-slate-600">
              No recent administrative events logged yet.
            </div>
          ) : (
            <ul className="divide-y divide-slate-100">
              {state.auditLogs.map((entry) => (
                <li
                  key={entry.id}
                  className="flex flex-wrap items-center justify-between gap-2 px-5 py-3 text-xs"
                >
                  <div>
                    <p className="font-medium text-slate-900">{entry.action}</p>
                    <p className="text-slate-500">
                      {entry.entityType}
                      {entry.actor ? ` • by ${entry.actor.fullName}` : ''}
                    </p>
                  </div>
                  <time className="text-slate-500" dateTime={entry.createdAt}>
                    {new Date(entry.createdAt).toLocaleString(undefined, { timeZone: 'Asia/Dhaka' })}
                  </time>
                </li>
              ))}
            </ul>
          )}
        </section>

        <div className="space-y-6 lg:col-span-5">
          <section className="rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)] p-5">
            <h2 className="text-sm font-semibold text-slate-900">Quick Navigation</h2>
            <div className="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-2">
              <Link
                href="/verifications"
                className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-50"
              >
                <ClipboardCheck className="h-4 w-4" aria-hidden="true" />
                <span>Review ID Queue</span>
              </Link>
              <Link
                href="/students"
                className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-50"
              >
                <GraduationCap className="h-4 w-4" aria-hidden="true" />
                <span>Student Directory</span>
              </Link>
              <Link
                href="/teachers"
                className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-50"
              >
                <Users className="h-4 w-4" aria-hidden="true" />
                <span>Manage Faculty</span>
              </Link>
              <Link
                href="/routine"
                className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-50"
              >
                <Calendar className="h-4 w-4" aria-hidden="true" />
              <span>View Class Routine</span>
              </Link>
            </div>
          </section>

          <section className="rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)] p-5">
            <div className="flex items-center justify-between">
              <h2 className="flex items-center gap-2 text-sm font-semibold text-slate-900">
                <FileText className="h-4 w-4 text-slate-600" aria-hidden="true" />
                <span>Notices &amp; Announcements</span>
              </h2>
              <Link href="/notices" className="text-xs font-medium text-slate-700 hover:underline">
                Manage
              </Link>
            </div>
            <p className="mt-2 text-xs text-slate-600">
              Publish and target institutional, department, or cohort notices from the Notices
              module.
            </p>
            <div className="mt-3">
              <EmptyState
                icon={<FileText className="h-6 w-6" aria-hidden="true" />}
                title="Open Notice Board"
                description="View published, draft, and archived institutional notices."
                action={
                  <Link
                    href="/notices"
                    className="inline-flex items-center gap-1 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50"
                  >
                    Manage Notices
                  </Link>
                }
              />
            </div>
          </section>
        </div>
      </div>

      {/* Preserve explicit status legend */}
      <div className="flex flex-wrap items-center gap-2 text-xs text-slate-500">
        <span>Status legend:</span>
        <StatusBadge status="VERIFIED" />
        <StatusBadge status="PENDING_VERIFICATION" />
        <StatusBadge status="UNDER_REVIEW" />
        <StatusBadge status="REJECTED" />
      </div>
    </div>
  );
}
