import { useState, type Dispatch, type SetStateAction } from "react";
import API_URL from "../config";
import "../styles/button.css";
import "../styles/sidebar.css";
import type { Robot } from "../types/robot";
import AddRobotForm from "./AddRobotForm";
import RobotList from "./RobotList";
import SimulationActions from "./SimulationActions";

type Props = {
    errorMessage: string;
    robots: Robot[];
    token: string | null;
    setErrorMessage: Dispatch<SetStateAction<string>>;
};

function Sidebar({ errorMessage, robots, token, setErrorMessage }: Props) {
    const [isAddingRobot, setIsAddingRobot] = useState(false);

    function handleAddClick() {
        setIsAddingRobot(true);
        setErrorMessage("");
    }

    return (
        <div className="sidebar">
            <div className="sidebar-robots-header">
                <h2>Your Robots</h2>
                <button
                    className="btn btn-add-robot"
                    onClick={handleAddClick}
                    disabled={isAddingRobot}
                >
                    + Add
                </button>
            </div>

           {isAddingRobot && (
                <AddRobotForm
                    apiUrl={API_URL}
                    errorMessage={errorMessage}
                    token={token}
                    setErrorMessage={setErrorMessage}
                    setIsAddingRobot={setIsAddingRobot}
                />
            )}

            {errorMessage && (
                <div className="error-message">{errorMessage}</div>
            )}

            <SimulationActions
                apiUrl={API_URL}
                token={token}
                setErrorMessage={setErrorMessage}
            />

            <RobotList robots={robots} />
        </div>
    );
}

export default Sidebar;

