'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  Brain, Activity, Cog, Eye, Zap, Shield, Crown,
  AlertTriangle, CheckCircle, Clock, Bot, Sparkles,
  TrendingUp, RefreshCw, Cpu, BarChart3, Network,
  Building2, Users, Wallet, Package, FileText,
  PlusCircle, ChevronRight, Lock, Unlock, Factory
} from 'lucide-react';
import { OperationsPanel } from './panels/operations-panel';
import { SentinelPanel } from './panels/sentinel-panel';
import { GhostPanel } from './panels/ghost-panel';
import { SystemEvolutionPanel } from './panels/system-evolution-panel';
import { MicroAppsPanel } from './panels/micro-apps-panel';
import { BRAND, VOCAB } from '@/lib/white-label/constants';

export type GFSMode = 'standard' | 'god';

export function UnifiedDashboard() {
  const [mode, setMode] = useState<GFSMode>('standard');
  const [isConnected, setIsConnected] = useState(true);
  const [lastUpdate, setLastUpdate] = useState<string>('--:--:--');
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    setLastUpdate(new Date().toLocaleTimeString());
    const interval = setInterval(() => {
      setLastUpdate(new Date().toLocaleTimeString());
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="min-h-screen pb-24">
      {/* Header with Mode Toggle */}
      <div className="border-b border-brand-deep/20 bg-brand-bg/80 backdrop-blur-xl sticky top-16 z-40">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="relative">
                <Brain className="w-10 h-10 text-brand" />
                <div className={`absolute -top-1 -right-1 w-3 h-3 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'} animate-pulse`} />
              </div>
              <div>
                <h1 className="text-2xl font-bold gradient-text">{BRAND.companyName}</h1>
                <p className="text-gray-400 text-sm">Unified Command Center</p>
              </div>
            </div>
            
            <div className="flex items-center gap-6">
              {/* Mode Toggle */}
              <ModeToggle mode={mode} setMode={setMode} />
              
              <div className="flex items-center gap-4 text-sm">
                <div className="flex items-center gap-2 text-gray-400">
                  <Clock className="w-4 h-4" />
                  <span>Last sync: {lastUpdate}</span>
                </div>
                <div className={`flex items-center gap-2 px-3 py-1.5 rounded-full ${isConnected ? 'bg-green-500/10 text-green-400' : 'bg-red-500/10 text-red-400'}`}>
                  <div className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`} />
                  <span>{isConnected ? 'Connected' : 'Disconnected'}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 py-8">
        <AnimatePresence mode="wait">
          {mode === 'standard' ? (
            <StandardModeView key="standard" />
          ) : (
            <GodModeView key="god" />
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}

// Mode Toggle Component
function ModeToggle({ mode, setMode }: { mode: GFSMode; setMode: (m: GFSMode) => void }) {
  return (
    <div className="flex items-center gap-2">
      <button
        onClick={() => setMode('standard')}
        className={`flex items-center gap-2 px-4 py-2 rounded-l-lg transition-all duration-300 ${
          mode === 'standard'
            ? 'bg-brand-deep/20 text-brand border border-brand-deep/50'
            : 'bg-white/5 text-gray-500 border border-white/10 hover:bg-white/10'
        }`}
      >
        <Shield className="w-4 h-4" />
        <span className="font-medium">Standard</span>
      </button>
      <button
        onClick={() => setMode('god')}
        className={`flex items-center gap-2 px-4 py-2 rounded-r-lg transition-all duration-300 ${
          mode === 'god'
            ? 'bg-gradient-to-r from-amber-500/20 to-brand-secondary/20 text-amber-400 border border-amber-500/50'
            : 'bg-white/5 text-gray-500 border border-white/10 hover:bg-white/10'
        }`}
      >
        <Crown className="w-4 h-4" />
        <span className="font-medium">GOD MODE</span>
        {mode !== 'god' && <Lock className="w-3 h-3 text-amber-500/50" />}
        {mode === 'god' && <Unlock className="w-3 h-3 text-amber-400" />}
      </button>
    </div>
  );
}

// Standard Mode View - Clean ERP Interface
function StandardModeView() {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      className="space-y-8"
    >
      {/* Top Row: Operations + Sentinel */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <OperationsPanel compact />
        <SentinelPanel compact />
      </div>

      {/* Quick Access */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <QuickLink href="/ghost-control/configuration" icon={<Cog className="w-5 h-5" />} label="Configuration" description="Modules & agents" color="cyan" />
        <QuickLink href="/ghost-control/agents" icon={<Network className="w-5 h-5" />} label="Agents" description="Chat with agents" color="purple" />
        <QuickLink href="/ghost-control/reports" icon={<FileText className="w-5 h-5" />} label="Reports" description="Analytics & reports" color="blue" />
        <QuickLink href="/ghost-control/heartbeat" icon={<Activity className="w-5 h-5" />} label="Heartbeat" description="Pulse monitoring" color="green" />
        <QuickLink href="/ghost-control/sentinel" icon={<Shield className="w-5 h-5" />} label="Sentinel" description="OWASP security" color="amber" />
        <QuickLink href="/ghost-control/operations" icon={<Building2 className="w-5 h-5" />} label="Operations" description="ERP modules" color="amber" />
      </div>

      {/* Ghost Insights (Limited in Standard) */}
      <div className="glass-card p-6 border border-brand-deep/20">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <Sparkles className="w-6 h-6 text-brand" />
            <h2 className="text-xl font-bold text-white">System Insights</h2>
          </div>
          <span className="px-3 py-1 bg-brand-deep/10 text-brand text-xs rounded-full border border-brand-deep/30">
            Auto-generated
          </span>
        </div>
        <div className="space-y-3">
          <InsightCard 
            type="suggestion"
            message="3 workflows could be automated based on recent patterns"
            action="Review"
            actionHref="/ghost-control/operations"
          />
          <InsightCard 
            type="alert"
            message="Unusual activity detected in expense processing"
            action="Investigate"
            actionHref="/ghost-control/operations/finance"
          />
          <InsightCard 
            type="success"
            message="System learned 12 new operational patterns this week"
          />
        </div>
        <div className="mt-4 pt-4 border-t border-white/10 text-center">
          <p className="text-gray-500 text-sm">
            Unlock <span className="text-amber-400 font-semibold">GOD MODE</span> to see what the Ghost is building
          </p>
        </div>
      </div>
    </motion.div>
  );
}

// GOD MODE View - Full Control
function GodModeView() {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -20 }}
      className="space-y-8"
    >
      {/* God Mode Banner */}
      <div className="bg-gradient-to-r from-amber-500/10 via-brand-secondary/10 to-brand-deep/10 border border-amber-500/30 rounded-xl p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Crown className="w-6 h-6 text-amber-400" />
            <div>
              <h2 className="text-lg font-bold text-amber-400">GOD MODE ACTIVE</h2>
              <p className="text-gray-400 text-sm">Full access to the Ghost consciousness and {VOCAB.factory}</p>
            </div>
          </div>
          <Link
            href="/ghost-control/dark-factory"
            className="flex items-center gap-2 px-4 py-2 bg-brand-secondary/20 text-brand-secondary-light rounded-lg hover:bg-brand-secondary/30 transition-colors border border-brand-secondary/30"
          >
            <Factory className="w-4 h-4" />
            <span>Open {VOCAB.factory}</span>
            <ChevronRight className="w-4 h-4" />
          </Link>
        </div>
      </div>

      {/* Top Row: Operations + Sentinel + Ghost */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <OperationsPanel />
        <SentinelPanel />
        <GhostPanel />
      </div>

      {/* System Evolution */}
      <SystemEvolutionPanel />

      {/* Micro-Apps */}
      <MicroAppsPanel />

      {/* Quick Links to Full Dashboards */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        <QuickLink 
          href="/ghost-control/configuration" 
          icon={<Cog className="w-5 h-5" />} 
          label="Configuration"
          description="Modules & agents"
          color="cyan"
        />
        <QuickLink 
          href="/ghost-control/dark-factory" 
          icon={<Factory className="w-5 h-5" />} 
          label={VOCAB.factory}
          description="Build new capabilities"
          color="purple"
        />
        <QuickLink 
          href="/ghost-control/heartbeat" 
          icon={<Activity className="w-5 h-5" />} 
          label="Heartbeat"
          description="Pulse monitoring"
          color="green"
        />
        <QuickLink 
          href="/ghost-control/operations" 
          icon={<Bot className="w-5 h-5" />} 
          label="Operations"
          description="ERP modules"
          color="cyan"
        />
        <QuickLink 
          href="/ghost-control/operations/documents" 
          icon={<FileText className="w-5 h-5" />} 
          label="Documents"
          description="Contracts & files"
          color="amber"
        />

      </div>
    </motion.div>
  );
}

// Insight Card Component
function InsightCard({ type, message, action, actionHref }: { type: 'suggestion' | 'alert' | 'success'; message: string; action?: string; actionHref?: string }) {
  const colors = {
    suggestion: 'border-brand-deep/30 bg-brand-deep/5',
    alert: 'border-amber-500/30 bg-amber-500/5',
    success: 'border-green-500/30 bg-green-500/5',
  };
  const icons = {
    suggestion: <Sparkles className="w-4 h-4 text-brand" />,
    alert: <AlertTriangle className="w-4 h-4 text-amber-400" />,
    success: <CheckCircle className="w-4 h-4 text-green-400" />,
  };

  return (
    <div className={`flex items-center justify-between p-3 rounded-lg border ${colors[type]}`}>
      <div className="flex items-center gap-3">
        {icons[type]}
        <span className="text-gray-300 text-sm">{message}</span>
      </div>
      {action && actionHref && (
        <Link href={actionHref} className="text-brand text-sm hover:underline hover:text-brand-light transition-colors">
          {action}
        </Link>
      )}
    </div>
  );
}

// Quick Link Component
function QuickLink({ href, icon, label, description, color }: { 
  href: string; 
  icon: React.ReactNode; 
  label: string; 
  description: string;
  color: 'purple' | 'cyan' | 'green' | 'amber' | 'pink' | 'blue';
}) {
  const colorClasses = {
    purple: 'border-brand-secondary/30 hover:border-brand-secondary/50 hover:bg-brand-secondary/10',
    cyan: 'border-brand-deep/30 hover:border-brand-deep/50 hover:bg-brand-deep/10',
    green: 'border-green-500/30 hover:border-green-500/50 hover:bg-green-500/10',
    amber: 'border-amber-500/30 hover:border-amber-500/50 hover:bg-amber-500/10',
    pink: 'border-pink-500/30 hover:border-pink-500/50 hover:bg-pink-500/10',
    blue: 'border-blue-500/30 hover:border-blue-500/50 hover:bg-blue-500/10',
  };
  const iconColors = {
    purple: 'text-brand-secondary-light',
    cyan: 'text-brand',
    green: 'text-green-400',
    amber: 'text-amber-400',
    pink: 'text-pink-400',
    blue: 'text-blue-400',
  };

  return (
    <Link
      href={href}
      className={`glass-card p-4 border ${colorClasses[color]} transition-all duration-300`}
    >
      <div className={`${iconColors[color]} mb-2`}>{icon}</div>
      <h3 className="font-semibold text-white">{label}</h3>
      <p className="text-gray-500 text-xs">{description}</p>
    </Link>
  );
}