"use client";

import { useEffect, useMemo, useState } from "react";
import {
  Users,
  Activity,
  Clock,
  ShieldAlert,
  Target,
  Database,
  ChevronRight,
} from "lucide-react";
import Link from "next/link";

export default function DashboardPage() {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/analytics/overview")
      .then((res) => res.json())
      .then((json) => {
        if (json.success) setData(json.data);
        setLoading(false);
      });
  }, []);

  const operatives = useMemo(() => {
    if (!data?.recentSessions) return [] as Array<{
      name: string;
      profileId: string | null;
      sessionCount: number;
      lastSession: any;
    }>;

    const map = new Map<string, {
      name: string;
      profileId: string | null;
      sessionCount: number;
      lastSession: any;
    }>();

    for (const s of data.recentSessions) {
      const name = s.profile?.name || "Unknown";
      const profileId = s.profile?.id || s.profileId || null;
      const existing = map.get(name);
      if (!existing) {
        map.set(name, {
          name,
          profileId,
          sessionCount: 1,
          lastSession: s,
        });
      } else {
        existing.sessionCount += 1;
        const a = new Date(existing.lastSession?.startTime || 0).getTime();
        const b = new Date(s?.startTime || 0).getTime();
        if (b > a) existing.lastSession = s;
      }
    }

    return Array.from(map.values()).sort((a, b) => {
      const ta = new Date(a.lastSession?.startTime || 0).getTime();
      const tb = new Date(b.lastSession?.startTime || 0).getTime();
      return tb - ta;
    });
  }, [data]);

  if (loading)
    return (
      <div className="h-full flex items-center justify-center text-sm text-[#044f54]/60">
        Loading dashboard…
      </div>
    );

  if (!data)
    return (
      <div className="h-full flex items-center justify-center text-sm text-red-600">
        Could not load analytics. Please try again.
      </div>
    );

  const stats = [
    {
      label: "Total operatives",
      value: data.totalPractitioners,
      icon: Users,
    },
    {
      label: "Mission records",
      value: data.totalSessions,
      icon: Database,
    },
    {
      label: "Avg mastery score",
      value: data.averageScore,
      icon: Target,
    },
    {
      label: "Training time",
      value: `${data.totalTrainingHours}h`,
      icon: Clock,
    },
  ];

  return (
    <div className="space-y-10 max-w-6xl mx-auto animate-in fade-in duration-500">
      <div className="border-b border-[#044f54]/10 pb-5">
        <h1 className="text-2xl md:text-3xl font-semibold tracking-tight text-[#044f54]">
          Command center
        </h1>
        <p className="text-sm text-[#044f54]/55 mt-1.5">
          Real-time mission analytics and operative status.
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat, i) => (
          <div
            key={i}
            className="bg-white p-5 rounded-xl border border-[#044f54]/10 shadow-sm hover:border-[#044f54]/30 hover:shadow-md transition-all"
          >
            <div className="flex items-center gap-4">
              <div className="p-2.5 bg-[#044f54]/5 text-[#044f54] rounded-lg">
                <stat.icon size={18} />
              </div>
              <div className="min-w-0">
                <p className="text-xs font-medium text-[#044f54]/55">
                  {stat.label}
                </p>
                <h3 className="text-2xl font-semibold text-[#044f54] tracking-tight mt-0.5">
                  {stat.value}
                </h3>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <section className="bg-white rounded-xl border border-[#044f54]/10 shadow-sm overflow-hidden flex flex-col h-[500px]">
          <header className="px-5 py-4 border-b border-[#044f54]/10 flex justify-between items-center">
            <h2 className="text-sm font-semibold text-[#044f54] tracking-tight">
              Latest mission logs
            </h2>
            <Link
              href="/admin/sessions"
              className="text-xs font-medium text-[#044f54]/60 hover:text-[#044f54] flex items-center gap-1"
            >
              View all
              <ChevronRight size={14} />
            </Link>
          </header>
          <div className="flex-1 overflow-y-auto divide-y divide-[#044f54]/5">
            {operatives.length === 0 ? (
              <p className="p-12 text-center text-sm text-[#044f54]/40">
                No mission logs yet.
              </p>
            ) : (
              operatives.map((op) => {
                const last = op.lastSession;
                const lastDate = last?.startTime
                  ? new Date(last.startTime).toLocaleDateString()
                  : "—";
                const score = last?.overallScore ?? null;
                const inner = (
                  <div className="p-4 px-5 flex items-center justify-between hover:bg-[#044f54]/[0.03] transition-colors">
                    <div className="flex items-center gap-4 min-w-0">
                      <div className="w-9 h-9 rounded-full bg-[#044f54]/5 flex items-center justify-center text-[#044f54] shrink-0">
                        <Activity size={15} />
                      </div>
                      <div className="min-w-0">
                        <p className="font-medium text-[#044f54] text-sm truncate">
                          {op.name}
                        </p>
                        <p className="text-xs text-[#044f54]/55 mt-0.5">
                          {op.sessionCount}{" "}
                          {op.sessionCount === 1 ? "session" : "sessions"}
                          {" · "}last on {lastDate}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3 shrink-0">
                      <span className="inline-block px-3 py-1 bg-[#044f54]/[0.06] text-[#044f54] rounded-full text-xs font-medium">
                        Score {score ?? "—"}
                      </span>
                      <ChevronRight
                        size={16}
                        className="text-[#044f54]/30"
                      />
                    </div>
                  </div>
                );
                return op.profileId ? (
                  <Link
                    key={op.name}
                    href={`/admin/practitioners/${op.profileId}`}
                  >
                    {inner}
                  </Link>
                ) : (
                  <div key={op.name}>{inner}</div>
                );
              })
            )}
          </div>
        </section>

        <section className="bg-white rounded-xl border border-[#044f54]/10 shadow-sm overflow-hidden flex flex-col h-[500px]">
          <header className="px-5 py-4 border-b border-[#044f54]/10 bg-red-50/60 flex justify-between items-center">
            <h2 className="text-sm font-semibold text-red-800 tracking-tight">
              Critical alerts
            </h2>
            <ShieldAlert size={16} className="text-red-500" aria-hidden />
          </header>
          <div className="flex-1 overflow-y-auto divide-y divide-[#044f54]/5">
            {data.practitionersNeedingAttention.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full text-[#044f54]/40 p-8 text-center">
                <ShieldAlert
                  size={36}
                  className="mb-4 opacity-20"
                  aria-hidden
                />
                <p className="text-sm leading-relaxed">
                  All operatives are within optimal parameters.
                </p>
              </div>
            ) : (
              data.practitionersNeedingAttention.map((p: any, idx: number) => (
                <div
                  key={idx}
                  className="p-4 px-5 flex items-center justify-between hover:bg-red-50/50 transition-colors"
                >
                  <div className="flex items-center gap-4 min-w-0">
                    <div className="w-9 h-9 rounded-full bg-red-100 flex items-center justify-center text-red-600 shrink-0">
                      <ShieldAlert size={15} />
                    </div>
                    <div className="min-w-0">
                      <Link
                        href={`/admin/practitioners/${p.id}`}
                        className="font-medium text-[#044f54] text-sm hover:text-red-600 truncate block"
                      >
                        {p.name}
                      </Link>
                      <p className="text-xs text-[#044f54]/55 mt-0.5">
                        Stuck on{" "}
                        <span className="text-red-600 font-medium">
                          {p.stuckElement}
                        </span>
                      </p>
                    </div>
                  </div>
                  <span className="inline-block px-3 py-1 bg-red-100 text-red-700 rounded-full text-xs font-medium shrink-0">
                    {p.failedAttempts} failures
                  </span>
                </div>
              ))
            )}
          </div>
        </section>
      </div>
    </div>
  );
}
