"use client";

/**
 * BuildingListingsDrawer — выезжающая справа панель с активными вторичными
 * объявлениями выбранного дома (GET /buildings/{id}/listings). Ссылка на
 * оригинал — через safeUrl (только http/https, защита от javascript:/data:).
 */
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";

import { safeUrl } from "@/lib/safeUrl";
import { useBuildingListings } from "@/lib/sale-share-api";
import type { BuildingListing, BuildingSaleShare } from "@/types/sale-share";
import { fmtPct, fmtRub, heatColor, sourceLabel } from "./saleShareUtils";

interface Props {
  building: BuildingSaleShare;
  onClose: () => void;
}

function roomsLabel(rooms: number | null): string {
  if (rooms === null) return "—";
  return rooms === 0 ? "студия" : `${rooms}-к`;
}

export function BuildingListingsDrawer({ building, onClose }: Props) {
  const { data, isPending, isError } = useBuildingListings(building.house_id);

  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);

  // Esc закрывает + initial focus на крестик, restore focus при размонтировании.
  const closeBtnRef = useRef<HTMLButtonElement>(null);
  const previouslyFocused = useRef<HTMLElement | null>(null);
  useEffect(() => {
    previouslyFocused.current = document.activeElement as HTMLElement | null;
    closeBtnRef.current?.focus();
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("keydown", onKey);
      previouslyFocused.current?.focus();
    };
  }, [onClose]);

  if (!mounted) return null;

  const listings: BuildingListing[] = data ?? [];

  return createPortal(
    <div className="ss-drawer-overlay" onClick={onClose}>
      <aside
        className="ss-drawer"
        role="dialog"
        aria-modal="true"
        aria-labelledby="ss-drawer-title"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="ss-drawer-head">
          <div style={{ minWidth: 0 }}>
            <div className="section-kicker">Объявления в продаже</div>
            <h2 id="ss-drawer-title" style={{ fontSize: 16 }}>
              {building.address ?? "Адрес не указан"}
            </h2>
            <div style={{ marginTop: 6, display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
              <span
                className="ss-pct"
                style={{ color: "#fff", background: heatColor(building.sale_share_pct) }}
              >
                {fmtPct(building.sale_share_pct)} в продаже
              </span>
              {building.active_secondary !== null && building.flat_count_effective !== null && (
                <span style={{ fontSize: 12, color: "var(--muted)" }}>
                  {building.active_secondary} из {building.flat_count_effective} квартир
                </span>
              )}
            </div>
          </div>
          <button
            ref={closeBtnRef}
            type="button"
            onClick={onClose}
            aria-label="Закрыть"
            className="ss-drawer-close"
          >
            ×
          </button>
        </header>

        <div className="ss-drawer-body">
          {isPending ? (
            <p style={{ color: "var(--muted)", padding: "24px 0", textAlign: "center" }}>
              Загрузка объявлений…
            </p>
          ) : isError ? (
            <p style={{ color: "var(--danger, #b3261e)", padding: "24px 0", textAlign: "center" }}>
              Не удалось загрузить объявления дома.
            </p>
          ) : listings.length === 0 ? (
            <p style={{ color: "var(--muted)", padding: "24px 0", textAlign: "center" }}>
              Активных вторичных объявлений по дому не найдено.
            </p>
          ) : (
            <ul className="ss-listing-list">
              {listings.map((l) => {
                const url = safeUrl(l.source_url);
                const floorTxt =
                  l.floor !== null
                    ? l.total_floors !== null
                      ? `этаж ${l.floor}/${l.total_floors}`
                      : `этаж ${l.floor}`
                    : null;
                const meta = [
                  roomsLabel(l.rooms),
                  l.area_m2 !== null ? `${l.area_m2.toFixed(1)} м²` : null,
                  floorTxt,
                ]
                  .filter(Boolean)
                  .join(" · ");
                return (
                  <li key={l.listing_id} className="ss-listing">
                    <div className="ss-listing-main">
                      <div className="ss-listing-price">
                        {l.price_rub !== null ? `${fmtRub(l.price_rub)} ₽` : "цена не указана"}
                      </div>
                      <div className="ss-listing-meta">{meta || "—"}</div>
                      <div className="ss-listing-sub">
                        {sourceLabel(l.source)}
                        {l.price_per_m2 !== null ? ` · ${fmtRub(l.price_per_m2)} ₽/м²` : ""}
                        {l.days_on_market !== null ? ` · ${l.days_on_market} дн в продаже` : ""}
                      </div>
                    </div>
                    {url && (
                      <a
                        href={url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="ss-listing-link"
                        aria-label="Открыть оригинал объявления"
                      >
                        <svg
                          width="15"
                          height="15"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          aria-hidden="true"
                        >
                          <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                          <polyline points="15 3 21 3 21 9" />
                          <line x1="10" y1="14" x2="21" y2="3" />
                        </svg>
                      </a>
                    )}
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      </aside>
    </div>,
    document.body,
  );
}
