'use client';

import { useState, useEffect } from 'react';
import { InternalHeader } from '@/components/ui/internal-header';
import Footer from '@/components/ui/footer';
import { 
  Brain, Settings, Shield, Zap, Database, Network, AlertTriangle,
  CheckCircle, XCircle, Save, RefreshCw, Info, BookOpen, Code, Users
} from 'lucide-react';
import { BRAND, VOCAB } from '@/lib/white-label/constants';

interface MemoryConfig {
  id: string;
  enabled: boolean;
  retentionDays: number;
  maxMemoriesPerAgent: number;
  maxInsightsPerDay: number;
  autoCleanupEnabled: boolean;
  crossAgentSharingEnabled: boolean;
  mcpEndpointEnabled: boolean;
  llmInsightsEnabled: boolean;
  proactiveAlertsEnabled: boolean;
  sensitiveDataFiltering: boolean;
  auditLogging: boolean;
}

const defaultConfig: MemoryConfig = {
  id: '',
  enabled: false,
  retentionDays: 365,
  maxMemoriesPerAgent: 10000,
  maxInsightsPerDay: 100,
  autoCleanupEnabled: true,
  crossAgentSharingEnabled: true,
  mcpEndpointEnabled: false,
  llmInsightsEnabled: true,
  proactiveAlertsEnabled: true,
  sensitiveDataFiltering: true,
  auditLogging: true
};

export default function MemorySystemPage() {
  const [activeTab, setActiveTab] = useState<'setup' | 'docs' | 'api'>('setup');
  const [config, setConfig] = useState<MemoryConfig>(defaultConfig);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

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

  const fetchConfig = async () => {
    try {
      const res = await fetch('/api/gfs/memory-config');
      const data = await res.json();
      if (data.config) {
        setConfig(data.config);
      }
    } catch (error) {
      console.error('Error fetching config:', error);
    } finally {
      setLoading(false);
    }
  };

  const saveConfig = async () => {
    setSaving(true);
    setMessage(null);
    try {
      const res = await fetch('/api/gfs/memory-config', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config)
      });
      const data = await res.json();
      if (data.success) {
        setMessage({ type: 'success', text: 'Configuration saved successfully!' });
      } else {
        setMessage({ type: 'error', text: data.error || 'Failed to save configuration' });
      }
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message });
    } finally {
      setSaving(false);
    }
  };

  const ToggleSwitch = ({ value, onChange, label, description }: {
    value: boolean;
    onChange: (v: boolean) => void;
    label: string;
    description?: string;
  }) => (
    <div className="flex items-start justify-between py-4 border-b border-slate-700">
      <div>
        <p className="text-white font-medium">{label}</p>
        {description && <p className="text-gray-400 text-sm mt-1">{description}</p>}
      </div>
      <button
        onClick={() => onChange(!value)}
        className={`relative w-12 h-6 rounded-full transition-colors ${
          value ? 'bg-brand-deep' : 'bg-slate-600'
        }`}
      >
        <span className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${
          value ? 'translate-x-7' : 'translate-x-1'
        }`} />
      </button>
    </div>
  );

  return (
    <div className="min-h-screen bg-brand-bg">
      <InternalHeader />
      
      <main className="pt-24 pb-16 px-4">
        <div className="max-w-6xl mx-auto">
          {/* Header */}
          <div className="flex items-center gap-4 mb-8">
            <div className="p-3 rounded-xl bg-gradient-to-r from-brand-deep/20 to-brand-secondary/20">
              <Brain className="w-8 h-8 text-brand" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-white">Familiar Memory System</h1>
              <p className="text-gray-400">Configure persistent memory and cross-agent knowledge sharing</p>
            </div>
          </div>

          {/* Tabs */}
          <div className="flex gap-2 mb-8">
            {[
              { id: 'setup', label: 'Setup Wizard', icon: Settings },
              { id: 'docs', label: 'Documentation', icon: BookOpen },
              { id: 'api', label: 'API Reference', icon: Code }
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                  activeTab === tab.id
                    ? 'bg-brand-deep text-white'
                    : 'bg-slate-800 text-gray-400 hover:text-white'
                }`}
              >
                <tab.icon className="w-4 h-4" />
                {tab.label}
              </button>
            ))}
          </div>

          {/* Setup Wizard Tab */}
          {activeTab === 'setup' && (
            <div className="space-y-6">
              {/* Main Enable Toggle */}
              <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className={`p-3 rounded-lg ${config.enabled ? 'bg-brand-deep/20' : 'bg-slate-700'}`}>
                      {config.enabled ? <CheckCircle className="w-6 h-6 text-brand" /> : <XCircle className="w-6 h-6 text-gray-500" />}
                    </div>
                    <div>
                      <h2 className="text-xl font-bold text-white">Memory System</h2>
                      <p className="text-gray-400">Enable persistent memory and institutional knowledge for all {VOCAB.agents}</p>
                    </div>
                  </div>
                  <button
                    onClick={() => setConfig({ ...config, enabled: !config.enabled })}
                    className={`px-6 py-2 rounded-lg font-medium transition-colors ${
                      config.enabled
                        ? 'bg-brand-deep text-white hover:bg-brand-deep'
                        : 'bg-slate-700 text-gray-300 hover:bg-slate-600'
                    }`}
                  >
                    {config.enabled ? 'Enabled' : 'Disabled'}
                  </button>
                </div>
              </div>

              {config.enabled && (
                <>
                  {/* Core Settings */}
                  <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                    <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                      <Database className="w-5 h-5 text-brand" />
                      Core Settings
                    </h3>
                    
                    <div className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-gray-400 text-sm mb-2">Retention Period (days)</label>
                          <input
                            type="number"
                            value={config.retentionDays}
                            onChange={(e) => setConfig({ ...config, retentionDays: parseInt(e.target.value) || 365 })}
                            className="w-full px-4 py-2 rounded-lg bg-slate-800 border border-slate-600 text-white"
                          />
                        </div>
                        <div>
                          <label className="block text-gray-400 text-sm mb-2">Max Memories per Agent</label>
                          <input
                            type="number"
                            value={config.maxMemoriesPerAgent}
                            onChange={(e) => setConfig({ ...config, maxMemoriesPerAgent: parseInt(e.target.value) || 10000 })}
                            className="w-full px-4 py-2 rounded-lg bg-slate-800 border border-slate-600 text-white"
                          />
                        </div>
                      </div>
                      
                      <div>
                        <label className="block text-gray-400 text-sm mb-2">Max Insights per Day</label>
                        <input
                          type="number"
                          value={config.maxInsightsPerDay}
                          onChange={(e) => setConfig({ ...config, maxInsightsPerDay: parseInt(e.target.value) || 100 })}
                          className="w-full px-4 py-2 rounded-lg bg-slate-800 border border-slate-600 text-white"
                        />
                      </div>
                    </div>
                  </div>

                  {/* Agent Features */}
                  <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                    <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                      <Network className="w-5 h-5 text-brand-secondary-light" />
                      Agent Features
                    </h3>
                    
                    <ToggleSwitch
                      value={config.crossAgentSharingEnabled}
                      onChange={(v) => setConfig({ ...config, crossAgentSharingEnabled: v })}
                      label="Cross-Agent Knowledge Sharing"
                      description="Allow agents to share insights and query each other's knowledge"
                    />
                    
                    <ToggleSwitch
                      value={config.llmInsightsEnabled}
                      onChange={(v) => setConfig({ ...config, llmInsightsEnabled: v })}
                      label="LLM-Powered Insights"
                      description="Use AI to generate pattern analysis and recommendations"
                    />
                    
                    <ToggleSwitch
                      value={config.proactiveAlertsEnabled}
                      onChange={(v) => setConfig({ ...config, proactiveAlertsEnabled: v })}
                      label="Proactive Alerts"
                      description="Agents can surface warnings and opportunities automatically"
                    />
                  </div>

                  {/* Security & Privacy */}
                  <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                    <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                      <Shield className="w-5 h-5 text-green-400" />
                      Security & Privacy
                    </h3>
                    
                    <ToggleSwitch
                      value={config.sensitiveDataFiltering}
                      onChange={(v) => setConfig({ ...config, sensitiveDataFiltering: v })}
                      label="Sensitive Data Filtering"
                      description="Automatically redact PII and sensitive information from memories"
                    />
                    
                    <ToggleSwitch
                      value={config.auditLogging}
                      onChange={(v) => setConfig({ ...config, auditLogging: v })}
                      label="Audit Logging"
                      description="Log all memory access and modifications for compliance"
                    />
                    
                    <ToggleSwitch
                      value={config.autoCleanupEnabled}
                      onChange={(v) => setConfig({ ...config, autoCleanupEnabled: v })}
                      label="Auto Cleanup"
                      description="Automatically remove expired memories based on retention policy"
                    />
                  </div>

                  {/* External Access */}
                  <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                    <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                      <Zap className="w-5 h-5 text-yellow-400" />
                      External Access (MCP)
                    </h3>
                    
                    <ToggleSwitch
                      value={config.mcpEndpointEnabled}
                      onChange={(v) => setConfig({ ...config, mcpEndpointEnabled: v })}
                      label="MCP Server Endpoint"
                      description="Allow external AIs (Claude, ChatGPT) to connect and query/write memories"
                    />
                    
                    {config.mcpEndpointEnabled && (
                      <div className="mt-4 p-4 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
                        <div className="flex items-start gap-2">
                          <AlertTriangle className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
                          <div>
                            <p className="text-yellow-400 font-medium">Security Notice</p>
                            <p className="text-gray-400 text-sm mt-1">
                              Set the <code className="bg-slate-800 px-1 rounded">GHOST_MCP_API_KEY</code> environment 
                              variable to require authentication for external connections.
                            </p>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </>
              )}

              {/* Save Button */}
              <div className="flex items-center justify-between">
                {message && (
                  <div className={`flex items-center gap-2 ${
                    message.type === 'success' ? 'text-green-400' : 'text-red-400'
                  }`}>
                    {message.type === 'success' ? <CheckCircle className="w-5 h-5" /> : <XCircle className="w-5 h-5" />}
                    {message.text}
                  </div>
                )}
                <div className="flex gap-3 ml-auto">
                  <button
                    onClick={fetchConfig}
                    className="flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-700 text-white hover:bg-slate-600"
                  >
                    <RefreshCw className="w-4 h-4" />
                    Reset
                  </button>
                  <button
                    onClick={saveConfig}
                    disabled={saving}
                    className="flex items-center gap-2 px-6 py-2 rounded-lg bg-brand-deep text-white hover:bg-brand-deep disabled:opacity-50"
                  >
                    <Save className="w-4 h-4" />
                    {saving ? 'Saving...' : 'Save Configuration'}
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Documentation Tab */}
          {activeTab === 'docs' && (
            <div className="space-y-6">
              <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                <h2 className="text-2xl font-bold text-white mb-4">Familiar Memory System</h2>
                <p className="text-gray-300 leading-relaxed">
                  The Familiar Memory System provides persistent, institutional knowledge for all 13 domain agents 
                  in {BRAND.companyName}. Inspired by the "Open Brain" architecture, this system enables agents to:
                </p>
                
                <div className="grid grid-cols-2 gap-4 mt-6">
                  {[
                    { title: 'Remember Decisions', desc: 'Store and recall past decisions with full context' },
                    { title: 'Share Knowledge', desc: 'Cross-agent knowledge sharing via Ghost Memory' },
                    { title: 'Generate Insights', desc: 'Proactive pattern detection and recommendations' },
                    { title: 'Time-Bridge', desc: 'Surface stale items and forgotten follow-ups' }
                  ].map((item, i) => (
                    <div key={i} className="p-4 rounded-lg bg-slate-800">
                      <h4 className="text-brand font-semibold">{item.title}</h4>
                      <p className="text-gray-400 text-sm mt-1">{item.desc}</p>
                    </div>
                  ))}
                </div>
              </div>

              <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                <h3 className="text-xl font-bold text-white mb-4">Architecture</h3>
                <div className="space-y-4">
                  <div>
                    <h4 className="text-brand font-semibold">Agent-Specific Memory</h4>
                    <p className="text-gray-300">Each agent maintains its own memory store for domain-specific knowledge, 
                    decisions, and observations. Memories are categorized (decision, observation, pattern, etc.) and 
                    ranked by importance and confidence.</p>
                  </div>
                  <div>
                    <h4 className="text-brand-secondary-light font-semibold">Shared Knowledge (Ghost Memory)</h4>
                    <p className="text-gray-300">Cross-agent knowledge that any agent can read or contribute to. 
                    This creates institutional memory that persists across sessions and enables cross-domain reasoning.</p>
                  </div>
                  <div>
                    <h4 className="text-yellow-400 font-semibold">Agent Insights</h4>
                    <p className="text-gray-300">Proactive observations generated by agents — patterns detected, 
                    anomalies flagged, opportunities identified. These surface in the {VOCAB.controlPanel} dashboard for human review.</p>
                  </div>
                  <div>
                    <h4 className="text-green-400 font-semibold">MCP Server</h4>
                    <p className="text-gray-300">Model Context Protocol endpoint that allows external AIs (Claude, ChatGPT) 
                    to connect, query, and write to the memory system. Enables true "Open Brain" architecture.</p>
                  </div>
                </div>
              </div>

              <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                <h3 className="text-xl font-bold text-white mb-4">Setup Guide</h3>
                <ol className="space-y-4 text-gray-300">
                  <li className="flex gap-3">
                    <span className="flex-shrink-0 w-6 h-6 rounded-full bg-brand-deep text-white flex items-center justify-center text-sm">1</span>
                    <div><strong>Enable the Memory System</strong> — Toggle the main switch in the Setup Wizard tab.</div>
                  </li>
                  <li className="flex gap-3">
                    <span className="flex-shrink-0 w-6 h-6 rounded-full bg-brand-deep text-white flex items-center justify-center text-sm">2</span>
                    <div><strong>Configure Retention</strong> — Set how long memories are kept and max limits per agent.</div>
                  </li>
                  <li className="flex gap-3">
                    <span className="flex-shrink-0 w-6 h-6 rounded-full bg-brand-deep text-white flex items-center justify-center text-sm">3</span>
                    <div><strong>Enable Cross-Agent Sharing</strong> — Allow agents to query each other's knowledge.</div>
                  </li>
                  <li className="flex gap-3">
                    <span className="flex-shrink-0 w-6 h-6 rounded-full bg-brand-deep text-white flex items-center justify-center text-sm">4</span>
                    <div><strong>Security Settings</strong> — Enable sensitive data filtering and audit logging for compliance.</div>
                  </li>
                  <li className="flex gap-3">
                    <span className="flex-shrink-0 w-6 h-6 rounded-full bg-brand-deep text-white flex items-center justify-center text-sm">5</span>
                    <div><strong>(Optional) Enable MCP</strong> — For external AI connections, enable MCP and set <code className="bg-slate-800 px-1 rounded">GHOST_MCP_API_KEY</code>.</div>
                  </li>
                </ol>
              </div>
            </div>
          )}

          {/* API Reference Tab */}
          {activeTab === 'api' && (
            <div className="space-y-6">
              <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                <h2 className="text-2xl font-bold text-white mb-4">API Reference</h2>
                <p className="text-gray-300 mb-6">The Familiar Memory System exposes REST APIs and an MCP endpoint for programmatic access.</p>

                {/* REST APIs */}
                <h3 className="text-lg font-semibold text-brand mb-3">REST Endpoints</h3>
                <div className="space-y-4">
                  {[
                    {
                      method: 'GET',
                      path: '/api/gfs/agent-memory',
                      desc: 'Query agent or shared memories',
                      params: 'agentId, category, scope (agent|shared|all), limit, minImportance'
                    },
                    {
                      method: 'POST',
                      path: '/api/gfs/agent-memory',
                      desc: 'Create or update a memory',
                      params: 'agentId, category, key, content, confidence, importance, scope'
                    },
                    {
                      method: 'GET',
                      path: '/api/gfs/agent-memory/insights',
                      desc: 'Query agent insights',
                      params: 'agentId, type, severity, status, limit'
                    },
                    {
                      method: 'POST',
                      path: '/api/gfs/agent-memory/insights',
                      desc: 'Create a new insight',
                      params: 'agentId, type, title, content, severity, confidence, tags'
                    },
                    {
                      method: 'POST',
                      path: '/api/gfs/agent-memory/mcp',
                      desc: 'MCP JSON-RPC endpoint',
                      params: 'JSON-RPC 2.0 request body'
                    }
                  ].map((api, i) => (
                    <div key={i} className="p-4 rounded-lg bg-slate-800">
                      <div className="flex items-center gap-2 mb-2">
                        <span className={`px-2 py-0.5 rounded text-xs font-mono ${
                          api.method === 'GET' ? 'bg-green-500/20 text-green-400' : 'bg-blue-500/20 text-blue-400'
                        }`}>{api.method}</span>
                        <code className="text-gray-300">{api.path}</code>
                      </div>
                      <p className="text-gray-400 text-sm">{api.desc}</p>
                      <p className="text-gray-500 text-xs mt-1">Params: {api.params}</p>
                    </div>
                  ))}
                </div>

                {/* MCP Methods */}
                <h3 className="text-lg font-semibold text-brand-secondary-light mb-3 mt-8">MCP Methods</h3>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    ['mcp.info', 'Server capabilities'],
                    ['memory.query', 'Query memories'],
                    ['memory.write', 'Create/update memory'],
                    ['memory.search', 'Full-text search'],
                    ['memory.stale', 'Find stale items'],
                    ['memory.crossref', 'Find related'],
                    ['memory.stats', 'Memory statistics'],
                    ['insights.query', 'Query insights'],
                    ['insights.create', 'Create insight'],
                    ['agents.list', 'List all agents'],
                    ['agents.query', 'Query agent details']
                  ].map(([method, desc], i) => (
                    <div key={i} className="p-3 rounded-lg bg-slate-800">
                      <code className="text-brand-secondary-light text-sm">{method}</code>
                      <p className="text-gray-500 text-xs mt-1">{desc}</p>
                    </div>
                  ))}
                </div>

                {/* Example */}
                <h3 className="text-lg font-semibold text-yellow-400 mb-3 mt-8">Example MCP Request</h3>
                <pre className="p-4 rounded-lg bg-slate-800 text-gray-300 text-sm overflow-x-auto">
{`POST /api/gfs/agent-memory/mcp
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "memory.query",
  "params": {
    "scope": "all",
    "category": "decision",
    "limit": 10
  }
}`}
                </pre>
              </div>
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  );
}
