import React, {useEffect, useState} from 'react';
import APINavigation from '@/components/api-tester/APINavigation';
import APITabs from '@/components/api-tester/APITabs';
import {useAPI} from '@/providers/APIProvider.jsx';
import ScenarioNavigation from '@/components/api-tester/ScenarioNavigation.jsx';
import ScenarioEditor from '@/components/api-tester/ScenarioEditor.jsx';
import {SidebarProvider} from '@/components/ui/sidebar.jsx';

const MainContentArea = ({isApiMode, toggleMode}) => {
  // Lift tab state up
  const [apiRequests, setApiRequests] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === 'm' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        toggleMode();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [toggleMode]);

  return (
      <div className="h-[calc(100vh-57px)] w-full overflow-hidden">
        {isApiMode ? (
            <APIMode
                isApiMode={isApiMode}
                onToggleMode={toggleMode}
                apiRequests={apiRequests}
                setApiRequests={setApiRequests}
                currentIndex={currentIndex}
                setCurrentIndex={setCurrentIndex}
            />
        ) : (
            <ScenarioMode
                isApiMode={isApiMode}
                onToggleMode={toggleMode}
                apiRequests={apiRequests}
                setApiRequests={setApiRequests}
                currentIndex={currentIndex}
                setCurrentIndex={setCurrentIndex}
            />
        )}
      </div>
  );
};

// API 모드
const APIMode = ({
  isApiMode,
  onToggleMode,
  apiRequests,
  setApiRequests,
  currentIndex,
  setCurrentIndex
}) => {
  const {collections, loadCollections} = useAPI();

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

  const handleTabChange = (value) => {
    setCurrentIndex(Number(value));
  };

  const handleCloseTab = (index) => {
    const updatedRequests = [...apiRequests];
    updatedRequests.splice(index, 1);
    setApiRequests(updatedRequests);

    if (currentIndex >= updatedRequests.length) {
      setCurrentIndex(Math.max(0, updatedRequests.length - 1));
    }
  };

  const handleOpenApi = (collectionId, apiId) => {
    const collection = collections.find((col) => col.id === collectionId);
    if (!collection) {
      console.error(`Collection with id "${collectionId}" not found`);
      return;
    }

    const api = collection.apis?.find((api) => api.id === apiId);
    if (!api) {
      console.error(`API with id "${apiId}" not found in collection "${collectionId}"`);
      return;
    }

    const newApiRequest = {
      id: api.id,
      name: api.name,
      type: api.type || 'HTTP',
      method: api.method || 'GET',
      path: api.path || '',
      headers: api.headers || [],
      queryParams: api.queryParams || [],
      contentType: api.contentType || 'application/json',
      requestBody: api.requestBody || '',
      preRequestScript: api.preRequestScript || '',
      postRequestScript: api.postRequestScript || '',
      collectionId: collectionId,
      collectionName: collection.name,
      server: api.server || null,
      description: api.description || '',
      layout: api.layout || {}
    };

    const existingIndex = apiRequests.findIndex(
        (request) => request.id === apiId && request.collectionId === collectionId
    );

    if (existingIndex === -1) {
      setApiRequests((prevRequests) => [...prevRequests, newApiRequest]);
      setCurrentIndex(apiRequests.length);
    } else {
      const updatedRequests = [...apiRequests];
      updatedRequests[existingIndex] = newApiRequest;
      setApiRequests(updatedRequests);
      setCurrentIndex(existingIndex);
    }
  };

  const renderFallback = () => (
      <div className="flex h-full w-full items-center justify-center text-muted-foreground">
        <p>왼쪽에서 API를 선택해 주세요</p>
      </div>
  );

  return (
      <SidebarProvider cookieName="sidebar-right:state" shortcut="/">
        <div className="api-mode flex flex-1 h-[calc(100vh-57px)]">
          <div className="navigation-sidebar min-w-[0px] border-r bg-gray-100">
            <APINavigation
                contextPath="/"
                collections={collections} // Pass collections to APINavigation
                side="left"
                onApiSelect={handleOpenApi}
                onNewCollection={() => {
                  // Handle new collection creation
                }}
                isApiMode={isApiMode}
                onToggleMode={onToggleMode}
            />
          </div>
          <div className="editor flex-1 h-[calc(100vh-57px)] overflow-hidden">
            {apiRequests.length === 0 ? (
                renderFallback() // Render fallback when no tabs exist
            ) : (
                <APITabs
                    apiRequests={apiRequests}
                    currentIndex={currentIndex}
                    onTabChange={handleTabChange}
                    onCloseTab={handleCloseTab}
                />
            )}
          </div>
        </div>
      </SidebarProvider>
  );
};

// 시나리오 모드
const ScenarioMode = ({
  isApiMode,
  onToggleMode
}) => {

  let handleApiSelect = () => {
  };
  return (
    <div className="scenario-mode flex flex-1 h-[calc(100vh-57px)]">
      <SidebarProvider cookieName="sidebar-left:state" shortcut=".">
        <div className="navigation-sidebar min-w-[0px] border-r bg-gray-100">
            <ScenarioNavigation
                contextPath="/"
                side="left"
                isApiMode={isApiMode}
                onToggleMode={onToggleMode}
            />
        </div>
        <div className="editor flex-1 h-[calc(100vh-57px)] overflow-hidden">
          <ScenarioEditor/>
        </div>
      </SidebarProvider>
      <div className="navigation-sidebar min-w-[0px] border-l bg-gray-100">
        <SidebarProvider cookieName="sidebar-right:state" shortcut="/">
          <APINavigation
              contextPath="/"
              side="right"
              onApiSelect={handleApiSelect}
              isApiMode={isApiMode}
              onToggleMode={onToggleMode}
          />
        </SidebarProvider>
      </div>
    </div>
  );
};

export default MainContentArea;
