import type { RequestMapItem } from "../../model/requestTypes";
import type { MapPolygon } from "./model/mapTypes";

export type RequestAtPoint = { polygon: MapPolygon; item: RequestMapItem };

type Props = {
  requests: RequestAtPoint[];
  selectedPolygonId?: string;
  onHover: (polygonId: string | undefined) => void;
  onSelect: (polygonId: string) => void;
  onClose: () => void;
};

export function Tgu2DMapRequestsPanel({ requests, selectedPolygonId, onHover, onSelect, onClose }: Props) {
  const selectedEntry = selectedPolygonId ? requests.find((r) => r.polygon.id === selectedPolygonId) : undefined;

  return (
    <aside className="tgu-map-requests-panel">
      <div className="tgu-panel-heading">
        <span>Заявки в точке ({requests.length})</span>
        <button className="tgu-link-button" type="button" onClick={onClose}>
          Закрыть
        </button>
      </div>

      <div className="tgu-map-requests-list">
        {requests.map(({ polygon, item }) => (
          <button
            key={polygon.id}
            className={`tgu-map-request-row ${polygon.id === selectedPolygonId ? "is-selected" : ""}`}
            type="button"
            onMouseEnter={() => onHover(polygon.id)}
            onMouseLeave={() => onHover(undefined)}
            onClick={() => onSelect(polygon.id)}
          >
            <i className={`tgu-map-request-row__type req-${item.surveyType.toLowerCase()}`} />
            <span className="tgu-map-request-row__body">
              <span className="tgu-map-request-row__name">{item.name || item.id}</span>
              <span className="tgu-map-request-row__meta">
                {formatDateRange(item.beginDateTime, item.endDateTime)}
                {" · "}
                {item.surveyType}
                {" · "}
                {item.status}
              </span>
            </span>
          </button>
        ))}
      </div>

      {selectedEntry && (
        <div className="tgu-map-request-details">
          <div className="tgu-map-panel__label">Детали заявки</div>
          <dl className="tgu-map-request-details__grid">
            <dt>ID</dt>
            <dd className="mono">{selectedEntry.item.id}</dd>

            <dt>Название</dt>
            <dd>{selectedEntry.item.name || "—"}</dd>

            <dt>Статус</dt>
            <dd>{selectedEntry.item.status}</dd>

            <dt>Тип съёмки</dt>
            <dd>{selectedEntry.item.surveyType}</dd>

            <dt>Начало</dt>
            <dd className="mono">{formatDateTime(selectedEntry.item.beginDateTime)}</dd>

            <dt>Конец</dt>
            <dd className="mono">{formatDateTime(selectedEntry.item.endDateTime)}</dd>

            <dt>Важность</dt>
            <dd className="mono">{selectedEntry.item.importance}</dd>

            <dt>Покрытие</dt>
            <dd className="mono">{selectedEntry.item.coveragePercent != null ? `${selectedEntry.item.coveragePercent.toFixed(1)} %` : "—"}</dd>

            <dt>КПП</dt>
            <dd className="mono">{selectedEntry.item.kpp?.join(", ") || "—"}</dd>

            <dt>Приоритет передачи</dt>
            <dd>{selectedEntry.item.highPriorityTransmit ? "Да" : "Нет"}</dd>

            <dt>Создано</dt>
            <dd className="mono">{formatDateTime(selectedEntry.item.createdAt)}</dd>

            <dt>Изменено</dt>
            <dd className="mono">{formatDateTime(selectedEntry.item.updatedAt)}</dd>
          </dl>
        </div>
      )}
    </aside>
  );
}

function formatDateTime(value: string): string {
  return new Date(value).toLocaleString("ru-RU");
}

function formatDateRange(begin: string, end: string): string {
  const b = new Date(begin);
  const e = new Date(end);
  const sameDay =
    b.getFullYear() === e.getFullYear() &&
    b.getMonth() === e.getMonth() &&
    b.getDate() === e.getDate();
  const dateOpts: Intl.DateTimeFormatOptions = { day: "2-digit", month: "2-digit" };
  const timeOpts: Intl.DateTimeFormatOptions = { hour: "2-digit", minute: "2-digit" };
  const beginStr = `${b.toLocaleDateString("ru-RU", dateOpts)} ${b.toLocaleTimeString("ru-RU", timeOpts)}`;
  const endStr = sameDay
    ? b.toLocaleTimeString("ru-RU", timeOpts)
    : `${e.toLocaleDateString("ru-RU", dateOpts)} ${e.toLocaleTimeString("ru-RU", timeOpts)}`;
  return `${beginStr} – ${endStr}`;
}
