import { useState, useEffect, useMemo } from "react";
import localforage from "localforage";
import {
  User,
  Play,
  Clock,
  BarChart3,
  Database,
  Folder,
  ChevronDown,
  ChevronRight,
  FileText,
  Download,
  Trash2,
} from "lucide-react";
import { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";
import { motion } from "motion/react";
import { GoogleGenAI } from "@google/genai";

export function SessionsOverview({ onClose }: { onClose: () => void }) {
  const [sessions, setSessions] = useState<any[]>([]);
  const [selectedSession, setSelectedSession] = useState<any>(null);
  const [isGeneratingPdf, setIsGeneratingPdf] = useState(false);
  const [expandedFolders, setExpandedFolders] = useState<
    Record<string, boolean>
  >({});

  useEffect(() => {
    loadSessions();
  }, []);

  const loadSessions = async () => {
    const keys = await localforage.keys();
    const sessionKeys = keys.filter((k) => k.startsWith("rms_session_"));
    const loaded = await Promise.all(
      sessionKeys.map(async (k) => {
        const item: any = await localforage.getItem(k);
        if (item) item._key = k;
        return item;
      }),
    );
    const sorted = loaded
      .filter(Boolean)
      .sort((a: any, b: any) => b.timestamp - a.timestamp);
    setSessions(sorted);
  };

  const groupedSessions = useMemo(() => {
    const groups: Record<string, any[]> = {};
    sessions.forEach((s) => {
      const name = s.candidateName || "Unknown";
      if (!groups[name]) groups[name] = [];
      groups[name].push(s);
    });
    return groups;
  }, [sessions]);

  const toggleFolder = (name: string) => {
    setExpandedFolders((prev) => ({ ...prev, [name]: !prev[name] }));
  };

  const playAudio = (blob: Blob) => {
    const url = URL.createObjectURL(blob);
    const audio = new Audio(url);
    audio.play();
  };

  const downloadAudio = (blob: Blob, sessionName: string) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `RMS_Audio_${sessionName.replace(/\\s+/g, "_")}.webm`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  const deleteSession = async (key: string, e?: React.MouseEvent) => {
    if (e) e.stopPropagation();
    await localforage.removeItem(key);
    if (selectedSession && selectedSession._key === key)
      setSelectedSession(null);
    loadSessions();
  };

  const deleteFolder = async (name: string, e: React.MouseEvent) => {
    e.stopPropagation();
    const toDelete = groupedSessions[name] || [];
    for (const s of toDelete) {
      await localforage.removeItem(s._key);
      if (selectedSession && selectedSession._key === s._key) {
        setSelectedSession(null);
      }
    }
    loadSessions();
  };

  const downloadSessionPDF = async (session: any) => {
    setIsGeneratingPdf(true);
    let aiAnalytics =
      "AI Analytics could not be generated. Please ensure your API key is set.";

    // Attempt to generate analytics
    try {
      const customApiKey =
        typeof window !== "undefined"
          ? localStorage.getItem("rms_gemini_api_key")
          : null;
      const apiKey = customApiKey || process.env.NEXT_PUBLIC_GEMINI_API_KEY;
      if (apiKey) {
        const ai = new GoogleGenAI({ apiKey });
        const logsText = (session.logs || [])
          .map((l: any) => `${l.role.toUpperCase()}: ${l.text}`)
          .join("\n");
        const prompt = `Analyze this comprehensive conversation transcript between our elite training agent and the student/professional. Give me highly detailed session notes, capturing the emotional tone and frustration levels of the user if present. Provide deep insights into their performance, 3 extensive bullet points of behavioral and performance analytics, and 3 actionable, empathetic suggestions for the student to improve. Frame the output to help a human professional mentor understand exactly how to help this student succeed and cope with their current stage of learning.\n\nTranscript:\n${logsText}`;

        const response = await ai.models.generateContent({
          model: "gemini-3.1-flash",
          contents: prompt,
        });

        if (response.text) {
          aiAnalytics = response.text.replace(/\*\*/g, ""); // Remove bold markdown for PDF
        }
      }
    } catch (e) {
      console.warn("AI Analytics Failed", e);
    }

    const doc = new jsPDF();
    doc.setFontSize(18);
    doc.text("RMS Session Analytics & Transcript", 14, 22);

    doc.setFontSize(12);
    doc.text(`Candidate: ${session.candidateName}`, 14, 32);
    doc.text(`Session ID: ${session.id}`, 14, 40);
    // Use startTime/endTime if available, fallback to timestamp
    doc.text(
      `Start: ${session.startTime ? new Date(session.startTime).toLocaleString() : new Date(session.timestamp).toLocaleString()}`,
      14,
      48,
    );
    doc.text(
      `End: ${session.endTime ? new Date(session.endTime).toLocaleString() : "N/A"}`,
      14,
      56,
    );
    doc.text(`Duration: ${session.duration} seconds`, 14, 64);
    doc.text(`Chapters Tested: ${session.chaptersTested || 0}`, 14, 72);

    doc.setFontSize(14);
    doc.text("AI Analytics & Suggestions", 14, 88);
    doc.setFontSize(10);

    const splitAnalytics = doc.splitTextToSize(aiAnalytics, 180);
    doc.text(splitAnalytics, 14, 96);

    const analyticsHeight = splitAnalytics.length * 5;

    doc.setFontSize(14);
    const transcriptY = Math.min(96 + analyticsHeight + 15, 200);
    doc.text("Transcript", 14, transcriptY);

    const tableData = (session.logs || []).map((log: any) => [
      log.role.toUpperCase(),
      log.text,
    ]);

    autoTable(doc, {
      startY: transcriptY + 6,
      head: [["Role", "Message"]],
      body: tableData,
      theme: "grid",
      styles: { font: "helvetica", fontSize: 10, cellPadding: 3 },
      columnStyles: {
        0: { cellWidth: 30, fontStyle: "bold" },
        1: { cellWidth: "auto" },
      },
    });

    doc.save(
      `RMS_Session_${session.candidateName.replace(/\s+/g, "_")}_${session.id.substring(0, 8)}.pdf`,
    );
    setIsGeneratingPdf(false);
  };

  const downloadFolderPDF = async (name: string, e: React.MouseEvent) => {
    e.stopPropagation();
    const docs = groupedSessions[name] || [];
    if (docs.length === 0) return;

    setIsGeneratingPdf(true);
    let aiAnalytics =
      "AI Analytics could not be generated. Please ensure your API key is set.";

    try {
      const customApiKey =
        typeof window !== "undefined"
          ? localStorage.getItem("rms_gemini_api_key")
          : null;
      const apiKey = customApiKey || process.env.NEXT_PUBLIC_GEMINI_API_KEY;
      if (apiKey) {
        const ai = new GoogleGenAI({ apiKey });
        const logsTokens = docs
          .map(
            (s, i) =>
              `--- Session ${i + 1} ---\n` +
              (s.logs || [])
                .map((l: any) => `${l.role.toUpperCase()}: ${l.text}`)
                .join("\n"),
          )
          .join("\n\n");
        const prompt = `Analyze this series of training sessions between our training agent and the student ${name}. Give me a very detailed overall assessment, highlighting their strengths, weaknesses, and a recommended practice plan moving forward (3 bullet points). Also, analyze their emotional state and frustration levels across the sessions to help understand how to best help this professional. Keep it empathetic but professional.\n\nTranscripts:\n${logsTokens.substring(0, 30000)}`; // limit context slightly

        const response = await ai.models.generateContent({
          model: "gemini-3.1-flash",
          contents: prompt,
        });

        if (response.text) {
          aiAnalytics = response.text.replace(/\*\*/g, ""); // Remove bold markdown for PDF
        }
      }
    } catch (e) {
      console.warn("AI Analytics Failed", e);
    }

    const doc = new jsPDF();
    doc.setFontSize(18);
    doc.text(`RMS Overall Analytics: ${name}`, 14, 22);

    const totalDuration = docs.reduce(
      (acc: number, curr: any) => acc + (curr.duration || 0),
      0,
    );
    const totalTested = docs.reduce(
      (acc: number, curr: any) => acc + (curr.chaptersTested || 0),
      0,
    );

    doc.setFontSize(12);
    doc.text(`Total Sessions: ${docs.length}`, 14, 32);
    doc.text(`Total Duration: ${totalDuration} seconds`, 14, 40);
    doc.text(`Total Chapters Tested: ${totalTested}`, 14, 48);

    doc.setFontSize(14);
    doc.text("Overall Performance Analytics", 14, 64);
    doc.setFontSize(10);

    const splitAnalytics = doc.splitTextToSize(aiAnalytics, 180);
    doc.text(splitAnalytics, 14, 72);

    let currentY = 72 + splitAnalytics.length * 5 + 15;

    docs.forEach((session: any, idx: number) => {
      if (currentY > 250) {
        doc.addPage();
        currentY = 20;
      }
      doc.setFontSize(14);
      doc.text(
        `Session ${idx + 1}: ${session.startTime ? new Date(session.startTime).toLocaleString() : new Date(session.timestamp).toLocaleString()}`,
        14,
        currentY,
      );
      currentY += 8;

      const tableData = (session.logs || []).map((log: any) => [
        log.role.toUpperCase(),
        log.text,
      ]);

      autoTable(doc, {
        startY: currentY,
        head: [["Role", "Message"]],
        body: tableData,
        theme: "grid",
        styles: { font: "helvetica", fontSize: 10, cellPadding: 3 },
        columnStyles: {
          0: { cellWidth: 30, fontStyle: "bold" },
          1: { cellWidth: "auto" },
        },
      });

      currentY = (doc as any).lastAutoTable.finalY + 15;
    });

    doc.save(`RMS_Overall_${name.replace(/\s+/g, "_")}.pdf`);
    setIsGeneratingPdf(false);
  };

  return (
    <div className="fixed inset-0 z-[300] bg-slate-50/90 backdrop-blur-md flex p-4 sm:p-8 animate-in fade-in duration-300">
      <div className="w-full h-full bg-slate-50 border border-[#044f54] shadow-[0_0_50px_rgba(4,79,84,0.15)] rounded flex relative overflow-hidden animate-in slide-in-from-bottom-4 duration-300">
        <div className="absolute inset-0 pointer-events-none bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(4,79,84,0.1)_2px,rgba(4,79,84,0.1)_4px)]"></div>
        {/* Sidebar */}
        <div className="w-80 border-r border-[#044f54]/20 bg-white relative z-10 flex flex-col">
          <div className="p-4 border-b border-[#044f54]/20 flex justify-between items-center bg-[#044f54]/10">
            <div className="flex items-center gap-2">
              <Database className="w-4 h-4 text-[#044f54]" />
              <span className="text-[#044f54] font-bold text-xs tracking-widest uppercase">
                Candidates
              </span>
            </div>
            <button
              onClick={onClose}
              className="text-[#044f54]/60 hover:text-[#044f54] transition-colors bg-[#044f54]/5 hover:bg-[#044f54]/20 px-2 py-1 text-[10px] uppercase rounded"
            >
              Close
            </button>
          </div>
          <div className="flex-1 overflow-y-auto p-2 space-y-1">
            {Object.keys(groupedSessions).length === 0 && (
              <div className="text-center p-4 text-[10px] text-[#044f54]/50 uppercase">
                No records found.
              </div>
            )}
            {Object.entries(groupedSessions).map(([name, sessionList]) => (
              <div key={name} className="flex flex-col">
                <div
                  className="w-full text-left p-2 rounded flex items-center justify-between hover:bg-[#044f54]/5 text-[#044f54] select-none cursor-pointer group"
                  onClick={() => toggleFolder(name)}
                >
                  <div className="flex items-center gap-2 overflow-hidden">
                    {expandedFolders[name] ? (
                      <ChevronDown className="w-4 h-4 flex-shrink-0" />
                    ) : (
                      <ChevronRight className="w-4 h-4 flex-shrink-0" />
                    )}
                    <Folder className="w-4 h-4 flex-shrink-0" />
                    <span className="text-xs font-bold truncate">
                      {name}{" "}
                      <span className="text-[9px] font-normal opacity-60">
                        ({sessionList.length})
                      </span>
                    </span>
                  </div>
                  <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                      disabled={isGeneratingPdf}
                      onClick={(e) => downloadFolderPDF(name, e)}
                      className={`p-1 rounded text-[#044f54] ${isGeneratingPdf ? "opacity-50 cursor-not-allowed" : "hover:bg-[#044f54]/10"}`}
                      title={
                        isGeneratingPdf
                          ? "Generating..."
                          : "Download Full Analytics PDF"
                      }
                    >
                      <Download className="w-3 h-3" />
                    </button>
                    <button
                      onClick={(e) => deleteFolder(name, e)}
                      className="p-1 hover:bg-red-500/10 rounded text-red-500"
                      title="Delete Folder"
                    >
                      <Trash2 className="w-3 h-3" />
                    </button>
                  </div>
                </div>

                {expandedFolders[name] && (
                  <div className="pl-6 pr-2 py-1 space-y-1 border-l-2 border-[#044f54]/10 ml-4 mb-2">
                    {sessionList.map((s, i) => (
                      <div
                        key={i}
                        className={`w-full group text-left px-3 py-2 rounded flex items-center justify-between transition-colors cursor-pointer ${selectedSession?._key === s._key ? "bg-[#044f54] text-white" : "hover:bg-[#044f54]/10 text-[#044f54]"}`}
                        onClick={() => setSelectedSession(s)}
                      >
                        <div className="flex flex-col">
                          <span className="text-[10px] uppercase font-bold tracking-widest">
                            {new Date(s.timestamp).toLocaleDateString()}{" "}
                            {new Date(s.timestamp).toLocaleTimeString([], {
                              hour: "2-digit",
                              minute: "2-digit",
                            })}
                          </span>
                          <span
                            className={`text-[9px] font-mono ${selectedSession?._key === s._key ? "text-white/60" : "text-[#044f54]/50"}`}
                          >
                            ID: {s.id.substring(0, 8)}
                          </span>
                        </div>
                        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                          <button
                            disabled={isGeneratingPdf}
                            onClick={(e) => {
                              e.stopPropagation();
                              downloadSessionPDF(s);
                            }}
                            className={`p-1 rounded ${isGeneratingPdf ? "opacity-50 cursor-not-allowed" : selectedSession?._key === s._key ? "hover:bg-white/20" : "hover:bg-[#044f54]/10"}`}
                            title={
                              isGeneratingPdf
                                ? "Generating..."
                                : "Download Session PDF"
                            }
                          >
                            <Download className="w-3 h-3" />
                          </button>
                          <button
                            onClick={(e) => deleteSession(s._key, e)}
                            className={`p-1 rounded ${selectedSession?._key === s._key ? "hover:bg-red-500/20 text-red-200" : "hover:bg-red-500/10 text-red-500"}`}
                            title="Delete Session"
                          >
                            <Trash2 className="w-3 h-3" />
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Detail Panel */}
        <div className="flex-1 bg-slate-50 relative z-10 flex flex-col">
          {selectedSession ? (
            <div className="flex-1 overflow-y-auto p-8 flex flex-col max-w-4xl mx-auto w-full">
              <div className="border-b border-[#044f54]/20 pb-4 mb-4 flex flex-col sm:flex-row sm:justify-between sm:items-end gap-4">
                <div>
                  <h2 className="text-[#044f54] text-2xl font-serif italic mb-1">
                    {selectedSession.candidateName}
                  </h2>
                  <p className="text-[#044f54]/50 font-mono text-[10px] uppercase">
                    Session: {selectedSession.id}
                  </p>
                  <p className="text-[#044f54]/50 font-mono text-[10px] uppercase mt-1">
                    Start:{" "}
                    {selectedSession.startTime
                      ? new Date(selectedSession.startTime).toLocaleString()
                      : new Date(selectedSession.timestamp).toLocaleString()}
                  </p>
                  <p className="text-[#044f54]/50 font-mono text-[10px] uppercase mt-1">
                    End:{" "}
                    {selectedSession.endTime
                      ? new Date(selectedSession.endTime).toLocaleString()
                      : "N/A"}
                  </p>
                </div>
                <div className="flex items-center gap-2 flex-wrap">
                  <button
                    onClick={() => downloadSessionPDF(selectedSession)}
                    disabled={isGeneratingPdf}
                    className={`flex items-center gap-2 px-4 py-2 bg-white text-[#044f54] border border-[#044f54]/20 rounded text-[10px] uppercase tracking-widest font-bold ${isGeneratingPdf ? "opacity-50 cursor-not-allowed" : "hover:bg-[#044f54]/5"}`}
                  >
                    <FileText className="w-3 h-3" />{" "}
                    {isGeneratingPdf ? "Generating..." : "PDF Analytics"}
                  </button>
                  {selectedSession.audioBlob && (
                    <>
                      <button
                        onClick={() => playAudio(selectedSession.audioBlob)}
                        className="flex items-center gap-2 px-4 py-2 bg-[#044f54] text-white rounded text-[10px] uppercase tracking-widest font-bold hover:bg-[#044f54]/90"
                      >
                        <Play className="w-3 h-3" /> Play Audio
                      </button>
                      <button
                        onClick={() =>
                          downloadAudio(
                            selectedSession.audioBlob,
                            selectedSession.candidateName,
                          )
                        }
                        className="flex items-center gap-2 px-4 py-2 bg-white text-[#044f54] border border-[#044f54]/20 rounded text-[10px] uppercase tracking-widest font-bold hover:bg-[#044f54]/5"
                      >
                        <Download className="w-3 h-3" /> Download Audio
                      </button>
                    </>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4 mb-8">
                <div className="p-4 border border-[#044f54]/20 rounded bg-white">
                  <div className="flex items-center gap-2 mb-2 text-[#044f54]/50">
                    <Clock className="w-4 h-4" />
                    <span className="text-[10px] uppercase tracking-widest font-mono">
                      Duration
                    </span>
                  </div>
                  <div className="text-2xl font-mono text-[#044f54]">
                    {selectedSession.duration}s
                  </div>
                </div>
                <div className="p-4 border border-[#044f54]/20 rounded bg-white">
                  <div className="flex items-center gap-2 mb-2 text-[#044f54]/50">
                    <BarChart3 className="w-4 h-4" />
                    <span className="text-[10px] uppercase tracking-widest font-mono">
                      Chapters Tested
                    </span>
                  </div>
                  <div className="text-2xl font-mono text-[#044f54]">
                    {selectedSession.chaptersTested || 0}
                  </div>
                </div>
              </div>

              <div className="flex-1 flex flex-col border border-[#044f54]/20 bg-white rounded overflow-hidden">
                <div className="p-3 border-b border-[#044f54]/20 bg-[#044f54]/5 flex justify-between">
                  <span className="text-[10px] font-mono uppercase tracking-widest text-[#044f54]/70">
                    Interaction Transcript
                  </span>
                  <span className="text-[10px] font-mono uppercase tracking-widest text-[#044f54]/40">
                    (Agent Actions & Text)
                  </span>
                </div>
                <div className="p-4 flex-1 overflow-y-auto space-y-4 max-h-[400px]">
                  {selectedSession.logs?.length > 0 ? (
                    selectedSession.logs.map((log: any, i: number) => (
                      <div
                        key={i}
                        className={`flex flex-col max-w-[85%] ${log.role === "agent" ? "self-start" : log.role === "user" ? "self-end items-end ml-auto" : "self-center items-center mx-auto"}`}
                      >
                        <span className="text-[9px] uppercase tracking-widest font-mono text-[#044f54]/40 mb-1">
                          {log.role}
                        </span>
                        <div
                          className={`p-3 rounded text-sm ${log.role === "agent" ? "bg-[#044f54]/5 text-[#044f54] border border-[#044f54]/10" : log.role === "user" ? "bg-[#044f54] text-white" : "bg-transparent text-[#044f54]/60 italic text-center w-full text-xs"}`}
                        >
                          {log.text}
                        </div>
                      </div>
                    ))
                  ) : (
                    <div className="text-center text-[#044f54]/40 font-mono text-xs uppercase p-8">
                      No transcript data available.
                    </div>
                  )}
                </div>
              </div>
            </div>
          ) : (
            <div className="flex-1 flex items-center justify-center p-8">
              <div className="flex flex-col items-center text-[#044f54]/30">
                <Database className="w-16 h-16 mb-4" />
                <p className="font-mono text-xs uppercase tracking-widest">
                  Select a session record to view analytics
                </p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
