import React, { useState, useEffect, useRef } from 'react';
import { Zap, Brain, Settings, Moon, ChevronRight, Send, Bot, Server, Sparkles, Circle, User, AlertCircle } from 'lucide-react';
import { createClient } from '@supabase/supabase-js';
import ChatInterface from './components/ChatInterface';
import VisualizationPanel from './components/VisualizationPanel';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import CognitionCocooner from './services/CognitionCocooner';
import AICore from './services/AICore';
import { CodetteResponse } from './components/CodetteComponents';

interface Message {
  role: string;
  content: string;
  timestamp: Date;
  metadata?: CodetteResponse;
}

// Initialize Supabase client
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY;

if (!supabaseUrl || !supabaseKey) {
  throw new Error('Missing Supabase environment variables');
}

const supabase = createClient(supabaseUrl, supabaseKey);

const App: React.FC = () => {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [darkMode, setDarkMode] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [aiState, setAiState] = useState({
    quantumState: [0.3, 0.7, 0.5],
    chaosState: [0.2, 0.8, 0.4, 0.6],
    activePerspectives: ['newton', 'davinci', 'neural_network', 'philosophical'],
    ethicalScore: 0.93,
    processingPower: 0.72
  });
  const [cocoons, setCocoons] = useState<Array<{id: string, type: string, wrapped: any}>>([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);
  
  const aiCore = useRef<AICore | null>(null);
  const cocooner = useRef(new CognitionCocooner());

  useEffect(() => {
    try {
      aiCore.current = new AICore();
      setError(null);
    } catch (err: any) {
      console.error('Error initializing AI Core:', err);
      setError(err.message);
    }
  }, []);

  useEffect(() => {
    // Check if user is already authenticated
    const checkAuth = async () => {
      try {
        const { data: { session }, error } = await supabase.auth.getSession();
        
        if (error) {
          console.error('Auth check error:', error.message);
          return;
        }

        if (session?.user) {
          setCurrentUserId(session.user.id);
          const { data: { role } } = await supabase.rpc('get_user_role');
          setIsAdmin(role === 'admin');
        }
      } catch (error: any) {
        console.error('Auth check error:', error.message);
      }
    };

    checkAuth();
  }, []);
  
  useEffect(() => {
    if (!error) {
      setMessages([
        {
          role: 'assistant',
          content: 'Hello! I am Codette, an advanced AI assistant with recursive reasoning, self-learning capabilities, and multi-agent intelligence. How can I assist you today?',
          timestamp: new Date(),
          metadata: {
            text: 'Hello! I am Codette, an advanced AI assistant with recursive reasoning, self-learning capabilities, and multi-agent intelligence. How can I assist you today?',
            instabilityFlag: false,
            perspectivesUsed: ['greeting', 'introduction'],
            cocoonLog: ['Initializing Codette AI...', 'Quantum state stabilized'],
            forceRefresh: () => handleForceRefresh('Hello! I am Codette, an advanced AI assistant with recursive reasoning, self-learning capabilities, and multi-agent intelligence. How can I assist you today?')
          }
        }
      ]);
    }
  }, [error]);
  
  const handleForceRefresh = async (content: string) => {
    if (!aiCore.current) return;
    
    setIsProcessing(true);
    try {
      const response = await aiCore.current.processInput(content, true, currentUserId || undefined);
      
      const assistantMessage: Message = {
        role: 'assistant',
        content: response,
        timestamp: new Date(),
        metadata: {
          text: response,
          instabilityFlag: Math.random() > 0.8,
          perspectivesUsed: aiState.activePerspectives.slice(0, 3),
          cocoonLog: [`Regenerating response for: ${content}`, `Generated new response at ${new Date().toISOString()}`],
          forceRefresh: () => handleForceRefresh(content)
        }
      };
      
      setMessages(prev => [...prev.slice(0, -1), assistantMessage]);
    } catch (error) {
      console.error('Error regenerating response:', error);
    } finally {
      setIsProcessing(false);
    }
  };
  
  const toggleSidebar = () => {
    setSidebarOpen(!sidebarOpen);
  };
  
  const toggleDarkMode = () => {
    setDarkMode(!darkMode);
    document.documentElement.classList.toggle('dark');
  };
  
  const sendMessage = async (content: string) => {
    if (!aiCore.current) {
      setError('AI Core is not initialized. Please check your configuration.');
      return;
    }

    const userMessage: Message = {
      role: 'user',
      content,
      timestamp: new Date()
    };
    
    setMessages(prev => [...prev, userMessage]);
    setIsProcessing(true);
    
    try {
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      const thought = { query: content, timestamp: new Date() };
      const cocoonId = cocooner.current.wrap(thought);
      setCocoons(prev => [...prev, { 
        id: cocoonId, 
        type: 'prompt', 
        wrapped: thought 
      }]);
      
      const response = await aiCore.current.processInput(content, false, currentUserId || undefined);
      
      setAiState(prev => ({
        ...prev,
        quantumState: [Math.random(), Math.random(), Math.random()].map(v => v.toFixed(2)).map(Number),
        chaosState: [Math.random(), Math.random(), Math.random(), Math.random()].map(v => v.toFixed(2)).map(Number),
        ethicalScore: Number((prev.ethicalScore + Math.random() * 0.1 - 0.05).toFixed(2)),
        processingPower: Number((prev.processingPower + Math.random() * 0.1 - 0.05).toFixed(2))
      }));
      
      const assistantMessage: Message = {
        role: 'assistant',
        content: response,
        timestamp: new Date(),
        metadata: {
          text: response,
          instabilityFlag: Math.random() > 0.8,
          perspectivesUsed: aiState.activePerspectives.slice(0, 3),
          cocoonLog: [`Processing query: ${content}`, `Generated response at ${new Date().toISOString()}`],
          forceRefresh: () => handleForceRefresh(content)
        }
      };
      
      setMessages(prev => [...prev, assistantMessage]);
    } catch (error: any) {
      console.error('Error processing message:', error);
      
      setMessages(prev => [...prev, {
        role: 'system',
        content: 'An error occurred while processing your request. Please check your configuration and try again.',
        timestamp: new Date()
      }]);
    } finally {
      setIsProcessing(false);
    }
  };
  
  if (error) {
    return (
      <div className={`min-h-screen flex items-center justify-center p-4 ${darkMode ? 'dark bg-gray-900 text-white' : 'bg-gray-50 text-gray-900'}`}>
        <div className={`max-w-md w-full p-6 rounded-lg shadow-lg ${darkMode ? 'bg-gray-800' : 'bg-white'}`}>
          <div className="flex items-center justify-center mb-4">
            <AlertCircle className="text-red-500" size={48} />
          </div>
          <h1 className="text-xl font-bold text-center mb-4">Configuration Error</h1>
          <p className="text-center mb-6">{error}</p>
          <div className={`p-4 rounded-md ${darkMode ? 'bg-gray-700' : 'bg-gray-100'}`}>
            <p className="text-sm">
              Please ensure you have:
              <ol className="list-decimal ml-5 mt-2 space-y-1">
                <li>Created a .env file</li>
                <li>Added your OpenAI API key to the .env file</li>
                <li>Added your Supabase configuration</li>
              </ol>
            </p>
          </div>
        </div>
      </div>
    );
  }
  
  return (
    <div className={`flex flex-col h-screen transition-colors duration-300 ${darkMode ? 'dark bg-gray-900 text-white' : 'bg-gray-50 text-gray-900'}`}>
      <Header 
        toggleSidebar={toggleSidebar}
        toggleDarkMode={toggleDarkMode} 
        darkMode={darkMode} 
        aiState={aiState}
      />
      
      <div className="flex flex-1 overflow-hidden">
        <Sidebar 
          isOpen={sidebarOpen} 
          cocoons={cocoons} 
          aiState={aiState}
          darkMode={darkMode}
          supabase={supabase}
          isAdmin={isAdmin}
          setIsAdmin={setIsAdmin}
        />
        
        <main className="flex-1 flex flex-col md:flex-row overflow-hidden">
          <ChatInterface 
            messages={messages} 
            sendMessage={sendMessage} 
            isProcessing={isProcessing}
            darkMode={darkMode}
          />
          
          <VisualizationPanel 
            aiState={aiState} 
            darkMode={darkMode}
          />
        </main>
      </div>
    </div>
  );
};

export default App;