"use client";

import React, { useState, useEffect } from 'react';
import { Sidebar } from '@/components/ui/sidebar';
import DocumentsSection from '@/components/documents/DocumentsSection';
import SearchSection from '@/components/search/SearchSection';
import ChatSection from '@/components/chat/ChatSection';
import AgentChatSection from '@/components/chat/AgentChatSection';
import GraphSection from '@/components/GraphSection';
import { AlertSystem } from '@/components/ui/alert-system';
import { extractTokenFromUri, getApiBaseUrlFromUri } from '@/lib/utils';
import { MorphikUIProps } from '@/components/types';

// Default API base URL
const DEFAULT_API_BASE_URL = 'http://localhost:8000';

const MorphikUI: React.FC<MorphikUIProps> = ({
  connectionUri,
  apiBaseUrl = DEFAULT_API_BASE_URL,
  isReadOnlyUri = false, // Default to editable URI
  onUriChange,
  onBackClick,
  initialFolder = null,
  initialSection = 'documents'
}) => {
  // State to manage connectionUri internally if needed
  const [currentUri, setCurrentUri] = useState(connectionUri);

  // Update internal state when prop changes
  useEffect(() => {
    setCurrentUri(connectionUri);
  }, [connectionUri]);

  // Handle URI changes from sidebar
  const handleUriChange = (newUri: string) => {
    console.log('MorphikUI: URI changed to:', newUri);
    setCurrentUri(newUri);
    if (onUriChange) {
      onUriChange(newUri);
    }
  };
  const [activeSection, setActiveSection] = useState(initialSection);
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);

  // Extract auth token and API URL from connection URI if provided
  const authToken = currentUri ? extractTokenFromUri(currentUri) : null;

  // Derive API base URL from the URI if provided
  // If URI is empty, this will now connect to localhost by default
  const effectiveApiBaseUrl = getApiBaseUrlFromUri(currentUri, apiBaseUrl);

  // Log the effective API URL for debugging
  useEffect(() => {
    console.log('MorphikUI: Using API URL:', effectiveApiBaseUrl);
    console.log('MorphikUI: Auth token present:', !!authToken);
  }, [effectiveApiBaseUrl, authToken]);

  return (
    <>
      <div className="flex h-full">
        <Sidebar
          activeSection={activeSection}
          onSectionChange={setActiveSection}
          className="h-full"
          connectionUri={currentUri}
          isReadOnlyUri={isReadOnlyUri}
          onUriChange={handleUriChange}
          isCollapsed={isSidebarCollapsed}
          setIsCollapsed={setIsSidebarCollapsed}
          onBackClick={onBackClick}
        />

        <div className="flex-1 flex flex-col h-full overflow-hidden">
          {/* Remove the header with back button */}
          <div className="flex-1 overflow-y-auto">
            {/* Documents Section */}
            {activeSection === 'documents' && (
              <DocumentsSection
                apiBaseUrl={effectiveApiBaseUrl}
                authToken={authToken}
                initialFolder={initialFolder}
                setSidebarCollapsed={setIsSidebarCollapsed}
              />
            )}

            {/* Search Section */}
            {activeSection === 'search' && (
              <SearchSection
                apiBaseUrl={effectiveApiBaseUrl}
                authToken={authToken}
              />
            )}

            {/* Chat Section */}
            {activeSection === 'chat' && (
              <ChatSection
                apiBaseUrl={effectiveApiBaseUrl}
                authToken={authToken}
              />
            )}

            {/* Agent Chat Section */}
            {activeSection === 'agent' && (
              <AgentChatSection
                apiBaseUrl={effectiveApiBaseUrl}
                authToken={authToken}
              />
            )}

            {/* Graphs Section */}
            {activeSection === 'graphs' && (
              <div className="space-y-4">
                <GraphSection
                  apiBaseUrl={effectiveApiBaseUrl}
                  authToken={authToken}
                />
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Global alert system - integrated directly in the component */}
      <AlertSystem position="bottom-right" />
    </>
  );
};

export default MorphikUI;
