"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import {
  Download,
  MessageSquare,
  Target,
  Headphones,
  ChevronLeft,
  User,
  Trash2,
  X,
  Archive,
  Sparkles,
  AlertTriangle,
  TrendingUp,
  TrendingDown,
  Lightbulb,
  Tag,
  HeartPulse,
  RefreshCw,
} from "lucide-react";

function formatTime(value?: string | Date | null) {
  if (!value) return "—";
  try {
    const d = new Date(value);
    return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
  } catch {
    return "—";
  }
}

function formatDateTime(value?: string | Date | null) {
  if (!value) return "—";
  try {
    return new Date(value).toLocaleString();
  } catch {
    return "—";
  }
}

function formatDuration(seconds?: number | null) {
  if (!seconds || seconds <= 0) return "—";
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  if (m === 0) return `${s}s`;
  return `${m}m ${s}s`;
}

export default function SessionDetailPage() {
  const params = useParams();
  const router = useRouter();
  const id = params.id as string;
  const [session, setSession] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  const [isArchiveModalOpen, setIsArchiveModalOpen] = useState(false);
  const [archiveReason, setArchiveReason] = useState("");
  const [isArchiving, setIsArchiving] = useState(false);
  const [regenLoading, setRegenLoading] = useState(false);
  const [regenError, setRegenError] = useState<string | null>(null);
  const [transcribeLoading, setTranscribeLoading] = useState(false);
  const [transcribeError, setTranscribeError] = useState<string | null>(null);

  const reload = () =>
    fetch(`/api/sessions/${id}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.success) setSession(json.data);
      });

  useEffect(() => {
    fetch(`/api/sessions/${id}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.success) setSession(json.data);
        setLoading(false);
      });
  }, [id]);

  const handleRegenerateAnalytics = async () => {
    setRegenLoading(true);
    setRegenError(null);
    try {
      const res = await fetch(`/api/sessions/${id}/analytics`, {
        method: "POST",
      });
      const json = await res.json();
      if (!json.success) {
        setRegenError(json.error || "Failed to generate analytics.");
      } else {
        await reload();
      }
    } catch {
      setRegenError("Network error while running analytics.");
    } finally {
      setRegenLoading(false);
    }
  };

  const handleTranscribe = async () => {
    setTranscribeLoading(true);
    setTranscribeError(null);
    try {
      const res = await fetch(`/api/sessions/${id}/transcribe`, {
        method: "POST",
      });
      const json = await res.json();
      if (!json.success) {
        setTranscribeError(
          json.error || "Failed to transcribe the recording.",
        );
      } else {
        await reload();
      }
    } catch {
      setTranscribeError("Network error while transcribing.");
    } finally {
      setTranscribeLoading(false);
    }
  };

  const handleArchive = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!archiveReason.trim()) return;

    setIsArchiving(true);
    const res = await fetch(`/api/sessions/${id}/archive`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ reason: archiveReason }),
    });

    const json = await res.json();
    if (json.success) {
      router.push("/admin/sessions");
      router.refresh();
    } else {
      alert("Failed to archive session: " + json.error);
    }
    setIsArchiving(false);
  };

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

  if (!session)
    return (
      <div className="h-full flex items-center justify-center text-sm text-red-600">
        Record not found.
      </div>
    );

  const startTime = session.startTime ? new Date(session.startTime) : null;
  const endTime = session.endTime ? new Date(session.endTime) : null;
  const durationSec =
    typeof session.duration === "number" && session.duration > 0
      ? session.duration
      : startTime && endTime
      ? Math.max(0, Math.round((endTime.getTime() - startTime.getTime()) / 1000))
      : 0;

  const transcripts: any[] = session.transcriptEntries || [];
  const hasTranscripts = transcripts.length > 0;
  const analytics: any = session.tags && typeof session.tags === "object" && (session.tags as any).summary ? session.tags : null;

  return (
    <div className="space-y-8 max-w-6xl mx-auto animate-in fade-in duration-500 text-[#044f54]">
      <div className="flex items-center justify-between border-b border-[#044f54]/10 pb-5">
        <div className="flex items-center gap-4">
          <button
            onClick={() => router.back()}
            className="p-2 rounded-lg bg-[#044f54]/5 text-[#044f54] hover:bg-[#044f54]/10 transition-colors"
            aria-label="Back"
          >
            <ChevronLeft size={18} />
          </button>
          <div>
            <h1 className="text-2xl md:text-3xl font-semibold tracking-tight text-[#044f54]">
              Mission log #{session.sessionNumber || "—"}
            </h1>
            <p className="text-sm text-[#044f54]/55 mt-1">
              {session.profile?.name ?? "Unknown operative"}
              {" · "}
              {formatDateTime(startTime)}
            </p>
          </div>
        </div>

        {!session.isArchived && (
          <button
            onClick={() => setIsArchiveModalOpen(true)}
            className="flex items-center gap-2 px-3.5 py-2 bg-red-50 text-red-700 hover:bg-red-100 rounded-lg border border-red-100 text-sm font-medium transition-all"
          >
            <Trash2 size={14} /> Archive
          </button>
        )}
      </div>

      {session.isArchived && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-xl flex flex-col gap-1.5">
          <div className="flex items-center gap-2 text-red-800 font-medium text-sm">
            <Archive size={14} /> This record has been archived
          </div>
          <p className="text-sm text-red-700">
            Reason: {session.archiveReason}
          </p>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
        <div className="md:col-span-2 bg-white p-6 rounded-xl border border-[#044f54]/10 shadow-sm flex flex-col md:flex-row justify-between gap-6">
          <div className="flex items-center gap-5">
            <div className="w-14 h-14 rounded-full bg-[#044f54]/5 border border-[#044f54]/10 flex items-center justify-center text-[#044f54]">
              <User size={26} />
            </div>
            <div>
              <h3 className="text-lg font-semibold tracking-tight">
                {session.profile?.name}
              </h3>
              <p className="text-sm text-[#044f54]/55 mt-0.5">
                {session.profile?.role ?? "Practitioner"}
              </p>
              <div className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm mt-3">
                <div>
                  <span className="text-[#044f54]/55">Started </span>
                  <span className="font-medium">{formatTime(startTime)}</span>
                </div>
                <div>
                  <span className="text-[#044f54]/55">Ended </span>
                  <span className="font-medium">
                    {endTime ? formatTime(endTime) : "—"}
                  </span>
                </div>
                <div>
                  <span className="text-[#044f54]/55">Date </span>
                  <span className="font-medium">
                    {startTime ? startTime.toLocaleDateString() : "—"}
                  </span>
                </div>
                <div>
                  <span className="text-[#044f54]/55">Duration </span>
                  <span className="font-medium">{formatDuration(durationSec)}</span>
                </div>
              </div>
            </div>
          </div>

          <div className="flex flex-col items-end justify-between">
            <div className="flex flex-col items-end">
              <span className="text-xs text-[#044f54]/55">Mastery score</span>
              <div className="text-3xl font-semibold tracking-tight mt-0.5">
                {session.overallScore ?? "—"}
              </div>
            </div>
            <span className="text-xs text-[#044f54]/55">
              {transcripts.length} transcript {transcripts.length === 1 ? "entry" : "entries"}
            </span>
          </div>
        </div>

        <div className="bg-[#044f54] text-white p-6 rounded-xl shadow-sm flex flex-col justify-between">
          <div>
            <span className="text-xs text-white/60">Emotional profile</span>
            <div className="text-xl font-semibold mt-1">
              {session.emotionalTone || "Normal"}
            </div>
          </div>
          <div className="mt-6 flex justify-between items-end border-t border-white/10 pt-4">
            <div className="flex flex-col">
              <span className="text-xs text-white/60">Status</span>
              <span className="text-sm font-medium">
                {endTime ? "Complete" : "Active"}
              </span>
            </div>
            <a
              href={`/api/reports/session/${id}`}
              target="_blank"
              className="bg-white text-[#044f54] p-2 rounded-lg hover:bg-white/90 transition-all"
              aria-label="Download report"
            >
              <Download size={16} />
            </a>
          </div>
        </div>
      </div>

      <section className="bg-white rounded-xl border border-[#044f54]/10 shadow-sm overflow-hidden">
        <header className="px-6 py-4 border-b border-[#044f54]/10 flex items-center justify-between">
          <div className="flex items-center gap-2 text-sm font-semibold tracking-tight">
            <Sparkles size={16} className="text-[#044f54]/60" />
            AI analytics
            {analytics?.model && (
              <span className="ml-2 text-xs font-normal text-[#044f54]/45">
                · {analytics.model}
              </span>
            )}
          </div>
          <button
            onClick={handleRegenerateAnalytics}
            disabled={regenLoading || !hasTranscripts}
            className="flex items-center gap-2 px-3 py-1.5 bg-[#044f54] text-white rounded-lg text-xs font-medium hover:bg-[#044f54]/90 disabled:opacity-50"
          >
            <RefreshCw size={12} className={regenLoading ? "animate-spin" : ""} />
            {regenLoading ? "Analyzing…" : analytics ? "Regenerate" : "Run analytics"}
          </button>
        </header>

        <div className="p-6 space-y-6">
          {regenError && (
            <div className="p-3 rounded-lg border border-red-100 bg-red-50 text-sm text-red-700">
              {regenError}
            </div>
          )}
          {!analytics ? (
            <div className="text-sm text-[#044f54]/55">
              {hasTranscripts
                ? "No analysis yet. Click \"Run analytics\" to summarize the conversation, detect emotions, and surface strengths, weaknesses and suggestions."
                : "Capture a transcript first, then run analytics."}
            </div>
          ) : (
            <>
              <p className="text-sm text-[#044f54]/85 leading-relaxed">
                {analytics.summary || "—"}
              </p>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="rounded-lg border border-[#044f54]/10 bg-[#044f54]/[0.04] p-4">
                  <div className="text-xs text-[#044f54]/55">Mastery score</div>
                  <div className="text-2xl font-semibold tracking-tight mt-0.5">
                    {analytics.overallScore ?? "—"}
                  </div>
                </div>
                <div className="rounded-lg border border-[#044f54]/10 bg-[#044f54]/[0.04] p-4">
                  <div className="text-xs text-[#044f54]/55 flex items-center gap-1.5">
                    <HeartPulse size={12} /> Emotion
                  </div>
                  <div className="text-base font-medium mt-0.5">
                    {analytics.emotionalTone || "—"}
                  </div>
                </div>
                <div className="rounded-lg border border-[#044f54]/10 bg-[#044f54]/[0.04] p-4">
                  <div className="text-xs text-[#044f54]/55">Risk flags</div>
                  <div className="text-base font-medium mt-0.5">
                    {analytics.riskFlags && analytics.riskFlags.length > 0
                      ? `${analytics.riskFlags.length} flag${analytics.riskFlags.length === 1 ? "" : "s"}`
                      : "None"}
                  </div>
                </div>
              </div>

              {Array.isArray(analytics.emotionalArc) && analytics.emotionalArc.length > 0 && (
                <div>
                  <div className="text-sm font-semibold tracking-tight mb-2">
                    Emotional arc
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                    {analytics.emotionalArc.map((seg: any, i: number) => (
                      <div
                        key={i}
                        className="rounded-lg border border-[#044f54]/10 p-3"
                      >
                        <div className="text-xs uppercase tracking-wide text-[#044f54]/55">
                          {seg.phase}
                        </div>
                        <div className="text-sm font-medium mt-0.5">{seg.tone}</div>
                        <p className="text-sm text-[#044f54]/70 mt-1 leading-relaxed">
                          {seg.note}
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="rounded-lg border border-emerald-100 bg-emerald-50/50 p-4">
                  <div className="flex items-center gap-1.5 text-sm font-semibold text-emerald-800 mb-2">
                    <TrendingUp size={14} /> Strengths
                  </div>
                  <ul className="text-sm text-emerald-900 space-y-1.5 list-disc pl-4">
                    {(analytics.strengths || []).map((s: string, i: number) => (
                      <li key={i}>{s}</li>
                    ))}
                    {(!analytics.strengths || analytics.strengths.length === 0) && (
                      <li className="list-none text-emerald-900/60">—</li>
                    )}
                  </ul>
                </div>
                <div className="rounded-lg border border-amber-100 bg-amber-50/50 p-4">
                  <div className="flex items-center gap-1.5 text-sm font-semibold text-amber-800 mb-2">
                    <TrendingDown size={14} /> Weaknesses
                  </div>
                  <ul className="text-sm text-amber-900 space-y-1.5 list-disc pl-4">
                    {(analytics.weaknesses || []).map((s: string, i: number) => (
                      <li key={i}>{s}</li>
                    ))}
                    {(!analytics.weaknesses || analytics.weaknesses.length === 0) && (
                      <li className="list-none text-amber-900/60">—</li>
                    )}
                  </ul>
                </div>
                <div className="rounded-lg border border-sky-100 bg-sky-50/50 p-4">
                  <div className="flex items-center gap-1.5 text-sm font-semibold text-sky-800 mb-2">
                    <Lightbulb size={14} /> Suggestions
                  </div>
                  <ul className="text-sm text-sky-900 space-y-1.5 list-disc pl-4">
                    {(analytics.suggestions || []).map((s: string, i: number) => (
                      <li key={i}>{s}</li>
                    ))}
                    {(!analytics.suggestions || analytics.suggestions.length === 0) && (
                      <li className="list-none text-sky-900/60">—</li>
                    )}
                  </ul>
                </div>
              </div>

              {(analytics.keyTopics?.length || analytics.riskFlags?.length || analytics.mentorBriefing) && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {analytics.keyTopics && analytics.keyTopics.length > 0 && (
                    <div className="rounded-lg border border-[#044f54]/10 p-4">
                      <div className="flex items-center gap-1.5 text-sm font-semibold mb-2">
                        <Tag size={14} className="text-[#044f54]/60" /> Key topics
                      </div>
                      <div className="flex flex-wrap gap-1.5">
                        {analytics.keyTopics.map((t: string, i: number) => (
                          <span
                            key={i}
                            className="px-2 py-0.5 rounded-full bg-[#044f54]/[0.06] text-[#044f54] text-xs"
                          >
                            {t}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}
                  {analytics.riskFlags && analytics.riskFlags.length > 0 && (
                    <div className="rounded-lg border border-red-100 bg-red-50/40 p-4">
                      <div className="flex items-center gap-1.5 text-sm font-semibold text-red-800 mb-2">
                        <AlertTriangle size={14} /> Risk flags
                      </div>
                      <ul className="text-sm text-red-800 space-y-1.5 list-disc pl-4">
                        {analytics.riskFlags.map((s: string, i: number) => (
                          <li key={i}>{s}</li>
                        ))}
                      </ul>
                    </div>
                  )}
                  {analytics.mentorBriefing && (
                    <div className="rounded-lg border border-[#044f54]/10 p-4 md:col-span-2">
                      <div className="text-sm font-semibold mb-2">
                        Mentor briefing
                      </div>
                      <p className="text-sm text-[#044f54]/85 leading-relaxed">
                        {analytics.mentorBriefing}
                      </p>
                    </div>
                  )}
                </div>
              )}
            </>
          )}
        </div>
      </section>

      <div className="bg-white p-6 rounded-xl border border-[#044f54]/10 shadow-sm">
        <div className="flex items-center justify-between mb-5">
          <div className="flex items-center gap-2 text-sm font-semibold tracking-tight">
            <Headphones size={16} className="text-[#044f54]/60" />
            Voice recording
          </div>
          <a
            href={`/api/sessions/${id}/audio`}
            download={`session_${session.sessionNumber || id}_audio.webm`}
            className="flex items-center gap-2 px-3 py-1.5 bg-[#044f54]/5 hover:bg-[#044f54]/10 rounded-lg border border-[#044f54]/10 text-xs font-medium transition-colors"
          >
            <Download size={12} /> Download
          </a>
        </div>
        <div className="bg-[#044f54]/[0.04] p-5 rounded-lg border border-[#044f54]/10">
          <audio controls className="w-full h-12">
            <source src={`/api/sessions/${id}/audio`} type="audio/webm" />
            Your browser does not support the audio element.
          </audio>
          <div className="flex justify-between mt-3 text-xs text-[#044f54]/55 px-1">
            <span>Started {formatTime(startTime)}</span>
            <span>{endTime ? `Ended ${formatTime(endTime)}` : "In progress"}</span>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 pb-12">
        <div className="lg:col-span-2 space-y-6">
          <div className="bg-white rounded-xl border border-[#044f54]/10 shadow-sm overflow-hidden flex flex-col h-[600px]">
            <div className="px-5 py-4 border-b border-[#044f54]/10 flex items-center justify-between">
              <h2 className="text-sm font-semibold tracking-tight">
                Transcript
              </h2>
              <MessageSquare size={14} className="text-[#044f54]/40" />
            </div>
            <div className="flex-1 overflow-auto p-6 space-y-4 bg-white">
              {!hasTranscripts ? (
                <div className="flex flex-col items-center justify-center h-full text-[#044f54]/55 text-center px-6">
                  <MessageSquare size={36} className="mb-3 opacity-30" />
                  <p className="text-sm mb-4">
                    No transcript captured during the live stream.
                  </p>
                  <button
                    onClick={handleTranscribe}
                    disabled={transcribeLoading}
                    className="flex items-center gap-2 px-4 py-2 bg-[#044f54] text-white rounded-lg text-sm font-medium hover:bg-[#044f54]/90 disabled:opacity-50"
                  >
                    <RefreshCw size={14} className={transcribeLoading ? "animate-spin" : ""} />
                    {transcribeLoading ? "Transcribing audio…" : "Transcribe from audio"}
                  </button>
                  {transcribeError && (
                    <p className="text-xs text-red-700 mt-3">{transcribeError}</p>
                  )}
                </div>
              ) : (
                transcripts.map((entry: any) => {
                  const isUser = entry.role === "user";
                  const isSystem = entry.role === "system";
                  return (
                    <div
                      key={entry.id}
                      className={`flex ${
                        isUser ? "justify-end" : isSystem ? "justify-center" : "justify-start"
                      }`}
                    >
                      <div
                        className={`max-w-[85%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${
                          isUser
                            ? "bg-[#044f54]/5 text-[#044f54] border border-[#044f54]/10"
                            : isSystem
                            ? "bg-slate-100 text-slate-500 text-xs italic text-center"
                            : "bg-[#044f54] text-white"
                        }`}
                      >
                        <div
                          className={`flex items-center gap-2 mb-1 text-[10px] uppercase tracking-wide ${
                            entry.role === "agent" ? "text-white/60" : "text-[#044f54]/45"
                          }`}
                        >
                          <span>
                            {entry.role === "agent"
                              ? "Agent"
                              : entry.role === "user"
                              ? "Operative"
                              : "System"}
                          </span>
                          <span className="opacity-70">·</span>
                          <span className="opacity-80">
                            {formatTime(entry.entryTimestamp)}
                          </span>
                        </div>
                        <div>{entry.text}</div>
                      </div>
                    </div>
                  );
                })
              )}
            </div>
          </div>
        </div>

        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-[#044f54]/10 shadow-sm overflow-hidden">
            <div className="px-5 py-4 border-b border-[#044f54]/10 flex items-center justify-between">
              <h3 className="text-sm font-semibold tracking-tight">Drills</h3>
              <Target size={14} className="text-[#044f54]/40" />
            </div>
            <div className="divide-y divide-[#044f54]/5">
              {!session.drillAttempts || session.drillAttempts.length === 0 ? (
                <p className="p-6 text-center text-sm text-[#044f54]/40">
                  No drill attempts recorded.
                </p>
              ) : (
                session.drillAttempts.map((d: any) => (
                  <div key={d.id} className="p-5 hover:bg-[#044f54]/[0.02] transition-colors">
                    <div className="flex justify-between items-start mb-2">
                      <span className="font-medium text-[#044f54] text-sm">
                        {d.element?.title}
                      </span>
                      <span
                        className={`text-xs font-medium px-2 py-0.5 rounded-full border ${
                          d.passed
                            ? "bg-green-50 text-green-700 border-green-100"
                            : "bg-red-50 text-red-700 border-red-100"
                        }`}
                      >
                        {d.score}%
                      </span>
                    </div>
                    {d.feedback && (
                      <p className="text-sm text-[#044f54]/70 leading-relaxed">
                        {d.feedback}
                      </p>
                    )}
                  </div>
                ))
              )}
            </div>
          </div>

          <div className="bg-white rounded-xl border border-[#044f54]/10 shadow-sm overflow-hidden">
            <div className="px-5 py-4 border-b border-[#044f54]/10">
              <h3 className="text-sm font-semibold tracking-tight">Coaching notes</h3>
            </div>
            <div className="p-5 space-y-4">
              {!session.coachingNotes || session.coachingNotes.length === 0 ? (
                <p className="text-center text-sm text-[#044f54]/40">
                  No coaching notes archived.
                </p>
              ) : (
                session.coachingNotes.map((n: any) => (
                  <div key={n.id} className="text-sm">
                    <div className="text-xs uppercase tracking-wide text-[#044f54]/45 mb-1">
                      {n.category}
                    </div>
                    <div className="text-[#044f54] leading-relaxed pl-3 border-l border-[#044f54]/15">
                      {n.note}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>

      {isArchiveModalOpen && (
        <div className="fixed inset-0 bg-[#044f54]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
          <div className="bg-white border border-[#044f54]/20 shadow-2xl w-full max-w-md rounded-xl overflow-hidden animate-in zoom-in-95 duration-200">
            <div className="border-b border-[#044f54]/10 p-4 flex justify-between items-center">
              <span className="text-[#044f54] font-semibold text-sm">
                Archive mission log
              </span>
              <button
                onClick={() => setIsArchiveModalOpen(false)}
                className="text-[#044f54]/60 hover:text-[#044f54]"
                aria-label="Close"
              >
                <X size={18} />
              </button>
            </div>

            <form onSubmit={handleArchive} className="p-6 space-y-5 text-[#044f54]">
              <p className="text-sm text-[#044f54]/65 leading-relaxed">
                Provide a brief reason. The record will be moved to the archive and hidden from the active list.
              </p>
              <div className="flex flex-col gap-1.5">
                <label className="text-sm font-medium" htmlFor="archive-reason">
                  Reason
                </label>
                <textarea
                  id="archive-reason"
                  required
                  value={archiveReason}
                  onChange={(e) => setArchiveReason(e.target.value)}
                  className="bg-slate-50 border border-[#044f54]/15 rounded-lg p-3 outline-none text-sm text-[#044f54] h-28 resize-none focus:border-[#044f54]/40 focus:ring-2 focus:ring-[#044f54]/10"
                  placeholder="Reason for archiving"
                />
              </div>
              <button
                type="submit"
                disabled={isArchiving || !archiveReason.trim()}
                className="bg-red-600 text-white px-6 py-3 rounded-lg font-semibold text-sm w-full hover:bg-red-700 disabled:opacity-50 transition-all"
              >
                {isArchiving ? "Archiving…" : "Archive"}
              </button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
