import type { TguPlatformUi } from "../../model/timelineTypes";
import { filterPlatforms, platformLabel } from "../tgu-planning/tguTimelineMapper";
import { TGU_2D_MAP_LAYERS, type Tgu2DMapLayerKey, type Tgu2DMapLayersState } from "./model/mapLayerTypes";
import type { Tgu2DMapLayerAvailability } from "./Tgu2DMapLayers";
import type { RequestsState } from "./Tgu2DMapTab";
import { parseLocal } from "../../utils/localTime";
import { DateTime24Field } from "../../components/timeFields";

const DAY_MS = 24 * 60 * 60 * 1000;

type Tgu2DMapSidebarProps = {
  platforms: TguPlatformUi[];
  selectedPlanId?: string;
  hiddenIds: ReadonlySet<string>;
  layers: Tgu2DMapLayersState;
  search: string;
  layerAvailability: Tgu2DMapLayerAvailability;
  requestsState: RequestsState;
  onSearchChange: (value: string) => void;
  onToggleSpacecraft: (id: string) => void;
  onShowAll: () => void;
  onToggleLayer: (key: Tgu2DMapLayerKey) => void;
  onRequestsFromChange: (value: string) => void;
  onRequestsToChange: (value: string) => void;
  onRequestsApply: () => void;
  onRequestsQuickRange: (fromMs: number, toMs: number) => void;
};

export function Tgu2DMapSidebar({
  platforms,
  selectedPlanId,
  hiddenIds,
  layers,
  search,
  layerAvailability,
  requestsState,
  onSearchChange,
  onToggleSpacecraft,
  onShowAll,
  onToggleLayer,
  onRequestsFromChange,
  onRequestsToChange,
  onRequestsApply,
  onRequestsQuickRange
}: Tgu2DMapSidebarProps) {
  const filteredPlatforms = filterPlatforms(platforms, search);
  const hiddenCount = hiddenIds.size;

  const quickToday = () => {
    const now = new Date();
    const fromMs = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
    onRequestsQuickRange(fromMs, fromMs + DAY_MS);
  };

  const quick7days = () => {
    const fromMs = Date.now();
    onRequestsQuickRange(fromMs, fromMs + 7 * DAY_MS);
  };

  const quick30days = () => {
    const fromMs = Date.now();
    onRequestsQuickRange(fromMs, fromMs + 30 * DAY_MS);
  };

  const requestsFromMs = parseLocal(requestsState.fromValue);
  const requestsToMs = parseLocal(requestsState.toValue);
  const requestsRangeInvalid =
    !Number.isFinite(requestsFromMs) ||
    !Number.isFinite(requestsToMs) ||
    requestsFromMs >= requestsToMs;

  return (
    <aside className="tgu-map-panel">
      <div className="tgu-panel-heading">
        <span>Карта</span>
        {hiddenCount > 0 && (
          <button className="tgu-link-button" type="button" onClick={onShowAll}>
            Показать все ({hiddenCount} скрыто)
          </button>
        )}
      </div>
      <div className="tgu-map-panel__section">
        <div className="tgu-map-panel__label">Выбранный план</div>
        <div className="tgu-map-panel__value mono">{selectedPlanId || "-"}</div>
      </div>
      <div className="tgu-map-panel__section">
        <div className="tgu-map-panel__label">Слои</div>
        <div className="tgu-map-layer-list">
          {TGU_2D_MAP_LAYERS.map((layer) => (
            <label className="tgu-map-layer" key={layer.key}>
              <input type="checkbox" checked={layers[layer.key]} onChange={() => onToggleLayer(layer.key)} />
              <span>
                <span className="tgu-map-layer__title">{layer.label}</span>
                <span className="tgu-map-layer__description">{layer.description}</span>
                {layers[layer.key] && layerAvailability[layer.key] && (
                  <span className="tgu-map-layer__warning">{layerAvailability[layer.key]}</span>
                )}
              </span>
            </label>
          ))}
        </div>
      </div>

      <div className="tgu-map-panel__section">
        <div className="tgu-map-panel__label">Заявки на съёмку</div>
        <div className="tgu-map-requests-filter">
          <label className="tgu-field">
            <span>С</span>
            <DateTime24Field value={requestsState.fromValue} onChange={onRequestsFromChange} />
          </label>
          <label className="tgu-field">
            <span>По</span>
            <DateTime24Field value={requestsState.toValue} onChange={onRequestsToChange} />
          </label>
          <div className="tgu-map-requests-filter__actions">
            <button
              className="tgu-button tgu-button--primary tgu-button--sm"
              type="button"
              onClick={onRequestsApply}
              disabled={requestsState.loading || requestsRangeInvalid}
            >
              {requestsState.loading ? "Загрузка..." : "Загрузить"}
            </button>
            <button className="tgu-button tgu-button--sm" type="button" onClick={quickToday} disabled={requestsState.loading}>
              Сегодня
            </button>
            <button className="tgu-button tgu-button--sm" type="button" onClick={quick7days} disabled={requestsState.loading}>
              7 дней
            </button>
            <button className="tgu-button tgu-button--sm" type="button" onClick={quick30days} disabled={requestsState.loading}>
              30 дней
            </button>
          </div>
          {requestsState.error && (
            <div className="tgu-alert tgu-alert--danger tgu-alert--compact">{requestsState.error}</div>
          )}
          {requestsState.loading && requestsState.totalItems > 0 && (
            <div className="tgu-map-requests-filter__status">
              Загрузка: {requestsState.loadedCount} / {requestsState.totalItems}...
            </div>
          )}
          {requestsState.loaded && !requestsState.error && (
            <div className="tgu-map-requests-filter__status">
              {requestsState.items.length === 0
                ? "Заявок не найдено."
                : `Загружено: ${requestsState.items.length} из ${requestsState.totalItems}`}
              {requestsState.truncated && (
                <span className="tgu-map-requests-filter__truncated"> (показаны первые 5000 — уточните интервал)</span>
              )}
            </div>
          )}
          {requestsState.loaded && requestsState.items.length > 0 && (
            <div className="tgu-map-requests-legend">
              <span><i className="req-optics" />OPTICS</span>
              <span><i className="req-rsa" />RSA</span>
              <span><i className="req-combined" />COMBINED</span>
            </div>
          )}
        </div>
      </div>

      <div className="tgu-map-panel__section">
        <div className="tgu-map-panel__label">Космические аппараты</div>
        <div className="tgu-search">
          <input
            type="search"
            placeholder="Поиск name / NORAD / mission"
            value={search}
            onChange={(event) => onSearchChange(event.target.value)}
          />
        </div>
        <div className="tgu-map-spacecraft-list">
          {filteredPlatforms.map((platform) => {
            const visible = !hiddenIds.has(platform.spacecraftId);
            return (
              <label
                className={`tgu-map-spacecraft ${visible ? "" : "is-hidden"}`}
                key={platform.spacecraftId}
              >
                <input
                  type="checkbox"
                  checked={visible}
                  onChange={() => onToggleSpacecraft(platform.spacecraftId)}
                />
                <span>
                  <span className="tgu-map-spacecraft__name">{platformLabel(platform, platform.spacecraftId)}</span>
                  <span className="tgu-map-spacecraft__meta">
                    NORAD {platform.noradId || platform.spacecraftId}
                    {platform.mission ? ` · ${platform.mission}` : ""}
                  </span>
                </span>
                <span className="tgu-spacecraft__count">{platform.planCount}</span>
              </label>
            );
          })}
          {filteredPlatforms.length === 0 && <div className="tgu-empty tgu-empty--compact">Нет КА по текущему поиску.</div>}
        </div>
      </div>

    </aside>
  );
}
