'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { InternalHeader } from '@/components/ui/internal-header';
import { InternalGate } from '@/components/ui/internal-gate';
import {
  Brain, Search, Plus, Edit3, Trash2, RefreshCw,
  Tag, Clock, Star, ChevronDown, ChevronRight,
  Lightbulb, Heart, FileText, Zap, Eye, X, Save, AlertCircle,
  Sparkles, Link2, AlertTriangle, TrendingUp, Database, Terminal
} from 'lucide-react';

interface TesaMemory {
  id: string;
  category: string;
  key: string;
  value: string;
  context: string | null;
  source: string;
  importance: number;
  confidence: number;
  tags: string[];
  relatedIds: string[];
  lastAccessed: string | null;
  accessCount: number;
  expiresAt: string | null;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

interface Stats {
  total: number;
  byCategory: Record<string, number>;
}

interface Insight {
  type: 'pattern' | 'gap' | 'connection' | 'suggestion' | 'stale';
  title: string;
  description: string;
  relatedMemoryIds: string[];
  importance: number;
  actionable: boolean;
}

const CATEGORIES = [
  { id: 'decision', label: 'Decisions', icon: Lightbulb, color: 'text-yellow-400', bgColor: 'bg-yellow-500/20' },
  { id: 'preference', label: 'Preferences', icon: Heart, color: 'text-pink-400', bgColor: 'bg-pink-500/20' },
  { id: 'context', label: 'Context', icon: FileText, color: 'text-blue-400', bgColor: 'bg-blue-500/20' },
  { id: 'insight', label: 'Insights', icon: Zap, color: 'text-brand-secondary-light', bgColor: 'bg-brand-secondary/20' },
  { id: 'fact', label: 'Facts', icon: Eye, color: 'text-brand', bgColor: 'bg-brand-deep/20' },
];

export default function TesaMemoryPage() {
  const [memories, setMemories] = useState<TesaMemory[]>([]);
  const [stats, setStats] = useState<Stats>({ total: 0, byCategory: {} });
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [showAddModal, setShowAddModal] = useState(false);
  const [editingMemory, setEditingMemory] = useState<TesaMemory | null>(null);
  const [expandedMemories, setExpandedMemories] = useState<Set<string>>(new Set());
  const [activeTab, setActiveTab] = useState<'memories' | 'insights' | 'mcp'>('memories');
  const [insights, setInsights] = useState<Insight[]>([]);
  const [insightsLoading, setInsightsLoading] = useState(false);
  const [generatingInsights, setGeneratingInsights] = useState(false);

  const fetchMemories = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (searchQuery) params.set('search', searchQuery);
      if (selectedCategory) params.set('category', selectedCategory);
      
      const res = await fetch(`/api/tesa/memory?${params.toString()}`);
      const data = await res.json();
      setMemories(data.memories || []);
      setStats(data.stats || { total: 0, byCategory: {} });
    } catch (error) {
      console.error('Failed to fetch memories:', error);
    } finally {
      setLoading(false);
    }
  }, [searchQuery, selectedCategory]);

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

  const fetchInsights = useCallback(async (useLLM = false) => {
    setInsightsLoading(true);
    try {
      const res = await fetch(`/api/tesa/insights?llm=${useLLM}`);
      const data = await res.json();
      setInsights(data.insights || []);
    } catch (error) {
      console.error('Failed to fetch insights:', error);
    } finally {
      setInsightsLoading(false);
    }
  }, []);

  const generateAndSaveInsights = async (useLLM = false) => {
    setGeneratingInsights(true);
    try {
      const res = await fetch('/api/tesa/insights', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ includeLLM: useLLM, save: true }),
      });
      const data = await res.json();
      setInsights(data.insights || []);
      // Refresh memories to show newly saved insights
      fetchMemories();
    } catch (error) {
      console.error('Failed to generate insights:', error);
    } finally {
      setGeneratingInsights(false);
    }
  };

  useEffect(() => {
    if (activeTab === 'insights') {
      fetchInsights();
    }
  }, [activeTab, fetchInsights]);

  const toggleExpanded = (id: string) => {
    setExpandedMemories(prev => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Archive this memory? (It can be restored later)')) return;
    try {
      await fetch(`/api/tesa/memory?id=${id}`, { method: 'DELETE' });
      fetchMemories();
    } catch (error) {
      console.error('Failed to delete memory:', error);
    }
  };

  const getCategoryInfo = (categoryId: string) => {
    return CATEGORIES.find(c => c.id === categoryId) || CATEGORIES[4];
  };

  return (
    <InternalGate>
    <div className="min-h-screen bg-brand-bg">
      <InternalHeader />
      
      <main className="pt-20 p-6 max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-gradient-to-br from-brand-deep/20 to-brand-secondary/20 border border-brand-deep/30">
              <Brain className="w-8 h-8 text-brand" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">Tesa&apos;s Memory</h1>
              <p className="text-gray-400">What I remember about you and our work together</p>
            </div>
          </div>
          {activeTab === 'memories' && (
            <button
              onClick={() => setShowAddModal(true)}
              className="flex items-center gap-2 px-4 py-2 bg-brand-deep hover:bg-brand-deep text-white rounded-lg transition-colors"
            >
              <Plus className="w-4 h-4" />
              Add Memory
            </button>
          )}
        </div>

        {/* Tab Navigation */}
        <div className="flex items-center gap-1 mb-6 p-1 bg-slate-900 rounded-lg border border-slate-700 w-fit">
          <button
            onClick={() => setActiveTab('memories')}
            className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
              activeTab === 'memories'
                ? 'bg-brand-deep text-white'
                : 'text-gray-400 hover:text-white hover:bg-slate-800'
            }`}
          >
            <Database className="w-4 h-4" />
            Memories
          </button>
          <button
            onClick={() => setActiveTab('insights')}
            className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
              activeTab === 'insights'
                ? 'bg-brand-secondary text-white'
                : 'text-gray-400 hover:text-white hover:bg-slate-800'
            }`}
          >
            <Sparkles className="w-4 h-4" />
            Insights
          </button>
          <button
            onClick={() => setActiveTab('mcp')}
            className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
              activeTab === 'mcp'
                ? 'bg-green-500 text-white'
                : 'text-gray-400 hover:text-white hover:bg-slate-800'
            }`}
          >
            <Terminal className="w-4 h-4" />
            MCP Server
          </button>
        </div>

        {/* Memories Tab */}
        {activeTab === 'memories' && (
          <>
            {/* Stats Bar */}
        <div className="grid grid-cols-2 md:grid-cols-6 gap-4 mb-6">
          <div
            onClick={() => setSelectedCategory(null)}
            className={`p-4 rounded-xl border cursor-pointer transition-all ${
              selectedCategory === null
                ? 'bg-slate-800 border-brand-deep/50'
                : 'bg-slate-900 border-slate-700 hover:border-slate-600'
            }`}
          >
            <p className="text-2xl font-bold text-white">{stats.total}</p>
            <p className="text-sm text-gray-400">Total Memories</p>
          </div>
          {CATEGORIES.map(cat => {
            const Icon = cat.icon;
            const count = stats.byCategory[cat.id] || 0;
            return (
              <div
                key={cat.id}
                onClick={() => setSelectedCategory(selectedCategory === cat.id ? null : cat.id)}
                className={`p-4 rounded-xl border cursor-pointer transition-all ${
                  selectedCategory === cat.id
                    ? `${cat.bgColor} border-current ${cat.color}`
                    : 'bg-slate-900 border-slate-700 hover:border-slate-600'
                }`}
              >
                <div className="flex items-center gap-2">
                  <Icon className={`w-4 h-4 ${cat.color}`} />
                  <p className="text-xl font-bold text-white">{count}</p>
                </div>
                <p className="text-sm text-gray-400">{cat.label}</p>
              </div>
            );
          })}
        </div>

        {/* Search Bar */}
        <div className="relative mb-6">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
          <input
            type="text"
            placeholder="Search memories..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-12 pr-4 py-3 bg-slate-900 border border-slate-700 rounded-xl text-white placeholder-gray-500 focus:border-brand-deep/50 focus:outline-none"
          />
          {searchQuery && (
            <button
              onClick={() => setSearchQuery('')}
              className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>

        {/* Memory List */}
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <RefreshCw className="w-8 h-8 text-brand animate-spin" />
          </div>
        ) : memories.length === 0 ? (
          <div className="text-center py-20">
            <Brain className="w-16 h-16 text-gray-600 mx-auto mb-4" />
            <h3 className="text-xl font-medium text-white mb-2">No memories yet</h3>
            <p className="text-gray-400 mb-6">
              {searchQuery || selectedCategory
                ? 'No memories match your filters'
                : "Start adding memories so I can remember important things about our work together"}
            </p>
            {!searchQuery && !selectedCategory && (
              <button
                onClick={() => setShowAddModal(true)}
                className="px-4 py-2 bg-brand-deep hover:bg-brand-deep text-white rounded-lg transition-colors"
              >
                Add First Memory
              </button>
            )}
          </div>
        ) : (
          <div className="space-y-3">
            {memories.map(memory => {
              const cat = getCategoryInfo(memory.category);
              const Icon = cat.icon;
              const isExpanded = expandedMemories.has(memory.id);
              
              return (
                <motion.div
                  key={memory.id}
                  layout
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="bg-slate-900 border border-slate-700 rounded-xl overflow-hidden"
                >
                  <div
                    onClick={() => toggleExpanded(memory.id)}
                    className="flex items-start gap-4 p-4 cursor-pointer hover:bg-slate-800/50 transition-colors"
                  >
                    <div className={`p-2 rounded-lg ${cat.bgColor}`}>
                      <Icon className={`w-5 h-5 ${cat.color}`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <h3 className="font-medium text-white truncate">{memory.key}</h3>
                        {memory.importance >= 8 && (
                          <Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
                        )}
                      </div>
                      <p className="text-gray-300 text-sm line-clamp-2">{memory.value}</p>
                      <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {new Date(memory.updatedAt).toLocaleDateString()}
                        </span>
                        {Array.isArray(memory.tags) && memory.tags.length > 0 && (
                          <span className="flex items-center gap-1">
                            <Tag className="w-3 h-3" />
                            {memory.tags.slice(0, 3).join(', ')}
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setEditingMemory(memory);
                        }}
                        className="p-2 text-gray-400 hover:text-brand transition-colors"
                      >
                        <Edit3 className="w-4 h-4" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDelete(memory.id);
                        }}
                        className="p-2 text-gray-400 hover:text-red-400 transition-colors"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                      {isExpanded ? (
                        <ChevronDown className="w-5 h-5 text-gray-400" />
                      ) : (
                        <ChevronRight className="w-5 h-5 text-gray-400" />
                      )}
                    </div>
                  </div>
                  
                  <AnimatePresence>
                    {isExpanded && (
                      <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: 'auto', opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        className="border-t border-slate-700"
                      >
                        <div className="p-4 bg-slate-800/50">
                          <div className="grid md:grid-cols-2 gap-4">
                            <div>
                              <h4 className="text-xs font-medium text-gray-500 uppercase mb-1">Full Value</h4>
                              <p className="text-gray-300 text-sm whitespace-pre-wrap">{memory.value}</p>
                            </div>
                            {memory.context && (
                              <div>
                                <h4 className="text-xs font-medium text-gray-500 uppercase mb-1">Context</h4>
                                <p className="text-gray-400 text-sm">{memory.context}</p>
                              </div>
                            )}
                          </div>
                          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4 pt-4 border-t border-slate-700">
                            <div>
                              <h4 className="text-xs font-medium text-gray-500 uppercase mb-1">Source</h4>
                              <p className="text-gray-300 text-sm">{memory.source}</p>
                            </div>
                            <div>
                              <h4 className="text-xs font-medium text-gray-500 uppercase mb-1">Importance</h4>
                              <div className="flex items-center gap-1">
                                {[...Array(10)].map((_, i) => (
                                  <div
                                    key={i}
                                    className={`w-2 h-2 rounded-full ${
                                      i < memory.importance ? 'bg-brand' : 'bg-slate-700'
                                    }`}
                                  />
                                ))}
                              </div>
                            </div>
                            <div>
                              <h4 className="text-xs font-medium text-gray-500 uppercase mb-1">Confidence</h4>
                              <p className="text-gray-300 text-sm">{Math.round(memory.confidence * 100)}%</p>
                            </div>
                            <div>
                              <h4 className="text-xs font-medium text-gray-500 uppercase mb-1">Access Count</h4>
                              <p className="text-gray-300 text-sm">{memory.accessCount} times</p>
                            </div>
                          </div>
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </motion.div>
              );
            })}
          </div>
        )}
          </>
        )}

        {/* Insights Tab */}
        {activeTab === 'insights' && (
          <div className="space-y-6">
            {/* Insights Header */}
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-lg font-semibold text-white">Pattern Analysis</h2>
                <p className="text-sm text-gray-400">Insights generated from your memory bank</p>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => fetchInsights()}
                  disabled={insightsLoading}
                  className="flex items-center gap-2 px-3 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-lg transition-colors text-sm"
                >
                  <RefreshCw className={`w-4 h-4 ${insightsLoading ? 'animate-spin' : ''}`} />
                  Refresh
                </button>
                <button
                  onClick={() => generateAndSaveInsights(true)}
                  disabled={generatingInsights}
                  className="flex items-center gap-2 px-3 py-2 bg-brand-secondary hover:bg-brand-secondary-deep text-white rounded-lg transition-colors text-sm"
                >
                  <Sparkles className={`w-4 h-4 ${generatingInsights ? 'animate-pulse' : ''}`} />
                  {generatingInsights ? 'Analyzing...' : 'Generate with AI'}
                </button>
              </div>
            </div>

            {/* Insights List */}
            {insightsLoading ? (
              <div className="flex items-center justify-center py-20">
                <RefreshCw className="w-8 h-8 text-brand-secondary-light animate-spin" />
              </div>
            ) : insights.length === 0 ? (
              <div className="text-center py-20">
                <Sparkles className="w-16 h-16 text-gray-600 mx-auto mb-4" />
                <h3 className="text-xl font-medium text-white mb-2">No insights yet</h3>
                <p className="text-gray-400 mb-6">
                  Add more memories to generate meaningful insights
                </p>
              </div>
            ) : (
              <div className="grid gap-4">
                {insights.map((insight, idx) => {
                  const typeConfig = {
                    pattern: { icon: TrendingUp, color: 'text-blue-400', bg: 'bg-blue-500/20', border: 'border-blue-500/30' },
                    gap: { icon: AlertTriangle, color: 'text-yellow-400', bg: 'bg-yellow-500/20', border: 'border-yellow-500/30' },
                    connection: { icon: Link2, color: 'text-brand-secondary-light', bg: 'bg-brand-secondary/20', border: 'border-brand-secondary/30' },
                    suggestion: { icon: Lightbulb, color: 'text-green-400', bg: 'bg-green-500/20', border: 'border-green-500/30' },
                    stale: { icon: Clock, color: 'text-orange-400', bg: 'bg-orange-500/20', border: 'border-orange-500/30' },
                  };
                  const config = typeConfig[insight.type];
                  const Icon = config.icon;

                  return (
                    <motion.div
                      key={idx}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: idx * 0.05 }}
                      className={`p-4 rounded-xl border ${config.border} ${config.bg}`}
                    >
                      <div className="flex items-start gap-4">
                        <div className={`p-2 rounded-lg ${config.bg}`}>
                          <Icon className={`w-5 h-5 ${config.color}`} />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <h3 className="font-medium text-white">{insight.title}</h3>
                            {insight.actionable && (
                              <span className="text-xs px-2 py-0.5 bg-green-500/20 text-green-400 rounded-full">
                                Actionable
                              </span>
                            )}
                          </div>
                          <p className="text-gray-300 text-sm">{insight.description}</p>
                          <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                            <span>Importance: {insight.importance}/10</span>
                            {insight.relatedMemoryIds.length > 0 && (
                              <span>{insight.relatedMemoryIds.length} related memories</span>
                            )}
                          </div>
                        </div>
                      </div>
                    </motion.div>
                  );
                })}
              </div>
            )}
          </div>
        )}

        {/* MCP Server Tab */}
        {activeTab === 'mcp' && (
          <div className="space-y-6">
            <div className="bg-slate-900 border border-slate-700 rounded-xl p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="p-2 rounded-lg bg-green-500/20">
                  <Terminal className="w-6 h-6 text-green-400" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-white">MCP Server</h2>
                  <p className="text-sm text-gray-400">Connect external AI clients to Tesa&apos;s memory</p>
                </div>
              </div>

              <div className="space-y-4">
                <div className="p-4 bg-slate-800 rounded-lg">
                  <h3 className="text-sm font-medium text-gray-300 mb-2">Endpoint</h3>
                  <code className="text-brand text-sm bg-slate-900 px-3 py-1.5 rounded block">
                    POST {typeof window !== 'undefined' ? window.location.origin : ''}/api/tesa/mcp
                  </code>
                </div>

                <div className="p-4 bg-slate-800 rounded-lg">
                  <h3 className="text-sm font-medium text-gray-300 mb-2">Available Methods</h3>
                  <div className="grid md:grid-cols-2 gap-2 text-sm">
                    {[
                      { method: 'mcp.info', desc: 'Get server capabilities' },
                      { method: 'memory.query', desc: 'Query memories with filters' },
                      { method: 'memory.write', desc: 'Create or update a memory' },
                      { method: 'memory.search', desc: 'Full-text search' },
                      { method: 'memory.stale', desc: 'Find neglected memories' },
                      { method: 'memory.crossref', desc: 'Find related memories' },
                      { method: 'memory.stats', desc: 'Get memory statistics' },
                    ].map(m => (
                      <div key={m.method} className="flex items-center gap-2 p-2 bg-slate-900 rounded">
                        <code className="text-green-400">{m.method}</code>
                        <span className="text-gray-500 text-xs">— {m.desc}</span>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="p-4 bg-slate-800 rounded-lg">
                  <h3 className="text-sm font-medium text-gray-300 mb-2">Example Request</h3>
                  <pre className="text-xs text-gray-300 bg-slate-900 p-3 rounded overflow-x-auto">
{`{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "memory.search",
  "params": {
    "query": "security",
    "limit": 10
  }
}`}
                  </pre>
                </div>

                <div className="p-4 bg-slate-800 rounded-lg">
                  <h3 className="text-sm font-medium text-gray-300 mb-2">Authentication</h3>
                  <p className="text-gray-400 text-sm mb-2">
                    Set <code className="text-brand">TESA_MCP_API_KEY</code> in your environment to require authentication.
                    Pass the key via <code className="text-brand">Authorization: Bearer &lt;key&gt;</code> or <code className="text-brand">X-API-Key</code> header.
                  </p>
                  <p className="text-yellow-400 text-sm">
                    ⚠️ Currently running in open mode (no key set)
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}
      </main>

      {/* Add/Edit Modal */}
      <AnimatePresence>
        {(showAddModal || editingMemory) && (
          <MemoryModal
            memory={editingMemory}
            onClose={() => {
              setShowAddModal(false);
              setEditingMemory(null);
            }}
            onSave={() => {
              setShowAddModal(false);
              setEditingMemory(null);
              fetchMemories();
            }}
          />
        )}
      </AnimatePresence>
    </div>
    </InternalGate>
  );
}

function MemoryModal({
  memory,
  onClose,
  onSave,
}: {
  memory: TesaMemory | null;
  onClose: () => void;
  onSave: () => void;
}) {
  const [form, setForm] = useState({
    category: memory?.category || 'fact',
    key: memory?.key || '',
    value: memory?.value || '',
    context: memory?.context || '',
    importance: memory?.importance || 5,
    tags: Array.isArray(memory?.tags) ? (memory?.tags as string[]).join(', ') : '',
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError('');

    try {
      const payload = {
        ...form,
        tags: form.tags.split(',').map(t => t.trim()).filter(Boolean),
        ...(memory && { id: memory.id }),
      };

      const res = await fetch('/api/tesa/memory', {
        method: memory ? 'PATCH' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (!res.ok) throw new Error('Failed to save');
      onSave();
    } catch (err) {
      setError('Failed to save memory');
    } finally {
      setSaving(false);
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        onClick={(e) => e.stopPropagation()}
        className="bg-slate-900 border border-slate-700 rounded-xl w-full max-w-lg max-h-[90vh] overflow-y-auto"
      >
        <div className="p-6">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-bold text-white">
              {memory ? 'Edit Memory' : 'Add Memory'}
            </h2>
            <button onClick={onClose} className="text-gray-400 hover:text-white">
              <X className="w-5 h-5" />
            </button>
          </div>

          {error && (
            <div className="flex items-center gap-2 p-3 mb-4 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400">
              <AlertCircle className="w-4 h-4" />
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">Category</label>
              <div className="grid grid-cols-5 gap-2">
                {CATEGORIES.map(cat => {
                  const Icon = cat.icon;
                  return (
                    <button
                      key={cat.id}
                      type="button"
                      onClick={() => setForm({ ...form, category: cat.id })}
                      className={`p-3 rounded-lg border text-center transition-all ${
                        form.category === cat.id
                          ? `${cat.bgColor} border-current ${cat.color}`
                          : 'bg-slate-800 border-slate-700 text-gray-400 hover:border-slate-600'
                      }`}
                    >
                      <Icon className="w-5 h-5 mx-auto mb-1" />
                      <span className="text-xs">{cat.label}</span>
                    </button>
                  );
                })}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">Key (identifier)</label>
              <input
                type="text"
                value={form.key}
                onChange={(e) => setForm({ ...form, key: e.target.value })}
                placeholder="e.g., password_hashing_choice"
                className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:border-brand-deep/50 focus:outline-none"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">Value (the memory itself)</label>
              <textarea
                value={form.value}
                onChange={(e) => setForm({ ...form, value: e.target.value })}
                placeholder="What should I remember?"
                rows={4}
                className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:border-brand-deep/50 focus:outline-none resize-none"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">Context (optional)</label>
              <textarea
                value={form.context}
                onChange={(e) => setForm({ ...form, context: e.target.value })}
                placeholder="When/why was this recorded?"
                rows={2}
                className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:border-brand-deep/50 focus:outline-none resize-none"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Importance: {form.importance}/10
              </label>
              <input
                type="range"
                min="1"
                max="10"
                value={form.importance}
                onChange={(e) => setForm({ ...form, importance: parseInt(e.target.value) })}
                className="w-full accent-cyan-500"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">Tags (comma-separated)</label>
              <input
                type="text"
                value={form.tags}
                onChange={(e) => setForm({ ...form, tags: e.target.value })}
                placeholder="e.g., security, architecture, preference"
                className="w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:border-brand-deep/50 focus:outline-none"
              />
            </div>

            <div className="flex gap-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="flex-1 px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={saving}
                className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-brand-deep hover:bg-brand-deep disabled:bg-brand-deep/50 text-white rounded-lg transition-colors"
              >
                {saving ? (
                  <RefreshCw className="w-4 h-4 animate-spin" />
                ) : (
                  <Save className="w-4 h-4" />
                )}
                {memory ? 'Update' : 'Save'}
              </button>
            </div>
          </form>
        </div>
      </motion.div>
    </motion.div>
  );
}
