import React, {useEffect, useState} from 'react';
import { FileText, MoreHorizontal } from 'lucide-react';
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuItem,
  SidebarMenuButton,
  SidebarMenuAction, SidebarHeader
} from '@/components/ui/sidebar';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip';
import { Button } from '@/components/ui/button';
import { useLoadTest } from '@/providers/LoadTestProvider';
import { SidebarProvider } from '@/components/ui/sidebar';
import DeleteScenarioDialog from '@/components/api-tester/DeleteScenarioDialog.jsx';

const ScenarioDropdownMenu = ({ onOpen, onRename, onDelete }) => (
    <DropdownMenu>
      <DropdownMenuTrigger data-dropdown-trigger="true" asChild>
        <div className="p-0 h-auto hover:bg-accent rounded-sm">
          <MoreHorizontal className="h-4 w-4"/>
        </div>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuItem onClick={onOpen}>
          열기
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem onClick={onRename}>
          이름 변경
        </DropdownMenuItem>
        <DropdownMenuItem className="text-destructive" onClick={onDelete}>
          삭제
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
);

const LoadingSpinner = () => (
    <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>
);

const ErrorMessage = ({ message }) => (
    <SidebarContent>
      <Alert className="m-4">
        <AlertDescription>{message}</AlertDescription>
      </Alert>
    </SidebarContent>
);

const ScenarioNavigation = ({
  contextPath = '/',
  side,
  isApiMode,
  onToggleMode
}) => {

  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [scenarioToDelete, setScenarioToDelete] = useState(null);

  const {
    scenarios,
    loading,
    error,
    deleteScenario,
    loadScenarioList,
    selectScenario
  } = useLoadTest();

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

  const handleScenarioAction = {
    open: async (scenarioId) => {
      try {
        console.log({scenarioId});
        selectScenario(scenarioId);
      } catch (err) {
        console.error('Failed to select scenario:', err);
      }
    },
    delete: async (scenario) => {
      console.log('delete', scenario);
      setScenarioToDelete(scenario);
      setDeleteDialogOpen(true);
    },
    rename: (scenarioId) => {
      // TODO: Implement rename functionality
      console.log('Rename scenario:', scenarioId);
    }
  };

  const handleDeleteConfirm = async () => {
    if (scenarioToDelete) {
      await deleteScenario(scenarioToDelete);
      setDeleteDialogOpen(false);
      setScenarioToDelete(null);
    }
  };

  const renderScenarioItem = (scenario) => (
      <SidebarMenuItem key={scenario.id}>
        <SidebarMenuButton
            onClick={() => handleScenarioAction.open(scenario.id)}
            className="w-full justify-start gap-2"
            asChild
        >
          <div className="w-full flex items-center gap-2 min-w-0 pr-2">
            <FileText className="h-4 w-4 flex-shrink-0"/>
            <Tooltip>
              <TooltipTrigger asChild>
                <span className="truncate flex-1">{scenario.name}</span>
              </TooltipTrigger>
              <TooltipContent>
                <p>{scenario.name}</p>
              </TooltipContent>
            </Tooltip>
            <SidebarMenuAction className="p-0 m-0 flex-shrink-0">
              <ScenarioDropdownMenu
                  onOpen={() => handleScenarioAction.open(scenario.id)}
                  onRename={() => handleScenarioAction.rename(scenario.id)}
                  onDelete={() => handleScenarioAction.delete(scenario)}
              />
            </SidebarMenuAction>
          </div>
        </SidebarMenuButton>
      </SidebarMenuItem>
  );

  const renderContent = () => {
    if (loading) {
      return <LoadingSpinner />;
    }

    if (error) {
      return <ErrorMessage message={error} />;
    }

    return (
        <SidebarContent>
          <ScrollArea className="h-[calc(100%-64px)]">
            <SidebarGroup>
              <SidebarGroupLabel>Scenarios</SidebarGroupLabel>
              <SidebarMenu>
                {scenarios.map(renderScenarioItem)}
              </SidebarMenu>
            </SidebarGroup>
          </ScrollArea>
        </SidebarContent>
    );
  };

  return (
      <SidebarProvider>
        <Sidebar side={side} className="py-16">
          <SidebarHeader>
            <Button
                variant="outline"
                className="w-full"
                onClick={onToggleMode}
            >
              {isApiMode ? 'Switch to Scenario Mode' : 'Switch to API Mode'}
            </Button>
          </SidebarHeader>
          {renderContent()}
          <DeleteScenarioDialog
              open={deleteDialogOpen}
              onOpenChange={setDeleteDialogOpen}
              onConfirm={handleDeleteConfirm}
              scenarioName={scenarioToDelete?.name || ''}
          />
        </Sidebar>
      </SidebarProvider>
  );
};

export default ScenarioNavigation;
