import { useState } from "react";
import type { Robot } from "../types/robot";

type ExpandedRobotsState = Record<number, boolean>;

type Props = { robots: Robot[]; };

function RobotList({ robots }: Props) {
    const [expandedRobots, setExpandedRobots] = useState<ExpandedRobotsState>(
        {}
    );

    function toggleRobotHistory(robotId: number) {
        setExpandedRobots((prev) => ({
            ...prev,
            [robotId]: !prev[robotId],
        }));
    }

    return (
        <ul className="sidebar-robot-list">
            {robots.map((robot) => {
                const isExpanded = expandedRobots[robot?.id];

                return (
                    <li key={robot?.id}>
                        <p className="robot-name">{robot?.name}</p>

                        <p>
                            Status:{" "}
                            <span className={`robot-status-${robot?.status}`}>
                                {robot?.status}
                            </span>
                        </p>

                        <p className="robot-coordinates-label">Position:</p>
                        <ul className="robot-coordinates">
                            <li>Lat: {robot?.lat}</li>
                            <li>Lon: {robot?.lon}</li>
                        </ul>

                        <button
                            className="btn btn-robot-history-toggle"
                            onClick={() => toggleRobotHistory(robot?.id)}
                            aria-expanded={isExpanded}
                        >
                            Position history
                            <span
                                className={`arrow ${isExpanded ? "open" : ""}`}
                            >
                                ▾
                            </span>
                        </button>

                        <div
                            className={`robot-history ${
                                isExpanded ? "expanded" : ""
                            }`}
                        >
                            <ul>
                                {robot?.robot_positions?.length ? (
                                    robot?.robot_positions?.map(
                                        (pos, index) => (
                                            <li key={index}>
                                                {`Lat: ${pos?.lat}, Lon: ${pos?.lon}`}
                                            </li>
                                        )
                                    )
                                ) : (
                                    <li className="robot-history-empty">
                                        No previous positions.
                                    </li>
                                )}
                            </ul>
                        </div>
                    </li>
                );
            })}
        </ul>
    );
}

export default RobotList;

