import { type Dispatch, type SetStateAction } from "react";
import type { ErrorResponse } from "../types/error";
import type { SimulationResponse } from "../types/robot";

type Props = {
    activeSimulation: boolean;
    apiUrl: string;
    token: string | null;
    setActiveSimulation: Dispatch<SetStateAction<boolean>>;
    setErrorMessage: Dispatch<SetStateAction<string>>;
};

function SimulationActions({
    activeSimulation,
    apiUrl,
    token,
    setActiveSimulation,
    setErrorMessage,
}: Props) {
    async function handleStartAllRobots() {
        setActiveSimulation(true);

        try {
            const response = await fetch(`${apiUrl}/robots/move`, {
                method: "POST",
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json",
                },
            });

            if (!response.ok) {
                const errorData: ErrorResponse = await response.json();
                throw new Error(
                    errorData.message || "Failed to set all robots moving."
                );
            }

            const data: SimulationResponse = await response.json();
            console.log(data.message);
        } catch (error) {
            console.error("Error starting robots:", error);

            if (error instanceof Error) {
                setErrorMessage(error.message);
            } else {
                setErrorMessage("An unexpected error occurred.");
            }

            setActiveSimulation(false);
        }
    }

    async function handleStopAllRobots() {
        setActiveSimulation(false);

        try {
            const response = await fetch(`${apiUrl}/robots/stop`, {
                method: "POST",
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json",
                },
            });

            if (!response.ok) {
                const errorData: ErrorResponse = await response.json();
                throw new Error(
                    errorData.message || "Failed to set all robots idle."
                );
            }

            const data: SimulationResponse = await response.json();
            console.log(data.message);
        } catch (error) {
            console.error("Error stopping robots:", error);

            if (error instanceof Error) {
                setErrorMessage(error.message);
            } else {
                setErrorMessage("An unexpected error occurred.");
            }

            setActiveSimulation(true);
        }
    }

    return (
        <div className="simulation-actions">
            <button
                className="btn btn-start"
                onClick={handleStartAllRobots}
                disabled={activeSimulation}
            >
                Start simulation
            </button>

            <button
                className="btn btn-stop"
                onClick={handleStopAllRobots}
                disabled={!activeSimulation}
            >
                Stop simulation
            </button>
        </div>
    );
}

export default SimulationActions;

