import { useState, useRef, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { 
  FaRobot, FaBrain, FaCode, FaDatabase, FaCloud, FaShieldAlt, 
  FaChartLine, FaProjectDiagram, FaBug, FaFileCode, FaGitAlt,
  FaDocker, FaServer, FaMobile, FaPalette, FaGlobe, FaLock,
  FaNetworkWired, FaMemory, FaMicrochip, FaCogs, FaRocket,
  FaTerminal, FaBook, FaGraduationCap, FaLightbulb, FaMagic,
  FaTools, FaRegClock, FaSearch, FaFilter, FaDownload, FaUpload,
  FaSave, FaTrash, FaEdit, FaCopy, FaPaste, FaUndo, FaRedo,
  FaPlay, FaStop, FaPause, FaStepForward, FaStepBackward,
  FaExpand, FaCompress, FaFullscreen, FaRegWindowMaximize,
  FaRegWindowMinimize, FaWindowClose, FaRegWindowRestore,
  FaDesktop, FaLaptop, FaTablet, FaMobileAlt, FaTv,
  FaGamepad, FaHeadphones, FaMicrophone, FaVideo, FaCamera,
  FaImage, FaFilm, FaMusic, FaPodcast, FaBroadcastTower,
  FaSatellite, FaWifi, FaEthernet, FaUsb, FaBluetooth,
  FaSimCard, FaSdCard, FaHdd, FaCompactDisc, FaPrint,
  FaScanner, FaKeyboard, FaMouse, FaGamepadAlt, FaJoystick,
  FaVrCardboard, FaGlasses, FaWatch, FaClock, FaStopwatch
} from 'react-icons/fa'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { vscDarkPlus } from 'react-syntax-highlighter/dist/cjs/styles/prism'
import toast from 'react-hot-toast'

export default function AIAgent({ language, theme }) {
  const [activeModel, setActiveModel] = useState('code-assistant')
  const [messages, setMessages] = useState([])
  const [input, setInput] = useState('')
  const [isProcessing, setIsProcessing] = useState(false)
  const [selectedCapability, setSelectedCapability] = useState('code-generation')
  const [context, setContext] = useState({})
  const [models] = useState([
    { id: 'code-assistant', name: 'Code Assistant', icon: FaCode, description: 'Full-stack programming assistant' },
    { id: 'database-expert', name: 'Database Expert', icon: FaDatabase, description: 'Database design and optimization' },
    { id: 'cloud-architect', name: 'Cloud Architect', icon: FaCloud, description: 'Cloud infrastructure and deployment' },
    { id: 'security-specialist', name: 'Security Specialist', icon: FaShieldAlt, description: 'Security analysis and protection' },
    { id: 'performance-analyst', name: 'Performance Analyst', icon: FaChartLine, description: 'Performance optimization' },
    { id: 'project-manager', name: 'Project Manager', icon: FaProjectDiagram, description: 'Project planning and management' },
    { id: 'debugger', name: 'Bug Hunter', icon: FaBug, description: 'Debug and fix issues' },
    { id: 'documentation', name: 'Documentation', icon: FaBook, description: 'Generate documentation' },
    { id: 'testing', name: 'Testing Expert', icon: FaVrCardboard, description: 'Automated testing' },
    { id: 'deployment', name: 'Deployment', icon: FaRocket, description: 'CI/CD and deployment' }
  ])

  const capabilities = [
    { id: 'code-generation', name: 'Code Generation', icon: FaCode },
    { id: 'code-review', name: 'Code Review', icon: FaSearch },
    { id: 'refactoring', name: 'Refactoring', icon: FaEdit },
    { id: 'optimization', name: 'Optimization', icon: FaRocket },
    { id: 'debugging', name: 'Debugging', icon: FaBug },
    { id: 'testing', name: 'Testing', icon: FaFlask },
    { id: 'documentation', name: 'Documentation', icon: FaBook },
    { id: 'architecture', name: 'Architecture', icon: FaProjectDiagram },
    { id: 'security', name: 'Security', icon: FaShieldAlt },
    { id: 'performance', name: 'Performance', icon: FaChartLine },
    { id: 'database', name: 'Database', icon: FaDatabase },
    { id: 'api', name: 'API Design', icon: FaNetworkWired },
    { id: 'ui-ux', name: 'UI/UX', icon: FaPalette },
    { id: 'mobile', name: 'Mobile Dev', icon: FaMobile },
    { id: 'web', name: 'Web Dev', icon: FaGlobe },
    { id: 'devops', name: 'DevOps', icon: FaServer },
    { id: 'ml', name: 'Machine Learning', icon: FaBrain },
    { id: 'blockchain', name: 'Blockchain', icon: FaLink },
    { id: 'iot', name: 'IoT', icon: FaWifi },
    { id: 'gaming', name: 'Game Dev', icon: FaGamepad }
  ]

  const handleSendMessage = async () => {
    if (!input.trim()) return

    const userMessage = {
      id: Date.now(),
      type: 'user',
      content: input,
      capability: selectedCapability,
      model: activeModel,
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    setInput('')
    setIsProcessing(true)

    try {
      // Simulate AI processing
      await new Promise(resolve => setTimeout(resolve, 2000))

      const aiResponse = await generateAIResponse(input, selectedCapability, activeModel)
      
      const assistantMessage = {
        id: Date.now() + 1,
        type: 'assistant',
        content: aiResponse,
        capability: selectedCapability,
        model: activeModel,
        timestamp: new Date()
      }

      setMessages(prev => [...prev, assistantMessage])
    } catch (error) {
      toast.error(language === 'fa' ? 'خطا در پردازش درخواست' : 'Error processing request')
    } finally {
      setIsProcessing(false)
    }
  }

  const generateAIResponse = async (prompt, capability, model) => {
    const responses = {
      'code-generation': `// Generated code for: ${prompt}\nfunction generateSolution() {\n  // AI-generated implementation\n  return "Solution generated by ${model}";\n}`,
      'code-review': `Code Review Results:\n✓ Code follows best practices\n✓ No security vulnerabilities detected\n⚠ Consider optimizing performance\n✓ Documentation is complete`,
      'refactoring': `Refactored Code:\n// Improved version with better structure\nclass RefactoredSolution {\n  constructor() {\n    this.optimized = true;\n  }\n}`,
      'debugging': `Debug Analysis:\n🐛 Issue identified in line 42\n🔧 Suggested fix: Initialize variable before use\n✅ Solution implemented successfully`,
      'testing': `Test Coverage Report:\n✓ Unit tests: 95%\n✓ Integration tests: 88%\n✓ E2E tests: 92%\n📊 Overall coverage: 92%`,
      'documentation': `Generated Documentation:\n# API Documentation\n\n## Overview\nThis module provides...\n\n## Installation\n\`\`\`bash\nnpm install package\n\`\`\`\n\n## Usage\n\`\`\`javascript\nimport { module } from 'package';\n\`\`\``,
      'architecture': `Architecture Recommendation:\n🏗️ Pattern: Microservices\n📊 Scalability: High\n🔒 Security: Enterprise grade\n⚡ Performance: Optimized`,
      'security': `Security Analysis:\n🔒 SSL/TLS: Configured\n🛡️ Firewall: Active\n🔐 Authentication: OAuth 2.0\n✅ No vulnerabilities found`,
      'performance': `Performance Metrics:\n⚡ Response time: 45ms\n💾 Memory usage: 128MB\n📈 Throughput: 1000 req/s\n🎯 Score: 95/100`,
      'database': `Database Schema:\n📊 Tables: Optimized\n🔍 Indexes: Properly configured\n⚡ Queries: Optimized\n💾 Storage: Efficient`,
      'api': `API Design:\n🌐 RESTful: Yes\n📝 Documentation: Complete\n🔒 Security: JWT auth\n⚡ Performance: High`,
      'ui-ux': `UI/UX Recommendations:\n🎨 Design: Modern\n📱 Responsive: Yes\n♿ Accessible: WCAG 2.1\n⚡ Performance: Optimized`,
      'mobile': `Mobile Solution:\n📱 Platform: Cross-platform\n⚡ Performance: Native-like\n🔋 Battery: Optimized\n📦 Size: Minimal`,
      'web': `Web Solution:\n🌐 Framework: Next.js\n⚡ Performance: Optimized\n🔒 Security: HTTPS\n📱 Responsive: Yes`,
      'devops': `DevOps Pipeline:\n🚀 CI/CD: Automated\n🐳 Docker: Containerized\n☁️ Cloud: AWS\n📊 Monitoring: Enabled`,
      'ml': `ML Solution:\n🧠 Model: Neural Network\n📊 Accuracy: 98%\n⚡ Training: Optimized\n🔮 Prediction: Real-time`,
      'blockchain': `Blockchain Solution:\n⛓️ Network: Ethereum\n🔐 Smart Contract: Audited\n⚡ Gas: Optimized\n🔒 Security: High`,
      'iot': `IoT Solution:\n📡 Devices: Connected\n🔌 Protocol: MQTT\n⚡ Real-time: Yes\n🔒 Security: Encrypted`,
      'gaming': `Game Development:\n🎮 Engine: Unity\n⚡ Performance: 60 FPS\n🎨 Graphics: 4K\n🎯 Gameplay: Smooth`
    }

    return responses[capability] || `AI Response from ${model} for: ${prompt}`
  }

  const exportConversation = () => {
    const data = JSON.stringify(messages, null, 2)
    const blob = new Blob([data], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'ai-conversation.json'
    a.click()
    toast.success(language === 'fa' ? 'گفتگو export شد' : 'Conversation exported')
  }

  const clearConversation = () => {
    setMessages([])
    toast.success(language === 'fa' ? 'گفتگو پاک شد' : 'Conversation cleared')
  }

  return (
    <div className="flex flex-col h-full space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between p-4 bg-gray-800 rounded-lg">
        <div className="flex items-center space-x-reverse space-x-3">
          <FaRobot className="w-6 h-6 text-primary-400" />
          <h2 className="text-lg font-semibold">AI Agent Studio</h2>
        </div>
        <div className="flex items-center space-x-reverse space-x-2">
          <button
            onClick={exportConversation}
            className="px-3 py-1 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-all text-sm"
          >
            <FaDownload className="w-4 h-4 inline ml-2" />
            {language === 'fa' ? 'export' : 'Export'}
          </button>
          <button
            onClick={clearConversation}
            className="px-3 py-1 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-all text-sm"
          >
            <FaTrash className="w-4 h-4 inline ml-2" />
            {language === 'fa' ? 'پاک کردن' : 'Clear'}
          </button>
        </div>
      </div>

      <div className="flex-1 flex space-x-reverse space-x-4 min-h-0">
        {/* Sidebar */}
        <div className="w-80 bg-gray-800 rounded-lg p-4 space-y-4 overflow-y-auto">
          {/* Models */}
          <div>
            <h3 className="text-sm font-medium mb-3">AI Models</h3>
            <div className="space-y-2">
              {models.map(model => {
                const Icon = model.icon
                return (
                  <button
                    key={model.id}
                    onClick={() => setActiveModel(model.id)}
                    className={`w-full p-3 rounded-lg transition-all text-left ${
                      activeModel === model.id
                        ? 'bg-primary-600 text-white'
                        : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                    }`}
                  >
                    <div className="flex items-center space-x-reverse space-x-2">
                      <Icon className="w-4 h-4" />
                      <div>
                        <div className="text-sm font-medium">{model.name}</div>
                        <div className="text-xs opacity-75">{model.description}</div>
                      </div>
                    </div>
                  </button>
                )
              })}
            </div>
          </div>

          {/* Capabilities */}
          <div>
            <h3 className="text-sm font-medium mb-3">Capabilities</h3>
            <div className="grid grid-cols-2 gap-2">
              {capabilities.map(cap => {
                const Icon = cap.icon
                return (
                  <button
                    key={cap.id}
                    onClick={() => setSelectedCapability(cap.id)}
                    className={`p-2 rounded-lg transition-all flex flex-col items-center justify-center ${
                      selectedCapability === cap.id
                        ? 'bg-primary-600 text-white'
                        : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                    }`}
                  >
                    <Icon className="w-4 h-4 mb-1" />
                    <span className="text-xs">{cap.name}</span>
                  </button>
                )
              })}
            </div>
          </div>
        </div>

        {/* Chat Area */}
        <div className="flex-1 bg-gray-800 rounded-lg flex flex-col">
          <div className="flex-1 p-4 overflow-y-auto space-y-4">
            <AnimatePresence>
              {messages.map(message => (
                <motion.div
                  key={message.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className={`flex ${message.type === 'user' ? 'justify-start' : 'justify-end'}`}
                >
                  <div className={`max-w-lg p-4 rounded-lg ${
                    message.type === 'user'
                      ? 'bg-gray-700 text-white'
                      : 'bg-primary-600 text-white'
                  }`}>
                    <div className="flex items-center space-x-reverse space-x-2 mb-2">
                      {message.type === 'user' ? (
                        <FaUser className="w-4 h-4" />
                      ) : (
                        <FaRobot className="w-4 h-4" />
                      )}
                      <span className="text-xs opacity-75">
                        {message.model} • {message.capability}
                      </span>
                    </div>
                    {message.content.includes('```') ? (
                      <SyntaxHighlighter
                        language="javascript"
                        style={vscDarkPlus}
                        className="rounded"
                      >
                        {message.content}
                      </SyntaxHighlighter>
                    ) : (
                      <div className="whitespace-pre-wrap text-sm">
                        {message.content}
                      </div>
                    )}
                  </div>
                </motion.div>
              ))}
            </AnimatePresence>

            {isProcessing && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="flex justify-end"
              >
                <div className="bg-primary-600 p-4 rounded-lg">
                  <div className="flex space-x-reverse space-x-1">
                    <div className="w-2 h-2 bg-white rounded-full animate-bounce" />
                    <div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                    <div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                  </div>
                </div>
              </motion.div>
            )}
          </div>

          {/* Input */}
          <div className="p-4 border-t border-gray-700">
            <div className="flex space-x-reverse space-x-2">
              <input
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
                placeholder="Ask AI anything..."
                className="flex-1 px-4 py-2 bg-gray-700 text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                disabled={isProcessing}
              />
              <button
                onClick={handleSendMessage}
                disabled={!input.trim() || isProcessing}
                className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 transition-all"
              >
                <FaPaperPlane className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}