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 ErrorBanner from "./ErrorBanner";
import RobotList from "./RobotList";
import SimulationActions from "./SimulationActions";

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

function Sidebar({
    activeSimulation,
    errorMessage,
    robots,
    token,
    setActiveSimulation,
    setErrorMessage,
    setRobots,
}: 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}
                    robots={robots}
                    token={token}
                    setErrorMessage={setErrorMessage}
                    setIsAddingRobot={setIsAddingRobot}
                    setRobots={setRobots}
                />
            )}

            {errorMessage && <ErrorBanner message={errorMessage} />}
            
            <SimulationActions
                activeSimulation={activeSimulation}
                apiUrl={API_URL}
                token={token}
                setActiveSimulation={setActiveSimulation}
                setErrorMessage={setErrorMessage}
            />

            <RobotList
                apiUrl={API_URL}
                robots={robots}
                token={token}
                setErrorMessage={setErrorMessage}
            />
        </div>
    );
}

export default Sidebar;
