"use client";

import Link from "next/link";
import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Clock, MapPin } from "lucide-react";
import { useRecentParcels } from "@/lib/site-finder-api";

const MAX_SHOWN = 5;

export function RecentParcels() {
  const queryClient = useQueryClient();
  const { data: parcels, isLoading } = useRecentParcels();

  // The visit is written to localStorage in page.handleParcelOpen, but the
  // QueryClient survives client-side navigation and useRecentParcels has a 60s
  // staleTime, so returning to /site-finder otherwise shows a stale snapshot
  // without the just-opened parcel. Invalidate on mount to refetch the latest
  // localStorage state (the component re-mounts on each return to the page).
  useEffect(() => {
    void queryClient.invalidateQueries({ queryKey: ["recent-parcels"] });
  }, [queryClient]);

  if (isLoading) {
    return (
      <div
        style={{
          background: "var(--bg-card)",
          border: "1px solid var(--border-card)",
          borderRadius: 12,
          padding: "12px 16px",
        }}
      >
        <div
          style={{
            height: 14,
            background: "var(--bg-card-alt)",
            borderRadius: 4,
            marginBottom: 12,
            width: 120,
          }}
        />
        {[1, 2, 3].map((i) => (
          <div
            key={i}
            style={{
              height: 40,
              background: "var(--bg-card-alt)",
              borderRadius: 6,
              marginBottom: 6,
            }}
          />
        ))}
      </div>
    );
  }

  const shown = (parcels ?? []).slice(0, MAX_SHOWN);

  if (shown.length === 0) {
    return (
      <div
        style={{
          background: "var(--bg-card)",
          border: "1px solid var(--border-card)",
          borderRadius: 12,
          padding: "12px 16px",
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 6,
            marginBottom: 8,
          }}
        >
          <Clock
            size={14}
            strokeWidth={1.5}
            style={{ color: "var(--fg-secondary)" }}
          />
          <span
            style={{
              fontSize: 11,
              fontWeight: 500,
              textTransform: "uppercase",
              letterSpacing: "0.04em",
              color: "var(--fg-secondary)",
            }}
          >
            Недавние участки
          </span>
        </div>
        <p
          style={{
            fontSize: 12,
            color: "var(--fg-tertiary)",
            margin: 0,
          }}
        >
          История просмотров пуста
        </p>
      </div>
    );
  }

  return (
    <div
      style={{
        background: "var(--bg-card)",
        border: "1px solid var(--border-card)",
        borderRadius: 12,
        overflow: "hidden",
      }}
    >
      {/* Header */}
      <div
        style={{
          padding: "10px 14px 8px",
          borderBottom: "1px solid var(--border-soft)",
          display: "flex",
          alignItems: "center",
          gap: 6,
        }}
      >
        <Clock
          size={14}
          strokeWidth={1.5}
          style={{ color: "var(--fg-secondary)" }}
        />
        <span
          style={{
            fontSize: 11,
            fontWeight: 500,
            textTransform: "uppercase",
            letterSpacing: "0.04em",
            color: "var(--fg-secondary)",
          }}
        >
          Недавние участки
        </span>
      </div>

      {/* List */}
      <div style={{ display: "flex", flexDirection: "column" }}>
        {shown.map((parcel, idx) => (
          <Link
            key={parcel.cad_num}
            href={`/site-finder/analysis/${encodeURIComponent(parcel.cad_num)}`}
            style={{
              display: "flex",
              alignItems: "flex-start",
              gap: 8,
              padding: "10px 14px",
              textDecoration: "none",
              borderBottom:
                idx < shown.length - 1
                  ? "1px solid var(--border-soft)"
                  : "none",
              transition: "background 0.1s",
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLElement).style.background =
                "var(--bg-card-alt)";
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLElement).style.background = "transparent";
            }}
          >
            <MapPin
              size={14}
              strokeWidth={1.5}
              style={{
                color: "var(--fg-tertiary)",
                marginTop: 2,
                flexShrink: 0,
              }}
            />
            <div style={{ minWidth: 0 }}>
              <div
                style={{
                  fontSize: 12,
                  fontWeight: 500,
                  color: "var(--fg-primary)",
                  fontVariantNumeric: "tabular-nums",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                }}
              >
                {parcel.cad_num}
              </div>
              <div
                style={{
                  fontSize: 11,
                  color: "var(--fg-tertiary)",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                  marginTop: 1,
                }}
              >
                {parcel.district}
                {parcel.area_ha ? ` · ${parcel.area_ha.toFixed(2)} га` : ""}
              </div>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
