import React, {useEffect, useState} from 'react';
import {ChevronRight} from 'lucide-react';
import {Sidebar, SidebarContent, SidebarGroup, SidebarGroupLabel, SidebarHeader, SidebarMenu, SidebarMenuAction, SidebarMenuButton, SidebarMenuItem, SidebarProvider} from '@/components/ui/sidebar';
import {ScrollArea} from '@/components/ui/scroll-area';
import {Alert, AlertDescription} from '@/components/ui/alert';
import {Button} from '@/components/ui/button';
import {Tooltip, TooltipContent, TooltipTrigger} from '@/components/ui/tooltip';
import {useAPI} from '@/providers/APIProvider';
import DraggableApiItem from '@/components/api-tester/DraggableApiItem';
import DeleteCollectionDialog from './DeleteCollectionDialog';
import RenameCollectionDialog from './RenameCollectionDialog';
import CollectionDropdownMenu from './CollectionDropdownMenu';
import DeleteAPIDialog from '@/components/api-tester/DeleteApiDialog.jsx';
import RenameAPIDialog from './RenameAPIDialog';
import AddAPIDialog from '@/components/api-tester/AddAPIDialog';

const APINavigation = ({
  contextPath = '/',
  onApiSelect,
  side,
  isApiMode,
  onToggleMode
}) => {
  // State
  const [selectedCollection, setSelectedCollection] = useState(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [renameDialogOpen, setRenameDialogOpen] = useState(false);
  const [collectionToDelete, setCollectionToDelete] = useState(null);
  const [collectionToRename, setCollectionToRename] = useState(null);
  const [showAddApi, setShowAddApi] = useState(false);
  const [apiToDelete, setApiToDelete] = useState(null);
  const [apiToRename, setApiToRename] = useState(null);
  const [renameApiDialogOpen, setRenameApiDialogOpen] = useState(false);


  // API Context
  const {
    collections,
    loading,
    error,
    loadCollections,
    deleteCollection,
    updateCollection,
    deleteAPIRequest,
    createAPIRequest,
    updateAPIRequest
  } = useAPI();

  // Load collections on mount
  useEffect(() => {
    loadCollections();
  }, [contextPath]);

  // Handlers
  const handleCollectionClick = (collectionId, event) => {
    // Prevent click when clicking dropdown menu
    if (!event.target.closest('[data-dropdown-trigger="true"]')) {
      setSelectedCollection(selectedCollection === collectionId ? null : collectionId);
    }
  };

  const handleApiAction = {
    open: (collectionId, apiId) => {
      if (onApiSelect) onApiSelect(collectionId, apiId);
    },
    delete: async (collectionId, apiId) => {
      setApiToDelete({ collectionId, apiId });
    },
    rename: (collectionId, apiId) => {
      const collection = collections.find(c => c.id === collectionId);
      const api = collection?.apis?.find(a => a.id === apiId);
      if (api) {
        setApiToRename({ ...api, collectionId });
        setRenameApiDialogOpen(true);
      }
    }
  };

  const handleRenameApi = async (apiId, newName) => {
    if (apiToRename) {
      try {
        const updatedApi = {
          ...apiToRename,
          name: newName
        };
        await updateAPIRequest(updatedApi);
        setApiToRename(null);
        setRenameApiDialogOpen(false);
        await loadCollections(); // Refresh the collections
        return true;
      } catch (error) {
        console.error('Failed to rename API:', error);
        return false;
      }
    }
  };

  const handleDeleteApi = async () => {
    if (apiToDelete) {
      try {
        await deleteAPIRequest(apiToDelete.collectionId, apiToDelete.apiId);
        setApiToDelete(null);
        return true;
      } catch (error) {
        console.error('Failed to delete API:', error);
        return false;
      }
    }
  };

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

  const handleCollectionAction = {
    delete: async (collection) => {
      setCollectionToDelete(collection);
      setDeleteDialogOpen(true);
    },
    rename: (collection) => {
      setCollectionToRename(collection);
      setRenameDialogOpen(true);
    },
    addRequest: (collection) => {
      setSelectedCollection(collection);
      setShowAddApi(true);
    }
  };

  const handleDeleteConfirm = async () => {
    if (collectionToDelete) {
      try {
        const success = await deleteCollection(collectionToDelete.id);
        if (success) {
          // If the deleted collection was selected, clear the selection
          if (selectedCollection === collectionToDelete.id) {
            setSelectedCollection(null);
          }
        }
      } catch (error) {
        console.error('Failed to delete collection:', error);
      }
    }
  };

  const handleRenameConfirm = async (collectionId, newName) => {
    try {
      const success = await updateCollection(collectionId, newName);
      if (success) {
        await loadCollections();
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to rename collection:', error);
      throw error;
    }
  };

  // Render helpers
  const renderApiList = (collection) => {
    if (selectedCollection !== collection.id || !collection.apis?.length) {
      return null;
    }

    return collection.apis.map((api) => (
        <DraggableApiItem
            key={api.id}
            api={api}
            collectionId={collection.id}
            onApiAction={handleApiAction}
        />
    ));
  };

  const renderCollectionItem = (collection) => (
      <SidebarMenuItem key={collection.id}>
        <SidebarMenuButton
            onClick={(e) => handleCollectionClick(collection.id, e)}
            className="w-full justify-start gap-2"
            asChild
        >
          <div className="w-full flex items-center gap-2 min-w-0 pr-2">
            <ChevronRight
                className={`flex-shrink-0 transition-transform ${
                    selectedCollection === collection.id ? 'rotate-90' : ''
                }`}
            />
            <Tooltip>
              <TooltipTrigger asChild>
                <span className="truncate flex-1">{collection.name}</span>
              </TooltipTrigger>
              <TooltipContent>
                <p>{collection.name}</p>
              </TooltipContent>
            </Tooltip>
            <SidebarMenuAction className="p-0 m-0 flex-shrink-0">
              <CollectionDropdownMenu
                  collection={collection}
                  onAddRequest={() => handleCollectionAction.addRequest(collection)}
                  onRename={() => handleCollectionAction.rename(collection)}
                  onDelete={() => handleCollectionAction.delete(collection)}
              />
            </SidebarMenuAction>
          </div>
        </SidebarMenuButton>
        {renderApiList(collection)}
      </SidebarMenuItem>
  );

  const renderContent = () => {
    if (loading) {
      return (
          <SidebarContent>
            <div className="flex items-center justify-center h-full">
              <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
            </div>
          </SidebarContent>
      );
    }

    if (error) {
      return (
          <SidebarContent>
            <Alert className="m-4">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          </SidebarContent>
      );
    }

    return (
        <SidebarContent>
          <ScrollArea className="h-[calc(100vh-64px)]">
            <SidebarGroup>
              <SidebarGroupLabel>Collections</SidebarGroupLabel>
              <SidebarMenu>
                {collections.map(renderCollectionItem)}
              </SidebarMenu>
            </SidebarGroup>
          </ScrollArea>
        </SidebarContent>
    );
  };

  return (
      <SidebarProvider>
        <Sidebar side={side} className="py-16">
          {side === 'left' && (
              <SidebarHeader>
                <Button
                    variant="outline"
                    className="w-full"
                    onClick={onToggleMode}
                >
                  {isApiMode ? 'Switch to Scenario Mode' : 'Switch to API Mode'}
                </Button>
              </SidebarHeader>
          )}
          {renderContent()}
        </Sidebar>

        <DeleteCollectionDialog
            open={deleteDialogOpen}
            onOpenChange={setDeleteDialogOpen}
            onConfirm={handleDeleteConfirm}
            collectionName={collectionToDelete?.name || ''}
        />

        <RenameCollectionDialog
            open={renameDialogOpen}
            onOpenChange={setRenameDialogOpen}
            onSubmit={handleRenameConfirm}
            collection={collectionToRename}
        />


        <DeleteAPIDialog
            open={!!apiToDelete}
            onOpenChange={(open) => !open && setApiToDelete(null)}
            onConfirm={handleDeleteApi}
            apiName={apiToDelete?.name || ''}
        />
        <AddAPIDialog
            open={showAddApi}
            onOpenChange={setShowAddApi}
            onSubmit={handleAddApi}
            selectedCollection={collections.find(c => c.id === selectedCollection)}
        />

        <RenameAPIDialog
            open={renameApiDialogOpen}
            onOpenChange={setRenameApiDialogOpen}
            onSubmit={handleRenameApi}
            api={apiToRename}
        />
      </SidebarProvider>
  );
};

export default APINavigation;
