import { top_route } from "../../json/rate_config.js";
import util from "../../lib/util.js";
import { SourceDestinationType, TopRoutesProps } from "./type.js";
import React from "react";

export const TopRoutes = (props: TopRoutesProps) => {
    const { selectedRoute, handleSelectRoute } = props;

    const { config } = top_route;
    const route_data:any = config.filter((_data: any) => _data.key === "top_route")[0]?.value;

    const routes = util.isEmptyObject(route_data)
        ? []
        : Object.entries(route_data).map(([key, value]) => ({
            id: key,
            source: Array.isArray(value)
                ? value[0]?.source?.alias?.name || value[0]?.source?.name
                : null,
            route: value || [],
        }));

    const onSelect = (city: SourceDestinationType) => {
        handleSelectRoute(city)
    };

    return (
        <div>
            {routes && routes.length
                ? routes.map((_r) => {
                    const route: any = _r?.route;
                    return (
                        <div
                            key={_r.id}
                            className="fr-border fr-bg-white fr-border-slate-200 fr-mb-2 fr-py-1 fr-px-3 fr-rounded-lg fr-relative"
                        >
                            <p className="fr-text-sm fr-font-semibold fr-mb-1">{_r.source} to</p>
                            <div>
                                {util.isEmptyArray(route)
                                    ? null
                                    : route.map((_rou: any) => {
                                        const active = ((_rou.destination_id === selectedRoute.destinationId) && (_rou.source_id === selectedRoute.sourceId));

                                        return (
                                            <button
                                                key={_rou.destination_id}
                                                onClick={() => onSelect(_rou)}
                                                className={`${active ? "fr-rate-btn" : "fr-rate-outline-btn"}`}
                                            >
                                                {_rou.destination.alias?.name || _rou.destination.name}
                                            </button>
                                        );
                                    })}
                            </div>
                        </div>
                    );
                })
                : null}
        </div>
    );
};
