"use client";

import { useEffect, useMemo, useState } from "react";
import {
  FileText,
  Download,
  User,
  Search,
  Sparkles,
  ListChecks,
  ChevronRight,
} from "lucide-react";

type Profile = {
  id: string;
  name: string;
  role?: string;
  email?: string;
  journeyStart?: string;
};

type Session = {
  id: string;
  sessionNumber?: number;
  startTime: string;
  endTime?: string | null;
  duration?: number;
  overallScore?: number | null;
  emotionalTone?: string | null;
  isArchived?: boolean;
  profileId?: string;
  profile?: { name?: string; role?: string };
};

function fmtDate(d?: string | null) {
  if (!d) return "—";
  try {
    return new Date(d).toLocaleDateString();
  } catch {
    return "—";
  }
}

export default function ReportsPage() {
  const [profiles, setProfiles] = useState<Profile[]>([]);
  const [sessions, setSessions] = useState<Session[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [selectedProfileId, setSelectedProfileId] = useState<string>("");

  useEffect(() => {
    Promise.all([
      fetch("/api/profiles").then((r) => r.json()),
      fetch("/api/sessions").then((r) => r.json()),
    ]).then(([profilesRes, sessionsRes]) => {
      if (profilesRes.success) setProfiles(profilesRes.data);
      if (sessionsRes.success) setSessions(sessionsRes.data);
      setLoading(false);
    });
  }, []);

  const filteredProfiles = useMemo(() => {
    const term = search.trim().toLowerCase();
    if (!term) return profiles;
    return profiles.filter(
      (p) =>
        (p.name || "").toLowerCase().includes(term) ||
        (p.role || "").toLowerCase().includes(term) ||
        (p.email || "").toLowerCase().includes(term),
    );
  }, [profiles, search]);

  const profileById = useMemo(() => {
    const m: Record<string, Profile> = {};
    for (const p of profiles) m[p.id] = p;
    return m;
  }, [profiles]);

  const sessionsByProfile = useMemo(() => {
    const m: Record<string, Session[]> = {};
    for (const s of sessions) {
      if (s.isArchived) continue;
      const pid = s.profileId || "";
      if (!pid) continue;
      if (!m[pid]) m[pid] = [];
      m[pid].push(s);
    }
    Object.values(m).forEach((arr) =>
      arr.sort(
        (a, b) =>
          new Date(b.startTime).getTime() - new Date(a.startTime).getTime(),
      ),
    );
    return m;
  }, [sessions]);

  const selectedSessions = selectedProfileId
    ? sessionsByProfile[selectedProfileId] || []
    : [];
  const selectedProfile = selectedProfileId
    ? profileById[selectedProfileId]
    : null;

  const open = (url: string) => window.open(url, "_blank");

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

  return (
    <div className="space-y-8 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]">
          Dossiers
        </h1>
        <p className="text-sm text-[#044f54]/55 mt-1.5">
          Generate AI-analyzed PDF reports for any operative — mentor briefings, full audits, or single sessions.
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <section className="md:col-span-1 bg-white rounded-xl border border-[#044f54]/10 shadow-sm overflow-hidden flex flex-col h-[640px]">
          <header className="px-5 py-4 border-b border-[#044f54]/10 flex items-center justify-between">
            <h2 className="text-sm font-semibold tracking-tight">Operatives</h2>
            <span className="text-xs text-[#044f54]/55">
              {filteredProfiles.length}
            </span>
          </header>
          <div className="px-4 py-3 border-b border-[#044f54]/10">
            <div className="relative">
              <Search
                size={14}
                className="absolute left-3 top-1/2 -translate-y-1/2 text-[#044f54]/40"
              />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search operatives"
                className="w-full pl-9 pr-3 py-2 bg-slate-50 border border-[#044f54]/10 rounded-lg text-sm focus:border-[#044f54]/30 focus:ring-2 focus:ring-[#044f54]/10 outline-none"
              />
            </div>
          </div>
          <div className="flex-1 overflow-y-auto divide-y divide-[#044f54]/5">
            {filteredProfiles.length === 0 ? (
              <p className="p-8 text-sm text-[#044f54]/40 text-center">
                No operatives match.
              </p>
            ) : (
              filteredProfiles.map((p) => {
                const isActive = p.id === selectedProfileId;
                const sessionCount =
                  (sessionsByProfile[p.id] || []).length;
                return (
                  <button
                    key={p.id}
                    onClick={() => setSelectedProfileId(p.id)}
                    className={`w-full text-left p-4 flex items-center gap-3 transition-colors ${
                      isActive
                        ? "bg-[#044f54]/[0.06]"
                        : "hover:bg-[#044f54]/[0.03]"
                    }`}
                  >
                    <div className="w-9 h-9 rounded-full bg-[#044f54]/5 flex items-center justify-center text-[#044f54] shrink-0">
                      <User size={15} />
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="text-sm font-medium text-[#044f54] truncate">
                        {p.name}
                      </div>
                      <div className="text-xs text-[#044f54]/55 truncate">
                        {p.role || "Practitioner"} · {sessionCount}{" "}
                        {sessionCount === 1 ? "session" : "sessions"}
                      </div>
                    </div>
                    <ChevronRight
                      size={14}
                      className={`shrink-0 ${
                        isActive ? "text-[#044f54]" : "text-[#044f54]/30"
                      }`}
                    />
                  </button>
                );
              })
            )}
          </div>
        </section>

        <section className="md:col-span-2 space-y-5">
          {!selectedProfile ? (
            <div className="bg-white rounded-xl border border-dashed border-[#044f54]/15 p-10 text-center text-sm text-[#044f54]/55">
              Select an operative to view their dossier and download AI-powered PDF reports.
            </div>
          ) : (
            <>
              <div className="bg-white rounded-xl border border-[#044f54]/10 shadow-sm p-6">
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <div>
                    <h2 className="text-xl font-semibold tracking-tight">
                      {selectedProfile.name}
                    </h2>
                    <p className="text-sm text-[#044f54]/55 mt-1">
                      {selectedProfile.role || "Practitioner"}
                      {selectedProfile.journeyStart && (
                        <>
                          {" · "}Active since{" "}
                          {fmtDate(selectedProfile.journeyStart)}
                        </>
                      )}
                    </p>
                  </div>
                  <div className="text-sm text-[#044f54]/55">
                    {selectedSessions.length}{" "}
                    {selectedSessions.length === 1 ? "session" : "sessions"}
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
                  <button
                    onClick={() =>
                      open(`/api/reports/mentor/${selectedProfile.id}`)
                    }
                    className="group text-left bg-[#044f54] text-white rounded-xl p-5 hover:bg-[#044f54]/90 transition-all shadow-sm"
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Sparkles size={16} />
                        <span className="text-sm font-semibold">
                          Mentor briefing
                        </span>
                      </div>
                      <Download
                        size={16}
                        className="opacity-70 group-hover:opacity-100"
                      />
                    </div>
                    <p className="text-sm text-white/75 mt-2 leading-relaxed">
                      AI-analyzed summary of recent sessions: emotion, strengths, weaknesses, risk flags and next-step suggestions.
                    </p>
                  </button>

                  <button
                    onClick={() =>
                      open(`/api/reports/full/${selectedProfile.id}`)
                    }
                    className="group text-left bg-white border border-[#044f54]/15 text-[#044f54] rounded-xl p-5 hover:border-[#044f54]/40 hover:shadow-sm transition-all"
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <ListChecks size={16} className="text-[#044f54]/70" />
                        <span className="text-sm font-semibold">
                          Full audit dossier
                        </span>
                      </div>
                      <Download size={16} className="opacity-60" />
                    </div>
                    <p className="text-sm text-[#044f54]/65 mt-2 leading-relaxed">
                      Every session, every transcript, every drill — with AI analytics included for each session.
                    </p>
                  </button>
                </div>
              </div>

              <div className="bg-white rounded-xl border border-[#044f54]/10 shadow-sm overflow-hidden">
                <header className="px-5 py-4 border-b border-[#044f54]/10 flex items-center justify-between">
                  <h2 className="text-sm font-semibold tracking-tight">
                    Per-session reports
                  </h2>
                  <FileText size={14} className="text-[#044f54]/40" />
                </header>
                <div className="divide-y divide-[#044f54]/5">
                  {selectedSessions.length === 0 ? (
                    <p className="p-8 text-sm text-[#044f54]/40 text-center">
                      No sessions for this operative yet.
                    </p>
                  ) : (
                    selectedSessions.map((s) => (
                      <div
                        key={s.id}
                        className="p-4 px-5 flex items-center justify-between gap-4 hover:bg-[#044f54]/[0.02] transition-colors"
                      >
                        <div className="min-w-0">
                          <div className="text-sm font-medium text-[#044f54]">
                            Mission log #{s.sessionNumber ?? "—"}
                          </div>
                          <div className="text-xs text-[#044f54]/55 mt-0.5">
                            {fmtDate(s.startTime)}
                            {" · "}
                            {s.overallScore != null
                              ? `Score ${s.overallScore}`
                              : "Score —"}
                            {s.emotionalTone ? ` · ${s.emotionalTone}` : ""}
                          </div>
                        </div>
                        <button
                          onClick={() => open(`/api/reports/session/${s.id}`)}
                          className="flex items-center gap-2 px-3 py-1.5 bg-[#044f54]/5 text-[#044f54] rounded-lg text-xs font-medium hover:bg-[#044f54]/10"
                        >
                          <Download size={12} /> PDF
                        </button>
                      </div>
                    ))
                  )}
                </div>
              </div>
            </>
          )}
        </section>
      </div>
    </div>
  );
}
