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';

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

// API 모드
const APIMode = ({ isApiMode, onToggleMode }) => {
  const [apiRequests, setApiRequests] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const {
    collections,
    loadCollections,
    loading,
    error
  } = 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 || ''
    };

    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>No APIs opened. Select an API to test from the sidebar.</p>
      </div>
  );

  return (
      <div className="api-mode flex h-full w-full">
        <div className="navigation w-[250px] flex-shrink-0 border-r bg-background">
          {/* APINavigation 고정 */}
          <APINavigation
              contextPath="/"
              collections={collections} // Pass collections to APINavigation
              side="left"
              onApiSelect={handleOpenApi}
              onNewCollection={() => {
                // Handle new collection creation
              }}
              isApiMode={isApiMode}
              onToggleMode={onToggleMode}
          />
        </div>
        <div className="flex-1 h-full w-full min-w-0 overflow-hidden">
          {apiRequests.length === 0 ? (
              renderFallback() // Render fallback when no tabs exist
          ) : (
              <APITabs
                  apiRequests={apiRequests}
                  currentIndex={currentIndex}
                  onTabChange={handleTabChange}
                  onCloseTab={handleCloseTab}
              />
          )}
        </div>
      </div>
  );
};

// 시나리오 모드
const ScenarioMode = ({ isApiMode, onToggleMode }) => (
    <div className="scenario-mode flex flex-1 h-[calc(100vh-57px)]">
      {/* 왼쪽 고정: ScenarioNavigation */}
      <div className="navigation-sidebar min-w-[200px] border-r bg-gray-100">
        <ScenarioNavigation
            contextPath="/"
            side="left"
            isApiMode={isApiMode}
            onToggleMode={onToggleMode}
        />
      </div>

      {/* 중앙: ScenarioEditor */}
      <div className="editor flex-1 h-[calc(100vh-57px)] overflow-hidden">
        <ScenarioEditor/>
      </div>

      {/* 오른쪽 고정: APINavigation */}
      <div className="navigation-sidebar min-w-[200px] border-l bg-gray-100">
        <APINavigation contextPath="/"
                       side="right"
                       onApiSelect={(collectionId, apiId) => {
                         // Handle API selection
                       }}
                       onNewCollection={() => {
                         // Handle new collection creation
                       }}
                       isApiMode={isApiMode}
                       onToggleMode={onToggleMode}
        />

      </div>
    </div>
);


export default MainContentArea;
