import type { TguPlatformUi } from "../../model/timelineTypes";
import { filterPlatforms, platformLabel } from "./tguTimelineMapper";
import { TguLegend } from "./TguLegend";

type TguSidebarProps = {
  platforms: TguPlatformUi[];
  selectedSpacecraftId?: string;
  search: string;
  platformLoadFailed: boolean;
  onSearchChange: (value: string) => void;
  onSelectSpacecraft: (spacecraftId?: string) => void;
};

export function TguSidebar({
  platforms,
  selectedSpacecraftId,
  search,
  platformLoadFailed,
  onSearchChange,
  onSelectSpacecraft
}: TguSidebarProps) {
  const filtered = filterPlatforms(platforms, search);

  return (
    <aside className="tgu-sidebar">
      <div className="tgu-panel-heading">
        <span>Космические аппараты</span>
        <button className="tgu-link-button" type="button" onClick={() => onSelectSpacecraft(undefined)}>
          Все
        </button>
      </div>

      <div className="tgu-search">
        <input
          type="search"
          placeholder="Поиск name / NORAD / mission"
          value={search}
          onChange={(event) => onSearchChange(event.target.value)}
        />
      </div>

      {platformLoadFailed && (
        <div className="tgu-alert tgu-alert--warning">
          Список платформ не загрузился. Timeline построен по spacecraftId из планов.
        </div>
      )}

      <div className="tgu-spacecraft-list">
        {filtered.map((platform) => {
          const selected = selectedSpacecraftId === platform.spacecraftId;
          return (
            <button
              className={`tgu-spacecraft ${selected ? "is-selected" : ""}`}
              type="button"
              key={platform.spacecraftId}
              onClick={() => onSelectSpacecraft(selected ? undefined : platform.spacecraftId)}
            >
              <span className={`tgu-spacecraft__problem ${platform.hasProblemStatus ? "is-problem" : ""}`} />
              <span className="tgu-spacecraft__body">
                <span className="tgu-spacecraft__name">{platformLabel(platform, platform.spacecraftId)}</span>
                <span className="tgu-spacecraft__meta">
                  NORAD {platform.noradId || platform.spacecraftId}
                  {platform.mission ? ` · ${platform.mission}` : ""}
                </span>
                {platform.status && <span className="tgu-spacecraft__status">{platform.status}</span>}
              </span>
              <span className="tgu-spacecraft__count">{platform.planCount}</span>
            </button>
          );
        })}
        {filtered.length === 0 && <div className="tgu-empty tgu-empty--compact">Нет КА по текущему поиску.</div>}
      </div>

      <div className="tgu-sidebar__legend">
        <TguLegend />
      </div>
    </aside>
  );
}
