import React, { useState } from "react"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, } from "@/components/ui/dialog"; import { Loader2, Search, CheckCircle, AlertCircle } from "lucide-react"; import { useToast } from "@/hooks/use-toast"; import { useApi } from "@/contexts/ApiContext"; interface PortDetectionModalProps { open: boolean; onOpenChange: (open: boolean) => void; robotType: "leader" | "follower"; onPortDetected: (port: string) => void; } const PortDetectionModal: React.FC = ({ open, onOpenChange, robotType, onPortDetected, }) => { const [step, setStep] = useState< "instructions" | "detecting" | "success" | "error" >("instructions"); const [detectedPort, setDetectedPort] = useState(""); const [error, setError] = useState(""); const [portsBeforeDisconnect, setPortsBeforeDisconnect] = useState( [] ); const { toast } = useToast(); const { baseUrl, fetchWithHeaders } = useApi(); const handleStartDetection = async () => { try { setStep("detecting"); setError(""); // Start port detection process const response = await fetchWithHeaders( `${baseUrl}/start-port-detection`, { method: "POST", body: JSON.stringify({ robot_type: robotType, }), } ); const data = await response.json(); if (data.status === "success") { setPortsBeforeDisconnect(data.data.ports_before); // Give user time to disconnect setTimeout(() => { detectPortAfterDisconnect(data.data.ports_before); }, 3000); // 3 second delay to allow disconnection } else { throw new Error(data.message || "Failed to start port detection"); } } catch (error) { console.error("Error starting port detection:", error); setError( `Error starting detection: ${ error instanceof Error ? error.message : "Unknown error" }` ); setStep("error"); } }; const detectPortAfterDisconnect = async (portsBefore: string[]) => { try { const response = await fetchWithHeaders( `${baseUrl}/detect-port-after-disconnect`, { method: "POST", body: JSON.stringify({ ports_before: portsBefore, }), } ); const data = await response.json(); if (data.status === "success") { setDetectedPort(data.port); // Save the port for future use await savePort(data.port); setStep("success"); toast({ title: "Port Detected Successfully", description: `${robotType} port detected: ${data.port}`, }); } else { throw new Error(data.message || "Failed to detect port"); } } catch (error) { console.error("Error detecting port:", error); setError( `Error detecting port: ${ error instanceof Error ? error.message : "Unknown error" }` ); setStep("error"); } }; const savePort = async (port: string) => { try { await fetchWithHeaders(`${baseUrl}/save-robot-port`, { method: "POST", body: JSON.stringify({ robot_type: robotType, port: port, }), }); } catch (error) { console.error("Error saving port:", error); // Don't throw here, as the main detection was successful } }; const handleUsePort = () => { onPortDetected(detectedPort); onOpenChange(false); resetModal(); }; const handleClose = () => { onOpenChange(false); resetModal(); }; const resetModal = () => { setStep("instructions"); setDetectedPort(""); setError(""); setPortsBeforeDisconnect([]); }; const renderStepContent = () => { switch (step) { case "instructions": return (

Detect {robotType === "leader" ? "Leader" : "Follower"} Port

Follow these steps to automatically detect the robot port:

1

Make sure your {robotType} robot arm is currently connected

2

Click "Start Detection" below

3

When prompted,{" "} unplug the {robotType} robot arm from USB

4

The system will automatically detect which port was disconnected

); case "detecting": return (

Detecting Port...

Please unplug the {robotType} robot arm from USB now

Detection will complete automatically in a few seconds

); case "success": return (

Port Detected Successfully!

{robotType === "leader" ? "Leader" : "Follower"} port detected:

{detectedPort}

This port has been saved as the default for future use.
You can now reconnect your robot arm.

); case "error": return (

Detection Failed

Unable to detect the robot port.

{error}

); default: return null; } }; return ( Port Detection Automatically detect the USB port for your robot arm
{renderStepContent()}
); }; export default PortDetectionModal;