import React, {useState} from 'react';
import {Menubar, MenubarContent, MenubarItem, MenubarMenu, MenubarSeparator, MenubarTrigger} from '@/components/ui/menubar';
import MainContentArea from '@/components/MainContentArea.jsx';
import {useAPI} from '@/providers/APIProvider.jsx';
import AddCollectionDialog from '@/components/api-tester/AddCollectionDialog.jsx';
import AddAPIDialog from '@/components/api-tester/AddAPIDialog.jsx';
import AddScenarioDialog from '@/components/api-tester/AddScenarioDialog.jsx';
import {useLoadTest} from '@/providers/LoadTestProvider.jsx';

const menuConfig = [
  {
    id: 'response',
    label: '응답관리',
    items: [
      {id: 'response-list', label: '응답목록', action: 'response-list'},
      {id: 'response-add', label: '응답추가', action: 'response-add'}
    ]
  },
  {
    id: 'request',
    label: '요청관리',
    items: [
      {id: 'collection-add', label: '컬렉션 추가', action: 'collection-add'},
      {id: 'request-add', label: '요청 추가', action: 'request-add'},
      {id: 'scenario-add', label: '시나리오 추가', action: 'scenario-add'}
    ]
  },
  {
    id: 'queue',
    label: '큐관리',
    items: [
      {id: 'queue-status', label: '큐상태', action: 'queue-status'},
      {id: 'queue-settings', label: '큐설정', action: 'queue-settings'}
    ]
  },
  {
    id: 'loadtest',
    label: '부하테스트',
    items: [
      {id: 'load-test-new', label: '새 테스트', action: 'load-test-new'},
      {id: 'load-test-history', label: '테스트 이력', action: 'load-test-history'},
      {id: 'load-test-reports', label: '결과 리포트', action: 'load-test-reports'}
    ]
  },
  {
    id: 'system',
    label: '시스템관리',
    items: [
      {id: 'system-settings', label: '시스템설정', action: 'system-settings'},
      {id: 'user-management', label: '사용자관리', action: 'user-management'},
      {type: 'separator'},
      {id: 'system-logs', label: '시스템로그', action: 'system-logs'}
    ]
  },
  {
    id: 'account',
    label: '계정',
    items: [
      {id: 'change-password', label: '비밀번호변경', action: 'change-password'},
      {type: 'separator'},
      {id: 'logout', label: '로그아웃', action: 'logout'}
    ]
  }
];

const MenuItem = ({item, onMenuClick}) => {
  if (item.type === 'separator') {
    return <MenubarSeparator/>;
  }

  return (
      <MenubarItem onClick={() => onMenuClick(item.action)}>
        {item.label}
      </MenubarItem>
  );
};

const APITester = () => {
  // API 모드와 시나리오 모드 상태를 관리
  const [isApiMode, setIsApiMode] = useState(true);
  const [showAddCollection, setShowAddCollection] = useState(false);
  const [showAddApi, setShowAddApi] = useState(false);
  const [showAddScenario, setShowAddScenario] = useState(false);
  const { handleLogout, createCollection, createAPIRequest } = useAPI();
  const {createScenario} = useLoadTest();

  // 모드 전환 핸들러
  const toggleMode = () => {
    setIsApiMode((prevMode) => !prevMode);
  };

  const handleAddCollection = async (name) => {
    try {
      await createCollection(name);
      return true;
    } catch (error) {
      throw new Error('컬렉션 생성에 실패했습니다');
    }
  };

  const handleAddApi = async (collectionId, apiData) => {
    try {
      await createAPIRequest(collectionId, apiData);
      return true;
    } catch (error) {
      console.error('Failed to create API:', error);
      return false;
    }
  };

  const handleAddScenario = async (name) => {
    try {
      await createScenario(name);
      return true;
    } catch (error) {
      console.error('시나리오 생성에 실패했습니다.');
    }
  }


  const handleMenuClick = async (action) => {
    // Handle menu item clicks
    console.log('Menu action:', action);
    switch (action) {
      case 'request-add':
        setShowAddApi(true);
        break;
      case 'collection-add':
        setShowAddCollection(true);
        break;
      case 'scenario-add':
        setShowAddScenario(true);
        break;
      case 'logout':
        const success = await handleLogout();
        if (success) {
          window.location.href = "/actionLogout.do";
        }
        break;
      case 'change-password':
        // Handle password change
        break;
        // Add other cases as needed
    }
  };

  return (
      <div className="flex flex-col h-screen">
        {/* Fixed Menubar */}
        <div className="fixed top-0 left-0 right-0 z-50 bg-background border-b">
          <div className="flex items-center h-14">
            <div className="px-4 py-2 border-r h-full flex items-center">
              <img
                  src="/img/logo.png"
                  alt="testmaster"
                  className="h-8 w-auto"
              />
            </div>
            <Menubar className="border-none flex-1">
              {menuConfig.map((menu) => (
                  <MenubarMenu key={menu.id}>
                    <MenubarTrigger className="font-bold">
                      {menu.label}
                    </MenubarTrigger>
                    <MenubarContent>
                      {menu.items.map((item, index) => (
                          <MenuItem
                              key={item.id || `separator-${index}`}
                              item={item}
                              onMenuClick={handleMenuClick}
                          />
                      ))}
                    </MenubarContent>
                  </MenubarMenu>
              ))}
            </Menubar>
          </div>
        </div>

        {/* Main content area with top padding for menubar */}
        <div className="flex-1 pt-14">
          <MainContentArea isApiMode={isApiMode} toggleMode={toggleMode}/>
        </div>
        <AddCollectionDialog
            open={showAddCollection}
            onOpenChange={setShowAddCollection}
            onSubmit={handleAddCollection}
        />
        {/* Add these at the bottom of your return statement */}
        <AddAPIDialog
            open={showAddApi}
            onOpenChange={setShowAddApi}
            onSubmit={handleAddApi}
        />
        <AddScenarioDialog
          open={showAddScenario}
          onOpenChange={setShowAddScenario}
          onSubmit={handleAddScenario}
        />
      </div>
  );
};

export default APITester;
