import { useRef, useEffect, useState } from "react";
import { useWindowVirtualizer } from "@tanstack/react-virtual";
import type { FlightData } from "./types";
import FlightCard from "./FlightCard";
import FlightsEmptyState from "./FlightsEmptyState";

interface FlightsListProps {
  flights: FlightData[];
  isLoading?: boolean;
}

export default function FlightsList({
  flights,
  isLoading = false,
}: FlightsListProps) {
  if (isLoading) {
    return (
      <div className="d-flex flex-column gap-3">
        {Array.from({ length: 6 }).map((_, i) => (
          <div
            key={i}
            className="card rounded-start-3 w-100 bgColor-white p-3 m-0"
          >
            <div className="row listing-row g-0">
              <div className="col-md-10">
                <div className="row">
                  <div className="col-md-2 d-flex flex-column align-items-center gap-2 pt-2">
                    <div
                      className="skeleton-box rounded-2"
                      style={{
                        width: 40,
                        height: 40,
                        backgroundColor: "#dee2e6",
                      }}
                    ></div>
                    <div
                      className="skeleton-box"
                      style={{
                        width: 60,
                        height: 12,
                        backgroundColor: "#dee2e6",
                        borderRadius: 4,
                      }}
                    ></div>
                  </div>
                  <div className="col-md-10 p-0 pe-md-5">
                    <div className="d-flex align-items-center justify-content-between pb-3 border-bottom mb-2">
                      <div
                        className="skeleton-box"
                        style={{
                          width: 60,
                          height: 28,
                          backgroundColor: "#dee2e6",
                          borderRadius: 4,
                        }}
                      ></div>
                      <div
                        className="flex-grow-1 mx-3 skeleton-box"
                        style={{ height: 2, backgroundColor: "#dee2e6" }}
                      ></div>
                      <div
                        className="skeleton-box"
                        style={{
                          width: 60,
                          height: 28,
                          backgroundColor: "#dee2e6",
                          borderRadius: 4,
                        }}
                      ></div>
                    </div>
                    <div
                      className="skeleton-box"
                      style={{
                        width: 120,
                        height: 14,
                        backgroundColor: "#dee2e6",
                        borderRadius: 4,
                      }}
                    ></div>
                  </div>
                </div>
              </div>
              <div className="col-md-2 border-start d-flex flex-column align-items-end gap-2 ps-2">
                <div
                  className="skeleton-box"
                  style={{
                    width: 70,
                    height: 32,
                    backgroundColor: "#dee2e6",
                    borderRadius: 4,
                  }}
                ></div>
                <div
                  className="skeleton-box"
                  style={{
                    width: 90,
                    height: 36,
                    backgroundColor: "#dee2e6",
                    borderRadius: 6,
                  }}
                ></div>
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  }

  if (flights.length === 0) {
    return <FlightsEmptyState />;
  }

  return <VirtualFlightList flights={flights} />;
}

/** Separate component so the virtualizer hook only mounts when there are results */
function VirtualFlightList({ flights }: { flights: FlightData[] }) {
  const listRef = useRef<HTMLDivElement>(null);
  const [scrollMargin, setScrollMargin] = useState(0);

  // scrollMargin = distance from page top to the list. Measured on mount AND on
  // resize — if it goes stale (fonts load, the results header wraps, an error
  // line appears) every virtual row is offset by the drift, which shows up as
  // flicker/jump while scrolling.
  useEffect(() => {
    const measure = () => {
      if (listRef.current) setScrollMargin(listRef.current.offsetTop);
    };
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, []);

  // Round-trip cards stack a second (Onward/Return) leg, so they render noticeably
  // taller — measureElement corrects the real height per item either way, this just
  // keeps the very first paint/scroll-position estimate close enough to avoid a jump.
  const isRoundTrip = flights[0]?.inbound != null;

  const virtualizer = useWindowVirtualizer({
    count: flights.length,
    // Card height ~190px (p-3 top/bottom + route row + amenity row);
    // round-trip roughly doubles the route-row content (Onward + Return legs).
    estimateSize: () => (isRoundTrip ? 350 : 190),
    // Bootstrap gap-3 between cards, handled by the virtualizer so measureElement
    // reads an accurate per-row height (margins are NOT in getBoundingClientRect,
    // so a marginBottom here would make every row measure 16px short — cumulative
    // drift is the main fast-scroll flicker cause).
    gap: 16,
    // Generous overscan so a fast fling has rows already rendered above/below the
    // viewport instead of briefly painting blank.
    overscan: 10,
    scrollMargin,
  });

  const items = virtualizer.getVirtualItems();

  // Window-virtualizer layout: a spacer of the full list height with each row
  // absolutely positioned. No flex, no per-row margins — both fight
  // measureElement's ResizeObserver and cause jitter. Rows are offset with `top`,
  // NOT `transform` — a `transform` on the row would make it a containing block
  // for `position: fixed`, which breaks the (non-portalled) fares/details modals
  // rendered inside each FlightCard.
  return (
    <div ref={listRef}>
      <div
        style={{
          height: virtualizer.getTotalSize(),
          position: "relative",
          width: "100%",
        }}
      >
        {items.map((virtualRow) => (
          <div
            key={virtualRow.key}
            data-index={virtualRow.index}
            ref={virtualizer.measureElement}
            style={{
              position: "absolute",
              top: virtualRow.start - virtualizer.options.scrollMargin,
              left: 0,
              width: "100%",
            }}
          >
            <FlightCard
              flight={flights[virtualRow.index]}
              index={virtualRow.index}
            />
          </div>
        ))}
      </div>
    </div>
  );
}
