import React, { useState, useEffect, useCallback } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "./ui/dialog";
import { ScrollArea } from "./ui/scroll-area";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { useVault } from "../contexts/VaultContext";
import { Loader2, Search, Filter, History, MapPin, Globe, Activity, Terminal, Shield, Plus } from "lucide-react";
import { PlayerContextMenu } from './PlayerContextMenu';
import { Separator } from './ui/separator';
import { cn } from '../lib/utils';

interface PlayerInsightsProps {
  player: {
    name: string;
    nameHash: string;
  } | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

interface LogEvent {
  timestamp: string;
  type: string;
  content: string;
  playerName?: string;
  playerNameHash?: string;
  serverId?: string;
  serverName?: string;
}

interface PlayerNote {
  id: string;
  category: string;
  content: string;
  createdBy: string;
  createdAt: string;
}

export const PlayerInsights: React.FC<PlayerInsightsProps> = ({ player, open, onOpenChange }) => {
  const [logs, setLogs] = useState<LogEvent[]>([]);
  const [notes, setNotes] = useState<PlayerNote[]>([]);
  const [loading, setLoading] = useState(false);
  const [notesLoading, setNotesLoading] = useState(false);
  
  // New Note State
  const [noteContent, setNoteContent] = useState('');
  const [noteCategory, setNoteCategory] = useState('info');
  const [isAddingNote, setIsAddingNote] = useState(false);

  const { decrypt } = useVault();

  const fetchNotes = useCallback(async () => {
    if (!player || !open) return;
    setNotesLoading(true);
    try {
      const res = await fetch(`/api/players/notes?playerNameHash=${player.nameHash}`, {
        headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` },
      });
      const data = await res.json();
      setNotes(data.notes ?? []);
    } catch (err) {
      console.error("Failed to fetch player notes:", err);
    } finally {
      setNotesLoading(false);
    }
  }, [player, open]);

  const handleAddNote = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!player || !noteContent.trim()) return;
    
    setIsAddingNote(true);
    try {
      const res = await fetch('/api/players/notes', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('auth_token')}` 
        },
        body: JSON.stringify({
          playerNameHash: player.nameHash,
          category: noteCategory,
          content: noteContent,
        }),
      });
      
      if (res.ok) {
        setNoteContent('');
        fetchNotes();
      }
    } catch (err) {
      console.error("Failed to add note:", err);
    } finally {
      setIsAddingNote(false);
    }
  };

  const fetchAndFilterLogs = useCallback(async () => {
    if (!player || !open) return;
    setLoading(true);
    try {
      const res = await fetch('/api/logs', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
        },
      });
      const data = await res.json();
      const encryptedLogs = (data.logs ?? []) as { data: string }[];

      const decrypted = await Promise.all(
        encryptedLogs.map(async (l) => {
          try {
            const binaryString = atob(l.data);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
              bytes[i] = binaryString.charCodeAt(i);
            }
            const decryptedText = await decrypt(bytes);
            return JSON.parse(decryptedText) as LogEvent;
          } catch (e) {
            return null;
          }
        })
      );

      // Filter logs by player nameHash
      const filtered = decrypted.filter((l): l is LogEvent => 
        l !== null && (l.playerNameHash === player.nameHash || l.content.includes(`[BLIND:${player.nameHash}]`))
      );

      setLogs(filtered.reverse()); // Newest first
    } catch (err) {
      console.error("Failed to fetch player logs:", err);
    } finally {
      setLoading(false);
    }
  }, [player, open, decrypt]);

  useEffect(() => {
    fetchAndFilterLogs();
    fetchNotes();
  }, [fetchAndFilterLogs, fetchNotes]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl h-[85vh] flex flex-col bg-[#090b14]/95 backdrop-blur-3xl border-border/50 p-0 overflow-hidden shadow-2xl">
        <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-primary via-indigo-500 to-primary/50" />
        
        <DialogHeader className="px-8 pt-8 pb-6 border-b border-border/20 bg-muted/5">
          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center">
                   <History className="w-5 h-5 text-primary" />
                </div>
                <div>
                  <DialogTitle className="text-2xl font-black tracking-tight flex items-center gap-2">
                    Personnel Insights: <span className="text-primary">{player?.name}</span>
                  </DialogTitle>
                  <DialogDescription className="text-xs font-bold uppercase tracking-widest text-muted-foreground/60">
                    Cryptographic Behavioral Tracking & Log Archive
                  </DialogDescription>
                </div>
              </div>
            </div>
            
            <div className="flex gap-4">
               <div className="text-right">
                  <p className="text-[10px] font-black uppercase text-muted-foreground/40 tracking-widest">Digital Fingerprint</p>
                  <p className="text-[11px] font-mono text-primary/80">{player?.nameHash.slice(0, 16)}...</p>
               </div>
            </div>
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-hidden flex flex-col">
          {/* Quick Stats */}
          <div className="grid grid-cols-4 border-b border-border/10 bg-muted/5">
             <div className="p-4 border-r border-border/10 flex flex-col items-center justify-center text-center gap-1">
                <Activity className="w-4 h-4 text-emerald-500" />
                <span className="text-[10px] font-black uppercase text-muted-foreground/50">Status</span>
                <span className="text-xs font-bold text-emerald-500">Authorized</span>
             </div>
             <div className="p-4 border-r border-border/10 flex flex-col items-center justify-center text-center gap-1">
                <Terminal className="w-4 h-4 text-primary" />
                <span className="text-[10px] font-black uppercase text-muted-foreground/50">Events</span>
                <span className="text-xs font-bold">{logs.length} Records</span>
             </div>
             <div className="p-4 border-r border-border/10 flex flex-col items-center justify-center text-center gap-1">
                <Shield className="w-4 h-4 text-amber-500" />
                <span className="text-[10px] font-black uppercase text-muted-foreground/50">Violations</span>
                <span className="text-xs font-bold">0 Detected</span>
             </div>
             <div className="p-4 flex flex-col items-center justify-center text-center gap-1">
                <Globe className="w-4 h-4 text-blue-500" />
                <span className="text-[10px] font-black uppercase text-muted-foreground/50">Node</span>
                <span className="text-xs font-bold">AMS-01</span>
             </div>
          </div>

          <div className="flex-1 flex overflow-hidden">
             {/* Main Log Area */}
             <div className="flex-1 flex flex-col border-r border-border/10">
                <div className="px-8 py-3 border-b border-border/10 flex items-center justify-between bg-muted/10">
                   <span className="text-[10px] font-black uppercase tracking-widest text-primary/80">Historical Telemetry Stream</span>
                   <div className="flex items-center gap-2">
                      <div className="w-2 h-2 bg-primary rounded-full animate-pulse" />
                      <span className="text-[9px] font-bold text-muted-foreground italic">Syncing with backbone...</span>
                   </div>
                </div>

                <ScrollArea className="flex-1 p-6">
                  {loading && logs.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                      <Loader2 className="w-10 h-10 animate-spin mb-4 text-primary opacity-50" />
                      <p className="text-xs font-black uppercase tracking-widest animate-pulse">Reconstructing encrypted history...</p>
                    </div>
                  ) : logs.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-64 text-muted-foreground opacity-20">
                      <Search className="w-12 h-12 mb-4" />
                      <p className="text-sm font-bold">No historical data identified for this entity.</p>
                    </div>
                  ) : (
                    <div className="space-y-6">
                      {logs.map((event, i) => {
                        const pInfo = event.playerNameHash ? {
                          name: event.playerName || 'Unknown',
                          nameHash: event.playerNameHash
                        } : null;
                        
                        const logRow = (
                          <div key={i} className="group relative pl-6 border-l-2 border-primary/10 hover:border-primary/40 transition-colors py-1">
                            <div className="absolute -left-[5px] top-2 w-2 h-2 rounded-full bg-border border-2 border-background group-hover:bg-primary transition-colors" />
                            <div className="flex flex-col gap-1.5">
                              <div className="flex items-center gap-3">
                                <span className="text-[10px] font-mono font-bold text-muted-foreground/40 bg-muted/20 px-1.5 py-0.5 rounded">
                                  {new Date(event.timestamp).toLocaleString()}
                                </span>
                                <Badge variant={
                                  event.type === 'CHAT' ? 'default' :
                                  event.type === 'JOIN' ? 'secondary' :
                                  event.type === 'LEAVE' ? 'destructive' : 'outline'
                                } className="text-[9px] px-1.5 py-0 h-4 uppercase font-black tracking-tighter">
                                  {event.type}
                                </Badge>
                                {event.serverName && (
                                  <span className="text-[9px] font-black uppercase text-muted-foreground/30 ml-auto tracking-widest">
                                    {event.serverName}
                                  </span>
                                )}
                              </div>
                              <p className={cn(
                                "text-sm leading-relaxed",
                                pInfo ? "text-primary cursor-context-menu font-medium" : "text-foreground/80"
                              )}>
                                {event.content}
                              </p>
                            </div>
                          </div>
                        );

                        return pInfo ? (
                          <PlayerContextMenu 
                            key={i} 
                            player={pInfo} 
                            onViewInsights={(p) => {
                               console.log("Insights for", p.name);
                            }}
                          >
                            {logRow}
                          </PlayerContextMenu>
                        ) : logRow;
                      })}
                    </div>
                  )}
                </ScrollArea>
             </div>

             {/* Metadata Sidebar */}
             <div className="w-80 bg-muted/5 p-6 space-y-8 hidden lg:block overflow-y-auto border-l border-border/10">
                {/* Tactical Notes Section */}
                <div className="space-y-4">
                   <div className="flex items-center justify-between border-b border-border/10 pb-2">
                      <h5 className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Tactical Intel & Notes</h5>
                      <Badge variant="outline" className="text-[9px] font-black">{notes.length}</Badge>
                   </div>

                   <form onSubmit={handleAddNote} className="space-y-3">
                      <select 
                        value={noteCategory} 
                        onChange={e => setNoteCategory(e.target.value)}
                        className="w-full h-8 px-2 bg-background border border-border/50 rounded-md text-[10px] font-black uppercase tracking-widest text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
                      >
                         <option value="info">General Intel</option>
                         <option value="warning">Tactical Warning</option>
                         <option value="violation">Protocol Violation</option>
                         <option value="suspicion">Intel Suspicion</option>
                      </select>
                      <div className="relative">
                        <textarea 
                          value={noteContent}
                          onChange={e => setNoteContent(e.target.value)}
                          placeholder="Record tactical observation..."
                          className="w-full bg-background/50 border border-border/50 rounded-xl p-3 text-xs placeholder:text-muted-foreground/30 focus:outline-none focus:ring-1 focus:ring-primary min-h-[80px] resize-none"
                        />
                        <Button 
                          type="submit" 
                          size="icon" 
                          disabled={isAddingNote || !noteContent.trim()}
                          className="absolute bottom-3 right-3 h-7 w-7 rounded-lg shadow-lg shadow-primary/20"
                        >
                           {isAddingNote ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Plus className="w-3.5 h-3.5" />}
                        </Button>
                      </div>
                   </form>

                   <ScrollArea className="h-[300px] -mx-2 px-2">
                      <div className="space-y-4">
                         {notes.length === 0 ? (
                            <p className="text-[10px] text-muted-foreground/40 italic text-center py-8 font-medium uppercase tracking-widest">Archive records empty</p>
                         ) : (
                            notes.map(note => (
                               <div key={note.id} className={cn(
                                 "p-3 rounded-xl border relative overflow-hidden group",
                                 note.category === 'warning' || note.category === 'violation' 
                                   ? "bg-destructive/5 border-destructive/20" 
                                   : "bg-muted/30 border-border/20"
                               )}>
                                  <div className="flex items-center justify-between mb-2">
                                     <Badge variant="outline" className={cn(
                                       "text-[8px] font-black uppercase h-4 px-1.5",
                                       note.category === 'warning' || note.category === 'violation' ? "text-destructive border-destructive/30" : "text-muted-foreground/60"
                                     )}>
                                        {note.category}
                                     </Badge>
                                     <span className="text-[8px] font-mono text-muted-foreground/40">{new Date(note.createdAt).toLocaleDateString()}</span>
                                  </div>
                                  <p className="text-[11px] leading-relaxed text-foreground/80">{note.content}</p>
                                  <div className="mt-2 text-[8px] font-black uppercase tracking-widest text-muted-foreground/30">Recorded by {note.createdBy}</div>
                               </div>
                            ))
                         )}
                      </div>
                   </ScrollArea>
                </div>

                <div className="space-y-4">
                   <h5 className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60 border-b border-border/10 pb-2">Known Metadata</h5>
                   <div className="space-y-3">
                      <div className="flex flex-col gap-1">
                         <span className="text-[9px] font-bold text-muted-foreground/40 uppercase">Initial Detection</span>
                         <span className="text-[11px] font-medium">{logs.length > 0 ? new Date(logs[logs.length-1].timestamp).toLocaleDateString() : 'Unknown'}</span>
                      </div>
                      <div className="flex flex-col gap-1">
                         <span className="text-[9px] font-bold text-muted-foreground/40 uppercase">Last Network Node</span>
                         <span className="text-[11px] font-medium flex items-center gap-1.5">
                            <MapPin className="w-3 h-3 text-primary" />
                            AMS-NODE-01
                         </span>
                      </div>
                      <div className="flex flex-col gap-1">
                         <span className="text-[9px] font-bold text-muted-foreground/40 uppercase">Clearance Level</span>
                         <Badge className="w-fit bg-emerald-500/10 text-emerald-500 border-emerald-500/20 text-[9px] font-black uppercase">Standard_Personnel</Badge>
                      </div>
                   </div>
                </div>

                <div className="space-y-4">
                   <h5 className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60 border-b border-border/10 pb-2">Security Advisory</h5>
                   <div className="p-3 bg-primary/5 rounded-lg border border-primary/10">
                      <p className="text-[10px] leading-relaxed text-muted-foreground italic">
                        No suspicious behavioral patterns identified within the last 50 cryptographic cycles. Entity remains within established operational parameters.
                      </p>
                   </div>
                </div>
             </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};
