import { useCallback, useEffect, useMemo, useState } from "react";
import type { SightingType, SightingWidgetType } from "../../types/types";
import { BLANK_IMG, capitalize, formatAge } 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";

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 onRowClick = useCallback(
    (sighting: SightingType | SightingWidgetType) => {
      if (!sighting) return;
      setSightingModalOpen(!isSightingModalOpen);
      setSelectedSighting(sighting);
    },
    [isSightingModalOpen, setSelectedSighting, setSightingModalOpen]
  );
  const rows = useMemo(
    () => sightings?.filter(Boolean) as SightingWidgetType[],
    [sightings]
  );
  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 ?? "") === "";
              return (
                <div
                  key={idx}
                  className={`border border-neutral-700 rounded-md mb-2 p-2 cursor-pointer`}
                  onClick={() => onRowClick(obj)}
                >
                  {/* Info bar */}
                  <div className="flex items-center gap-3 text-xs bg-neutral-900 px-2 py-1 rounded justify-between">
                    <div className="flex items-center gap-3 text-xs">
                      {" "}
                      <div className="min-w-14">
                        CH: {obj ? obj.charHeight : "—"}
                      </div>
                      <div className="min-w-14">
                        Seen: {obj ? obj.seenCount : "—"}
                      </div>
                      <div className="min-w-20">
                        {obj ? capitalize(obj.motion) : "—"}
                      </div>
                      <div className="min-w-14 opacity-80">
                        {obj ? formatAge(obj.timeStampMillis) : "—"}
                      </div>
                    </div>

                    <div className="min-w-14 opacity-80 ">
                      {isNPEDHit ? (
                        <span className="text-red-500 font-semibold">
                          NPED HIT
                        </span>
                      ) : (
                        ""
                      )}
                    </div>
                  </div>

                  {/* Patch row */}
                  <div
                    className={`flex items-center gap-3 mt-2
                  ${isNPEDHit ? "border border-red-600" : ""}
                  `}
                  >
                    <div
                      className={`border p-1 ${
                        primaryIsColour ? "" : "ring-2 ring-lime-400"
                      } ${!obj ? "opacity-30" : ""}`}
                    >
                      <img
                        src={obj?.plateUrlInfrared || BLANK_IMG}
                        height={48}
                        alt="infrared patch"
                        className={!primaryIsColour ? "" : "opacity-60"}
                      />
                    </div>
                    <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>
                    <NumberPlate motion={motionAway} vrm={obj?.vrm} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </Card>
      <SightingModal
        isSightingModalOpen={isSightingModalOpen}
        handleClose={handleClose}
        sighting={selectedSighting}
      />
    </>
  );
}
