"use client";

import { useState } from "react";

import type { AnalogLot } from "@/types/trade-in";

/** XSS prevention: only allow http/https/relative src */
function safeImgSrc(url: string | null): string | null {
  if (!url) return null;
  if (
    url.startsWith("https://") ||
    url.startsWith("http://") ||
    url.startsWith("/")
  ) {
    return url;
  }
  return null;
}

function fmtRub(value: number): string {
  return value.toLocaleString("ru-RU", {
    style: "currency",
    currency: "RUB",
    maximumFractionDigits: 0,
  });
}

function fmtDate(iso: string | null): string {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("ru-RU", {
    day: "2-digit",
    month: "2-digit",
    year: "2-digit",
  });
}

type SortKey = "price_rub" | "price_per_m2" | "days_on_market";

interface Props {
  rows: AnalogLot[];
  emptyLabel?: string;
}

export function AnalogsTable({
  rows,
  emptyLabel = "Нет аналогов в радиусе 1 км",
}: Props) {
  const [sortKey, setSortKey] = useState<SortKey>("price_rub");
  const [sortAsc, setSortAsc] = useState(true);

  if (rows.length === 0) {
    return (
      <div
        style={{
          padding: "20px 0",
          color: "#9ca3af",
          fontSize: 14,
          textAlign: "center",
        }}
      >
        {emptyLabel}
      </div>
    );
  }

  const sorted = [...rows].sort((a, b) => {
    const av = a[sortKey];
    const bv = b[sortKey];
    // null ('неизвестно') всегда в конце, независимо от направления
    if (av === null) return bv === null ? 0 : 1;
    if (bv === null) return -1;
    return sortAsc ? av - bv : bv - av;
  });

  function handleSort(key: SortKey) {
    if (sortKey === key) {
      setSortAsc((prev) => !prev);
    } else {
      setSortKey(key);
      setSortAsc(true);
    }
  }

  function SortIcon({ col }: { col: SortKey }) {
    if (sortKey !== col) return null;
    return sortAsc ? (
      <svg
        width="11"
        height="11"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        style={{ display: "inline", marginLeft: 2, verticalAlign: "middle" }}
        aria-hidden="true"
      >
        <polyline points="18 15 12 9 6 15" />
      </svg>
    ) : (
      <svg
        width="11"
        height="11"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        style={{ display: "inline", marginLeft: 2, verticalAlign: "middle" }}
        aria-hidden="true"
      >
        <polyline points="6 9 12 15 18 9" />
      </svg>
    );
  }

  const thStyle: React.CSSProperties = {
    padding: "7px 8px",
    fontSize: 11,
    color: "#5b6066",
    textTransform: "uppercase",
    letterSpacing: "0.04em",
    fontWeight: 600,
    borderBottom: "1px solid #e6e8ec",
    textAlign: "left",
    whiteSpace: "nowrap",
    background: "#f9fafb",
  };
  const tdStyle: React.CSSProperties = {
    padding: "8px 8px",
    fontSize: 13,
    color: "#1a1d23",
    borderBottom: "1px solid #f3f4f6",
    verticalAlign: "middle",
  };
  const numTd: React.CSSProperties = {
    ...tdStyle,
    fontVariantNumeric: "tabular-nums",
    textAlign: "right",
  };
  const sortableTh = (col: SortKey): React.CSSProperties => ({
    ...thStyle,
    cursor: "pointer",
    userSelect: "none",
    color: sortKey === col ? "#1d4ed8" : "#5b6066",
  });

  return (
    <div style={{ overflowX: "auto" }}>
      <table
        style={{
          width: "100%",
          borderCollapse: "collapse",
          fontSize: 13,
        }}
      >
        <thead>
          <tr>
            <th style={thStyle}>Фото</th>
            <th style={thStyle}>Адрес</th>
            <th style={{ ...thStyle, textAlign: "right" }}>м²</th>
            <th style={{ ...thStyle, textAlign: "right" }}>Комн.</th>
            <th style={{ ...thStyle, textAlign: "right" }}>Этаж</th>
            <th
              style={sortableTh("price_rub")}
              onClick={() => handleSort("price_rub")}
            >
              Цена ₽ <SortIcon col="price_rub" />
            </th>
            <th
              style={sortableTh("price_per_m2")}
              onClick={() => handleSort("price_per_m2")}
            >
              ₽/м² <SortIcon col="price_per_m2" />
            </th>
            <th
              style={sortableTh("days_on_market")}
              onClick={() => handleSort("days_on_market")}
            >
              Дней <SortIcon col="days_on_market" />
            </th>
          </tr>
        </thead>
        <tbody>
          {sorted.map((row, i) => {
            const imgSrc = safeImgSrc(row.photo_url);
            return (
              <tr
                key={i}
                style={{ background: i % 2 === 0 ? "#fff" : "#fafafa" }}
              >
                <td style={tdStyle}>
                  {imgSrc ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={imgSrc}
                      alt="фото"
                      width={48}
                      height={36}
                      style={{
                        objectFit: "cover",
                        borderRadius: 4,
                        display: "block",
                      }}
                    />
                  ) : (
                    <div
                      style={{
                        width: 48,
                        height: 36,
                        background: "#f3f4f6",
                        borderRadius: 4,
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                      }}
                    >
                      <svg
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="#9ca3af"
                        strokeWidth="1.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        aria-hidden="true"
                      >
                        <rect
                          x="3"
                          y="3"
                          width="18"
                          height="18"
                          rx="2"
                          ry="2"
                        />
                        <circle cx="8.5" cy="8.5" r="1.5" />
                        <polyline points="21 15 16 10 5 21" />
                      </svg>
                    </div>
                  )}
                </td>
                <td style={{ ...tdStyle, maxWidth: 200 }}>
                  <span
                    title={row.address}
                    style={{
                      display: "block",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      whiteSpace: "nowrap",
                    }}
                  >
                    {row.address}
                  </span>
                  {row.listing_date && (
                    <span style={{ fontSize: 11, color: "#9ca3af" }}>
                      {fmtDate(row.listing_date)}
                    </span>
                  )}
                </td>
                <td style={{ ...numTd }}>{row.area_m2.toFixed(1)}</td>
                <td style={{ ...numTd }}>
                  {row.rooms === 0 ? "ст." : row.rooms}
                </td>
                <td style={{ ...numTd }}>
                  {row.floor !== null && row.total_floors !== null
                    ? `${row.floor}/${row.total_floors}`
                    : (row.floor ?? "—")}
                </td>
                <td style={{ ...numTd }}>{fmtRub(row.price_rub)}</td>
                <td style={{ ...numTd }}>{fmtRub(row.price_per_m2)}</td>
                <td style={{ ...numTd }}>
                  {row.days_on_market !== null ? row.days_on_market : "—"}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
