import { useEffect, useState } from "react"
import { Trash2, Sparkles, User, Scroll, Shield, Tag, Clock, Search, Plus, BookOpen } from "lucide-react"
import { api, type DedupeResult, type Memory } from "@/lib/api"
import { cn } from "@/lib/utils"
import { CustomDialog } from "@/components/CustomDialog"


const CATEGORIES = ["user", "instruction", "stable", "versioned", "ephemeral"]

const CAT_CONFIG: Record<string, { label: string; icon: any; color: string; border: string; bg: string; text: string }> = {
  user: { label: "User", icon: User, color: "text-cyan-400", border: "border-cyan-500/30", bg: "bg-cyan-500/10", text: "text-cyan-400" },
  instruction: { label: "Regel", icon: Scroll, color: "text-violet-400", border: "border-violet-500/30", bg: "bg-violet-500/10", text: "text-violet-400" },
  stable: { label: "Fakt", icon: Shield, color: "text-indigo-400", border: "border-indigo-500/30", bg: "bg-indigo-500/10", text: "text-indigo-400" },
  versioned: { label: "Version", icon: Tag, color: "text-amber-400", border: "border-amber-500/30", bg: "bg-amber-500/10", text: "text-amber-400" },
  ephemeral: { label: "Temporär", icon: Clock, color: "text-pink-400", border: "border-pink-500/30", bg: "bg-pink-500/10", text: "text-pink-400" },
}

const DEFAULT_CAT = { label: "Gedächtnis", icon: BookOpen, color: "text-muted-foreground", border: "border-border/40", bg: "bg-muted/10", text: "text-muted-foreground" }

const BORDER_CLASSES: Record<string, string> = {
  user: "border-l-cyan-500/80",
  instruction: "border-l-violet-500/80",
  stable: "border-l-indigo-500/80",
  versioned: "border-l-amber-500/80",
  ephemeral: "border-l-pink-500/80",
}

export function MemoryView() {
  const [items, setItems] = useState<Memory[]>([])
  const [filter, setFilter] = useState("")
  const [q, setQ] = useState("")
  const [content, setContent] = useState("")
  const [category, setCategory] = useState("stable")
  const [error, setError] = useState("")
  const [deduping, setDeduping] = useState(false)

  // Custom Dialog State
  const [dialog, setDialog] = useState<{
    type: "alert" | "confirm"
    title: string
    message: string
    onConfirm: () => void
    onCancel?: () => void
  } | null>(null)

  function showAlert(title: string, message: string, onConfirm?: () => void) {
    setDialog({
      type: "alert",
      title,
      message,
      onConfirm: () => {
        setDialog(null)
        if (onConfirm) onConfirm()
      }
    })
  }

  function showConfirm(title: string, message: string, onConfirm: () => void) {
    setDialog({
      type: "confirm",
      title,
      message,
      onConfirm: () => {
        setDialog(null)
        onConfirm()
      },
      onCancel: () => setDialog(null)
    })
  }


  function load() {
    const params = new URLSearchParams()
    if (q) params.set("q", q)
    if (filter) params.set("category", filter)
    api<Memory[]>(`/api/memory?${params}`)
      .then(setItems)
      .catch((e) => setError(String(e)))
  }

  useEffect(load, [q, filter])

  async function add() {
    if (!content.trim()) return
    await api("/api/memory", { 
      method: "POST", 
      body: JSON.stringify({ content, category, source: "ui" }) 
    })
    setContent("")
    load()
  }

  async function del(id: string) {
    await api(`/api/memory/${id}`, { method: "DELETE" })
    load()
  }

  async function cleanup() {
    setDeduping(true)
    try {
      const dry = await api<DedupeResult>("/api/memory/dedupe", {
        method: "POST", 
        body: JSON.stringify({ apply: false }),
      })
      if (dry.duplicate_count === 0) {
        showAlert("Ergebnis", "Keine Dubletten gefunden — alles sauber.")
        return
      }
      showConfirm(
        "Deduplizierung bestätigen",
        `${dry.duplicate_count} Dublette(n) in ${dry.groups.length} Gruppe(n) gefunden. Entfernen?`,
        async () => {
          try {
            await api("/api/memory/dedupe", { 
              method: "POST", 
              body: JSON.stringify({ apply: true }) 
            })
            load()
          } catch (e: any) {
            showAlert("Fehler", `Fehler beim Löschen: ${e.message}`)
          }
        }
      )
    } catch (e: any) {
      showAlert("Fehler", `Fehler bei der Deduplizierung: ${e.message}`)
    } finally {
      setDeduping(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
        <div>
          <h1 className="text-2xl font-space font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-primary bg-clip-text text-transparent">
            Gedächtnis-Pool (Memory)
          </h1>
          <p className="text-sm text-muted-foreground">
            Die geteilte Konstitution des Systems. Alle Instanzen (Hermes, IDEs, Gateway) lesen und schreiben hierauf per MCP-Protokoll.
          </p>
        </div>

        <button
          onClick={cleanup}
          disabled={deduping}
          className="flex h-9 px-4 items-center gap-1.5 text-xs font-semibold rounded-lg border border-border/60 bg-card hover:border-primary/50 transition-all cursor-pointer shadow-md disabled:opacity-50 shrink-0 self-start"
        >
          <Sparkles className="h-4 w-4 text-primary animate-pulse" />
          <span>Deduplizieren</span>
        </button>
      </div>

      {/* Add New Fact Box */}
      <div className="rounded-2xl border border-border/60 bg-card/45 backdrop-blur-md p-5 shadow-lg shadow-black/10 space-y-4">
        <div className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Neuen Eintrag anlegen</div>
        
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder="Füge eine neue Regel, eine Vorliebe oder einen stabilen Fakt über das Projekt oder dich hinzu..."
          rows={3}
          className="w-full resize-none rounded-xl border border-border/60 bg-background/30 p-3.5 text-xs outline-none focus:ring-1 focus:ring-primary/50 text-foreground transition-all leading-relaxed"
        />

        <div className="flex flex-wrap items-center justify-between gap-3">
          <div className="flex items-center gap-2">
            <span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">Kategorie</span>
            <select
              value={category}
              onChange={(e) => setCategory(e.target.value)}
              className="h-8 rounded-lg border border-border/60 bg-background/50 px-2 py-1 text-xs outline-none font-semibold text-foreground cursor-pointer"
            >
              {CATEGORIES.map((c) => (
                <option key={c} value={c} className="bg-popover text-foreground">
                  {CAT_CONFIG[c]?.label || c}
                </option>
              ))}
            </select>
          </div>

          <button 
            onClick={add} 
            className="h-9 px-4 rounded-lg bg-primary text-primary-foreground text-xs font-semibold hover:opacity-90 transition-all flex items-center gap-1.5 cursor-pointer shadow-md shadow-primary/10"
          >
            <Plus className="h-4 w-4" /> Speichern
          </button>
        </div>
      </div>

      {/* Filter / Search HUD */}
      <div className="flex flex-col md:flex-row items-stretch md:items-center gap-3">
        <div className="relative flex-1">
          <input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Gedächtnis durchsuchen..."
            className="w-full h-9 pl-9 pr-3 rounded-lg border border-border/60 bg-card/45 text-xs outline-none focus:ring-1 focus:ring-primary/50 text-foreground"
          />
          <Search className="absolute left-3 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
        </div>

        <div className="flex flex-wrap items-center gap-1.5 p-1 bg-card/30 border border-border/40 rounded-xl overflow-x-auto max-w-full">
          <button
            onClick={() => setFilter("")}
            className={cn(
              "h-7 px-3 rounded-lg text-[10px] font-semibold uppercase tracking-wider transition-all cursor-pointer whitespace-nowrap",
              !filter ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground"
            )}
          >
            Alle
          </button>
          {CATEGORIES.map((c) => {
            const conf = CAT_CONFIG[c] || DEFAULT_CAT
            const Icon = conf.icon
            return (
              <button
                key={c}
                onClick={() => setFilter(c)}
                className={cn(
                  "h-7 px-2.5 rounded-lg text-[10px] font-semibold uppercase tracking-wider transition-all cursor-pointer flex items-center gap-1 whitespace-nowrap",
                  filter === c 
                    ? "bg-primary text-primary-foreground" 
                    : "text-muted-foreground hover:text-foreground"
                )}
              >
                <Icon className="h-3 w-3" />
                <span>{conf.label}</span>
              </button>
            )
          })}
        </div>
      </div>

      {error && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/5 p-4 text-xs text-red-400">
          Fehler beim Laden des Gedächtnisses: {error}
        </div>
      )}

      {/* Facts List */}
      <div className="space-y-3">
        {items.length === 0 ? (
          <div className="text-xs text-muted-foreground border border-dashed border-border/60 rounded-2xl p-12 text-center">
            Keine Einträge für die aktuellen Filterkriterien gefunden.
          </div>
        ) : (
          items.map((m) => {
            const conf = CAT_CONFIG[m.category] || DEFAULT_CAT
            const Icon = conf.icon
            return (
              <div 
                key={m.id} 
                className={cn(
                  "flex items-start justify-between gap-4 p-4 rounded-xl border border-l-4 bg-card/45 backdrop-blur-md border-border/60 shadow-md shadow-black/5 hover:border-primary/20 transition-all group",
                  BORDER_CLASSES[m.category] || "border-l-muted"
                )}
              >
                <div className="flex items-start gap-3 flex-1 min-w-0">
                  <span className={cn(
                    "flex items-center gap-1 px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider font-mono shrink-0",
                    conf.bg, conf.text
                  )}>
                    <Icon className="h-3 w-3" />
                    <span className="hidden sm:inline">{conf.label}</span>
                  </span>
                  <span className="text-xs text-foreground leading-relaxed break-words whitespace-pre-wrap flex-1">{m.content}</span>
                </div>
                
                <div className="flex items-center gap-3 shrink-0">
                  <span className="text-[9px] font-mono text-muted-foreground/60 bg-background/20 px-1.5 py-0.5 rounded uppercase tracking-wider">
                    {m.source}
                  </span>
                  <button 
                    onClick={() => del(m.id)} 
                    className="h-7 w-7 rounded-lg flex items-center justify-center border border-border/40 text-muted-foreground hover:text-red-400 hover:bg-red-500/5 transition-all opacity-0 group-hover:opacity-100"
                    title="Eintrag löschen"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>
            )
          })
        )}
      </div>

      {dialog && (
        <CustomDialog
          type={dialog.type}
          title={dialog.title}
          message={dialog.message}
          onConfirm={dialog.onConfirm}
          onCancel={dialog.onCancel}
        />
      )}
    </div>
  )
}
