import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { SightingType } from "../../types/types";
import { BLANK_IMG } from "../../utils/utils";
import NumberPlate from "../PlateStack/NumberPlate";
import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader";
import clsx from "clsx";
import { useSightingFeedContext } from "../../context/SightingFeedContext";
import SightingModal from "../SightingModal/SightingModal";
// import { useAlertHitContext } from "../../context/AlertHitContext";
import InfoBar from "./InfoBar";
import HotListImg from "/Hotlist_Hit.svg";

function useNow(tickMs = 1000) {
  const [, setNow] = useState(() => Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), tickMs);
    return () => clearInterval(id);
  }, [tickMs]);
  return undefined;
}

type SightingHistoryProps = {
  baseUrl?: string;
  entries?: number; // number of rows to show
  pollMs?: number; // poll frequency
  autoSelectLatest?: boolean;
  title: string;
  className: React.HTMLAttributes<HTMLDivElement> | string;
};

// /type SightingHistoryWidgetProps = React.HTMLAttributes<HTMLDivElement>;

export default function SightingHistoryWidget({
  className,
  title,
}: SightingHistoryProps) {
  useNow(1000);

  const {
    sightings,
    setSelectedSighting,
    setSightingModalOpen,
    isSightingModalOpen,
    selectedSighting,
  } = useSightingFeedContext();

  // const { dispatch } = useAlertHitContext();

  const hasAutoOpenedRef = useRef(false);

  const onRowClick = useCallback(
    (sighting: SightingType) => {
      if (!sighting) return;
      setSightingModalOpen(!isSightingModalOpen);
      setSelectedSighting(sighting);
    },
    [isSightingModalOpen, setSelectedSighting, setSightingModalOpen]
  );

  const rows = useMemo(
    () => sightings?.filter(Boolean) as SightingType[],
    [sightings]
  );

  // useEffect(() => {
  //   rows?.forEach((obj) => {
  //     const isNPEDHit = obj?.metadata?.npedJSON?.status_code === 404;

  //     if (isNPEDHit) {
  //       dispatch({
  //         type: "ADD",
  //         payload: obj,
  //       });
  //     }
  //   });
  // }, [rows, dispatch]);

  useEffect(() => {
    if (hasAutoOpenedRef.current) return;
    const firstHot = rows?.find(
      (r) => r?.metadata?.hotlistMatches?.Hotlist0 === true
    );
    if (firstHot) {
      setSelectedSighting(firstHot);
      setSightingModalOpen(true);
      hasAutoOpenedRef.current = true; // prevent future auto-opens
    }
  }, [rows, setSelectedSighting, setSightingModalOpen]);

  const handleClose = () => {
    setSightingModalOpen(false);
  };
  return (
    <>
      <Card className={clsx("overflow-y-auto h-100", className)}>
        <CardHeader title={title} />
        <div className="flex flex-col gap-3 ">
          {/* Rows */}
          <div className="flex flex-col">
            {rows?.map((obj, idx) => {
              // const isNPEDHit = obj?.metadata?.npedJSON?.status_code === 404;
              const motionAway = (obj?.motion ?? "").toUpperCase() === "AWAY";
              const primaryIsColour = obj?.srcCam === 1;
              const secondaryMissing = (obj?.vrmSecondary ?? "") === "";
              const isHotListHit =
                obj?.metadata?.hotlistMatches?.Hotlist0 === true;
              return (
                <div
                  key={idx}
                  className={`border border-neutral-700 rounded-md mb-2 p-2 cursor-pointer`}
                  onClick={() => onRowClick(obj)}
                >
                  <InfoBar obj={obj} />
                  {/* Patch row */}
                  <div
                    className={`flex items-center gap-3 mt-2 justify-between`}
                  >
                    <div
                      className={`border p-1 ${
                        primaryIsColour ? "ring-2 ring-lime-400" : ""
                      } ${
                        secondaryMissing && primaryIsColour
                          ? "opacity-30 grayscale"
                          : ""
                      }`}
                    >
                      <img
                        src={obj?.plateUrlColour || BLANK_IMG}
                        height={48}
                        alt="colour patch"
                        className={primaryIsColour ? "" : "opacity-60"}
                      />
                    </div>
                    {isHotListHit && (
                      <img
                        src={HotListImg}
                        alt="hotlistHit"
                        className="h-20 object-contain rounded-md"
                      />
                    )}
                    <NumberPlate motion={motionAway} vrm={obj?.vrm} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </Card>
      <SightingModal
        isSightingModalOpen={isSightingModalOpen}
        handleClose={handleClose}
        sighting={selectedSighting}
      />
    </>
  );
}
