"use client";
import { useEstimateHouseAnalytics, useEstimateSellTimeSensitivity } from "@/lib/trade-in-api";
import { PriceHistoryChart } from "./PriceHistoryChart";
import { HouseAnalyticsKpiRow } from "./HouseAnalyticsKpiRow";
import { RecentSoldList } from "./RecentSoldList";
import { SellTimeSensitivity } from "./SellTimeSensitivity";

type Props = { estimateId: string };

export function HouseAnalyticsSection({ estimateId }: Props) {
  const { data, isPending, isError } = useEstimateHouseAnalytics(estimateId);
  const sellTime = useEstimateSellTimeSensitivity(estimateId);

  if (isPending || isError || !data) return null;
  if (data.kpi.total_lots === 0) return null;

  return (
    <section style={{ marginTop: 16, minWidth: 0, maxWidth: "100%" }}>
      <header
        style={{
          marginBottom: 12,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "baseline",
        }}
      >
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>
          Аналитика дома
        </h3>
        <small style={{ color: "var(--muted, #6b7280)" }}>
          {data.kpi.total_lots} объявлений
          {data.radius_m > 0
            ? ` · в радиусе ${data.radius_m}м`
            : " · в этом доме"}
        </small>
      </header>
      <HouseAnalyticsKpiRow kpi={data.kpi} />
      {sellTime.data && <SellTimeSensitivity data={sellTime.data} />}
      {data.price_history.length >= 2 && (
        <PriceHistoryChart points={data.price_history} />
      )}
      {data.recent_sold.length > 0 && (
        <RecentSoldList items={data.recent_sold} />
      )}
    </section>
  );
}
