"use client";

import { useState, useEffect, useMemo } from "react";
import Link from "next/link";
import { 
  User, 
  Play, 
  Clock, 
  BarChart3, 
  Database, 
  Folder, 
  ChevronDown, 
  ChevronRight, 
  FileText, 
  Download, 
  Trash2,
  Eye,
  MessageSquare,
  Search,
  X,
  Archive,
  History,
  ArchiveX
} from "lucide-react";

export default function SessionsPage() {
  const [sessions, setSessions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedFolders, setExpandedFolders] = useState<Record<string, boolean>>({});
  const [searchTerm, setSearchTerm] = useState("");
  const [showArchived, setShowArchived] = useState(false);

  // Archive Modal State
  const [archiveTarget, setArchiveTarget] = useState<{id: string, type: 'session' | 'folder', name: string} | null>(null);
  const [archiveReason, setArchiveReason] = useState("");
  const [isArchiving, setIsArchiving] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);

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

  const fetchSessions = () => {
    setLoading(true);
    fetch("/api/sessions")
      .then(res => res.json())
      .then(json => {
        if (json.success) setSessions(json.data);
        setLoading(false);
      });
  };

  const groupedSessions = useMemo(() => {
    const groups: Record<string, { sessions: any[], profileId: string }> = {};
    const filtered = sessions.filter(s => {
       const matchesSearch = (s.profile?.name || "").toLowerCase().includes(searchTerm.toLowerCase());
       if (showArchived) return matchesSearch;
       return matchesSearch && !s.isArchived;
    });

    filtered.forEach((s) => {
      const name = s.profile?.name || "Unknown Candidate";
      if (!groups[name]) groups[name] = { sessions: [], profileId: s.profileId };
      groups[name].sessions.push(s);
    });
    return groups;
  }, [sessions, searchTerm, showArchived]);

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

  const handleArchive = async (e?: React.FormEvent, isPermanent: boolean = false) => {
    if (e) e.preventDefault();
    if (!archiveTarget) return;
    
    // Validate ID
    if (!archiveTarget.id || archiveTarget.id === 'undefined') {
      alert("CRITICAL ERROR: Operation aborted. The target record ID is missing or invalid. Please refresh the page and try again.");
      return;
    }

    if (!isPermanent && !archiveReason.trim()) return;
    
    setIsArchiving(true);
    const endpoint = archiveTarget.type === 'session' 
      ? `/api/sessions/${archiveTarget.id}/archive`
      : `/api/practitioners/${archiveTarget.id}/archive`;

    try {
      console.log(`Executing ${isPermanent ? 'DELETE' : 'ARCHIVE'} on ${endpoint}`);
      const res = await fetch(endpoint, {
        method: isPermanent ? "DELETE" : "POST",
        headers: { "Content-Type": "application/json" },
        body: isPermanent ? undefined : JSON.stringify({ reason: archiveReason })
      });
      
      const json = await res.json();
      if (json.success) {
        setArchiveTarget(null);
        setArchiveReason("");
        setConfirmDelete(false);
        fetchSessions();
      } else {
        alert(`OPERATION FAILED: ${json.error || 'Unknown server error'}`);
      }
    } catch (err) {
      console.error("Archive/Delete error:", err);
      alert("NETWORK ERROR: Could not communicate with the database. Please check your connection.");
    } finally {
      setIsArchiving(false);
    }
  };

  if (loading && sessions.length === 0) return (
    <div className="h-full flex items-center justify-center font-mono text-[#044f54] uppercase tracking-widest text-xs">
      Accessing Records Database...
    </div>
  );

  return (
    <div className="space-y-6 max-w-6xl mx-auto animate-in fade-in duration-500 text-[#044f54]">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-end border-b border-[#044f54]/20 pb-6 gap-4">
        <div>
          <h2 className="text-2xl font-serif italic">Mission Log Database</h2>
          <p className="text-[#044f54]/40 text-[10px] font-mono uppercase tracking-[0.2em] mt-1">Authorized intelligence performance records</p>
        </div>
        <div className="flex flex-wrap items-center gap-4 w-full md:w-auto">
          <button 
            onClick={() => setShowArchived(!showArchived)}
            className={`flex items-center gap-2 px-4 py-2 rounded border text-[10px] font-bold uppercase tracking-widest transition-all ${showArchived ? 'bg-[#044f54] text-white border-[#044f54]' : 'bg-white text-[#044f54] border-[#044f54]/20 hover:border-[#044f54]'}`}
          >
            {showArchived ? <History size={14}/> : <Archive size={14}/>}
            {showArchived ? 'Show Active Only' : 'View Archived Files'}
          </button>
          <div className="relative flex-1 md:flex-initial min-w-[240px]">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#044f54]/40" size={16} />
            <input 
              type="text" 
              placeholder="SEARCH BY OPERATIVE..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white border border-[#044f54]/20 rounded font-mono text-[10px] uppercase tracking-wider focus:border-[#044f54] outline-none"
            />
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 pb-20">
        {Object.keys(groupedSessions).length === 0 ? (
          <div className="py-20 text-center border-2 border-dashed border-[#044f54]/10 rounded bg-white/50 backdrop-blur-sm">
             <Database className="w-12 h-12 text-[#044f54]/10 mx-auto mb-4" />
             <p className="text-[#044f54]/30 font-mono text-[10px] uppercase tracking-widest">No intelligence data recovered in this sector</p>
          </div>
        ) : Object.keys(groupedSessions).map((name) => {
          const group = groupedSessions[name];
          const practitionerSessions = group.sessions;
          const isExpanded = expandedFolders[name];
          
          return (
            <div key={name} className={`space-y-2`}>
              <div 
                className={`p-4 rounded border transition-all cursor-pointer flex items-center justify-between group ${isExpanded ? 'bg-[#044f54] border-[#044f54] text-white shadow-lg' : 'bg-white border-[#044f54]/20 text-[#044f54] hover:border-[#044f54]/50 shadow-sm'}`}
              >
                <div className="flex items-center gap-4 flex-1" onClick={() => toggleFolder(name)}>
                  <div className={`p-2 rounded ${isExpanded ? 'bg-white/10' : 'bg-[#044f54]/5'}`}>
                    <Folder className="w-5 h-5" />
                  </div>
                  <div>
                    <div className="font-bold tracking-widest uppercase text-xs">{name}</div>
                    <div className={`text-[9px] font-mono uppercase ${isExpanded ? 'text-white/60' : 'text-[#044f54]/40'}`}>
                      {practitionerSessions.length} MISSION RECORDS
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center gap-4">
                  {!showArchived && practitionerSessions.length > 0 && (
                    <button 
                      onClick={(e) => {
                        e.stopPropagation();
                        setArchiveTarget({ id: group.profileId, type: 'folder', name: name });
                      }}
                      className={`flex items-center gap-2 px-3 py-1.5 rounded border text-[8px] font-bold uppercase tracking-widest transition-all ${isExpanded ? 'bg-white/10 border-white/20 hover:bg-white/20 text-white' : 'bg-red-50 border-red-100 text-red-600 hover:bg-red-600 hover:text-white'}`}
                      title="Delete or Archive Folder"
                    >
                      <Trash2 size={12} /> Delete Folder
                    </button>
                  )}
                  <div className="flex items-center gap-4" onClick={() => toggleFolder(name)}>
                    {isExpanded ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
                  </div>
                </div>
              </div>

              {isExpanded && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 pl-4 md:pl-8 pr-2 py-4 animate-in slide-in-from-top-2 duration-300">
                  {practitionerSessions.map((s, i) => (
                    <div 
                      key={s.id} 
                      className={`bg-white border p-5 rounded hover:shadow-md transition-all flex flex-col justify-between group h-40 relative overflow-hidden ${s.isArchived ? 'border-red-200 opacity-80' : 'border-[#044f54]/10 hover:border-[#044f54]/50 shadow-sm'}`}
                    >
                      {s.isArchived && (
                        <div className="absolute top-0 right-0 bg-red-600 text-white text-[8px] font-mono px-2 py-0.5 uppercase tracking-tighter z-10">
                          ARCHIVED
                        </div>
                      )}
                      
                      <div className="flex justify-between items-start mb-4">
                        <div className="flex flex-col">
                          <span className="text-[9px] font-mono text-[#044f54]/40 uppercase tracking-[0.2em]">MISSION {s.sessionNumber || i+1}</span>
                          <span className="text-xs font-bold text-[#044f54] mt-1 uppercase">{new Date(s.startTime).toLocaleDateString()}</span>
                        </div>
                        <div className="text-[9px] font-mono text-[#044f54]/60 bg-[#044f54]/5 px-2 py-1 rounded border border-[#044f54]/10 font-bold uppercase">
                          {Math.floor(s.duration / 60)}M {s.duration % 60}s
                        </div>
                      </div>

                      <div className="flex justify-between items-center pt-4 border-t border-[#044f54]/5 mt-auto">
                        <div className="flex items-center gap-4">
                           <div className="flex flex-col">
                              <span className="text-[8px] font-mono text-[#044f54]/40 uppercase tracking-tighter">Score</span>
                              <span className="text-sm font-black text-[#044f54]">{s.overallScore || '---'}</span>
                           </div>
                           <div className="flex flex-col border-l border-[#044f54]/10 pl-4">
                              <span className="text-[8px] font-mono text-[#044f54]/40 uppercase tracking-tighter">Tone</span>
                              <span className="text-xs font-bold text-[#044f54] uppercase">{s.emotionalTone || 'NRM'}</span>
                           </div>
                        </div>
                        <div className="flex items-center gap-2">
                           {!s.isArchived && (
                             <button 
                                onClick={(e) => { e.preventDefault(); setArchiveTarget({ id: s.id, type: 'session', name: `Mission ${s.sessionNumber || i+1}` }); }}
                                className="w-8 h-8 rounded bg-red-50 text-red-600 hover:bg-red-600 hover:text-white transition-all flex items-center justify-center border border-red-100"
                                title="Archive Record"
                             >
                               <Trash2 size={14} />
                             </button>
                           )}
                           <Link 
                             href={`/admin/sessions/${s.id}`}
                             className="w-8 h-8 rounded bg-[#044f54]/5 flex items-center justify-center text-[#044f54] hover:bg-[#044f54] hover:text-white transition-all border border-[#044f54]/10"
                           >
                             <Eye size={14} />
                           </Link>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Archive Modal */}
      {archiveTarget && (
        <div className="fixed inset-0 bg-[#044f54]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
          <div className="bg-slate-50 border border-[#044f54] shadow-[0_0_50px_rgba(4,79,84,0.2)] w-full max-w-md rounded overflow-hidden animate-in zoom-in-95 duration-200">
             <div className="absolute inset-0 pointer-events-none bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(4,79,84,0.05) 2px,rgba(4,79,84,0.05) 4px)]"></div>
             
             <div className="border-b border-[#044f54]/30 bg-[#044f54]/10 p-4 flex justify-between items-center relative z-10">
                <div className="flex items-center gap-3">
                  <div className="w-6 h-6 bg-[#044f54] flex items-center justify-center text-white font-black uppercase text-[10px] tracking-widest rounded-sm">ADM</div>
                  <span className="text-[#044f54] font-bold text-xs tracking-widest uppercase">
                    {archiveTarget.type === 'folder' ? 'Archive Entire Folder' : 'Archive Mission Log'}
                  </span>
                </div>
                <button onClick={() => { setArchiveTarget(null); setConfirmDelete(false); }} className="text-[#044f54]/60 hover:text-[#044f54]"><X size={18}/></button>
             </div>

             <div className="p-6 space-y-6 relative z-10 text-[#044f54]">
                {!confirmDelete ? (
                  <>
                    <div className="space-y-4">
                       <p className="text-xs text-[#044f54]/60 leading-relaxed uppercase font-mono tracking-wider">
                          Target: <span className="font-bold">{archiveTarget.name}</span>
                       </p>
                       <div className="flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-white">
                          <label className="text-[9px] font-mono text-[#044f54]/50 uppercase tracking-wider">Reason for Archive</label>
                          <textarea 
                            required
                            value={archiveReason}
                            onChange={e => setArchiveReason(e.target.value)}
                            className="bg-transparent outline-none text-sm font-medium text-[#044f54] h-24 resize-none"
                            placeholder="ENTER OPERATIONAL JUSTIFICATION..."
                          />
                       </div>
                    </div>
                    
                    <div className="flex flex-col gap-3 pt-4">
                       <button 
                        onClick={() => handleArchive(undefined, false)}
                        disabled={isArchiving || !archiveReason.trim()}
                        className="bg-[#044f54] text-white px-8 py-3 rounded font-bold uppercase tracking-widest text-[10px] w-full shadow-lg shadow-[#044f54]/20 hover:bg-[#044f54]/90 disabled:opacity-50 cursor-pointer pointer-events-auto"
                       >
                         {isArchiving ? "PROCESSING..." : "COMMIT TO ARCHIVE"}
                       </button>
                       
                       <div className="relative py-2">
                         <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-[#044f54]/10"></div></div>
                         <div className="relative flex justify-center text-[8px] uppercase font-mono text-[#044f54]/30 bg-slate-50 px-2">OR</div>
                       </div>

                       <button 
                        type="button"
                        onClick={() => setConfirmDelete(true)}
                        disabled={isArchiving}
                        className="bg-white text-red-600 border border-red-200 px-8 py-3 rounded font-bold uppercase tracking-widest text-[10px] w-full hover:bg-red-50 disabled:opacity-50 cursor-pointer pointer-events-auto"
                       >
                         INITIATE PERMANENT DELETE
                       </button>
                    </div>
                  </>
                ) : (
                  <div className="space-y-6 py-4">
                    <div className="flex flex-col items-center text-center space-y-3">
                      <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center text-red-600">
                        <ArchiveX size={24} />
                      </div>
                      <h3 className="text-sm font-black uppercase tracking-tighter">Confirm Irreversible Deletion</h3>
                      <p className="text-[10px] text-red-600/70 font-mono uppercase leading-relaxed">
                        You are about to permanently purge all data for <span className="font-bold underline">{archiveTarget.name}</span>. This action cannot be undone.
                      </p>
                    </div>
                    
                    <div className="flex flex-col gap-2">
                      <button 
                        onClick={() => handleArchive(undefined, true)}
                        disabled={isArchiving}
                        className="bg-red-600 text-white px-8 py-3 rounded font-bold uppercase tracking-widest text-[10px] w-full shadow-lg shadow-red-600/20 hover:bg-red-700"
                      >
                        {isArchiving ? "PURGING DATA..." : "YES, DELETE PERMANENTLY"}
                      </button>
                      <button 
                        onClick={() => setConfirmDelete(false)}
                        disabled={isArchiving}
                        className="bg-white text-[#044f54] border border-[#044f54]/20 px-8 py-2 rounded font-bold uppercase tracking-widest text-[8px] w-full hover:bg-slate-100"
                      >
                        CANCEL
                      </button>
                    </div>
                  </div>
                )}
             </div>
          </div>
        </div>
      )}
    </div>
  );
}
