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 HotListImg from "/Hotlist_Hit.svg";
import NPED_CAT_A from "/NPED_Cat_A.svg";
import NPED_CAT_B from "/NPED_Cat_B.svg";
import NPED_CAT_C from "/NPED_Cat_C.svg";
import popup from "../../assets/sounds/ui/popup_open.mp3";
import { useSound } from "react-sounds";
import { useNPEDContext } from "../../context/NPEDUserContext";

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

type SightingHistoryProps = {
  baseUrl?: string;
  entries?: number;
  pollMs?: number;
  autoSelectLatest?: boolean;
  title: string;
  className?: string;
};

export default function SightingHistoryWidget({
  className,
  title,
}: SightingHistoryProps) {
  useNow(1000);
  const { play } = useSound(popup);
  const {
    sightings,
    setSelectedSighting,
    setSightingModalOpen,
    isSightingModalOpen,
    selectedSighting,
    mostRecent,
  } = useSightingFeedContext();

  const { dispatch } = useAlertHitContext();
  const { sessionStarted, setSessionList, sessionList } = useNPEDContext();

  useEffect(() => {
    if (sessionStarted) {
      if (!mostRecent) return;
      setSessionList([...sessionList, mostRecent]);
    }
  }, [mostRecent, sessionStarted, setSessionList]);

  const hasAutoOpenedRef = useRef(false);

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

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

  useEffect(() => {
    rows?.forEach((obj) => {
      const isNPEDHitA = obj?.metadata?.npedJSON?.["NPED CATEGORY"] === "A";
      const isNPEDHitB = obj?.metadata?.npedJSON?.["NPED CATEGORY"] === "B";
      const isNPEDHitC = obj?.metadata?.npedJSON?.["NPED CATEGORY"] === "C";

      if (isNPEDHitA || isNPEDHitB || isNPEDHitC) {
        dispatch({
          type: "ADD",
          payload: obj,
        });
      }
    });
  }, [dispatch, rows]);

  useEffect(() => {
    if (hasAutoOpenedRef.current) return;
    const firstHot = rows?.find((r) => {
      const isHotListHit = r?.metadata?.hotlistMatches?.Hotlist0 === true;
      const isNPEDHitA = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "A";
      const isNPEDHitB = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "B";
      const isNPEDHitC = r?.metadata?.npedJSON?.["NPED CATEGORY"] === "C";
      return isNPEDHitA || isNPEDHitB || isNPEDHitC || isHotListHit;
    });
    if (firstHot) {
      setSelectedSighting(firstHot);
      play();
      setSightingModalOpen(true);
      hasAutoOpenedRef.current = true;
    }
  }, [play, rows, setSelectedSighting, setSightingModalOpen]);

  const handleClose = () => {
    setSightingModalOpen(false);
  };
  return (
    <>
      <Card
        className={clsx(
          "overflow-y-auto min-h-[40vh] md:min-h-[60vh] max-h-[80vh] lg:w-[40%] p-4",
          className
        )}
      >
        <CardHeader title={title} />
        <div className="flex flex-col gap-3 ">
          {/* Rows */}
          <div className="flex flex-col">
            {rows?.map((obj) => {
              const isNPEDHitA =
                obj?.metadata?.npedJSON?.["NPED CATEGORY"] === "A";
              const isNPEDHitB =
                obj?.metadata?.npedJSON?.["NPED CATEGORY"] === "B";
              const isNPEDHitC =
                obj?.metadata?.npedJSON?.["NPED CATEGORY"] === "C";
              const isNPEDHitD =
                obj?.metadata?.npedJSON?.["NPED CATEGORY"] === "D";
              const motionAway = (obj?.motion ?? "").toUpperCase() === "AWAY";
              const isHotListHit =
                obj?.metadata?.hotlistMatches?.Hotlist0 === true;
              return (
                <div
                  key={obj.ref}
                  className={`border border-gray-700 rounded-md mb-2 p-2 cursor-pointer `}
                  onClick={() => onRowClick(obj)}
                >
                  <div
                    className={`flex items-center gap-3 mt-2 justify-between ${
                      isNPEDHitD ? " border-amber-600" : ""
                    }`}
                  >
                    <div className={`border p-1 `}>
                      <img
                        src={obj?.plateUrlColour || BLANK_IMG}
                        height={48}
                        width={200}
                        alt="colour patch"
                      />
                    </div>
                    {isHotListHit && (
                      <img
                        src={HotListImg}
                        alt="hotlistHit"
                        className="h-20 object-contain rounded-md"
                      />
                    )}
                    {isNPEDHitA && (
                      <img
                        src={NPED_CAT_A}
                        alt="hotlistHit"
                        className="h-20 object-contain rounded-md"
                      />
                    )}
                    {isNPEDHitB && (
                      <img
                        src={NPED_CAT_B}
                        alt="hotlistHit"
                        className="h-20 object-contain rounded-md"
                      />
                    )}
                    {isNPEDHitC && (
                      <img
                        src={NPED_CAT_C}
                        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}
      />
    </>
  );
}
