import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader";
import { useIntegrationsContext } from "../../context/IntegrationsContext";
import type { ReducedSightingType } from "../../types/types";
import { toast } from "sonner";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFloppyDisk, faPause, faPlay, faStop, faArrowRotateRight } from "@fortawesome/free-solid-svg-icons";
import VehicleSessionItem from "../UI/VehicleSessionItem";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";

const SessionCard = () => {
  const { state, dispatch } = useIntegrationsContext();
  const { mutation } = useCameraBlackboard();

  const sessionStarted = state.sessionStarted;
  const sessionPaused = state.sessionPaused;
  const sessionList = state.sessionList;

  const sightings = [...new Map(sessionList?.map((vehicle) => [vehicle.vrm, vehicle]))];

  const dedupedSightings = sightings.map((sighting) => sighting[1]);

  const vehicles = dedupedSightings.reduce<Record<string, ReducedSightingType[]>>(
    (acc, item) => {
      const hotlisthit = Object.values(item.metadata?.hotlistMatches ?? {}).includes(true);
      if (item.metadata?.npedJSON["NPED CATEGORY"] === "A") acc.npedCatA.push(item);
      if (item.metadata?.npedJSON["NPED CATEGORY"] === "B") acc.npedCatB.push(item);
      if (item.metadata?.npedJSON["NPED CATEGORY"] === "C") acc.npedCatC.push(item);
      if (item.metadata?.npedJSON["NPED CATEGORY"] === "D") acc.npedCatD.push(item);
      if (item.metadata?.npedJSON["TAX STATUS"] === false) acc.notTaxed.push(item);
      if (item.metadata?.npedJSON["MOT STATUS"] === false) acc.notMOT.push(item);
      if (hotlisthit) acc.hotlistHit.push(item);
      acc.vehicles.push(item);
      return acc;
    },
    {
      npedCatA: [],
      npedCatB: [],
      npedCatC: [],
      npedCatD: [],
      notTaxed: [],
      notMOT: [],
      hotlistHit: [],
      vehicles: [],
    }
  );

  const handleStartClick = () => {
    dispatch({ type: "SESSIONSTART", payload: !sessionStarted });
    dispatch({ type: "SESSIONPAUSE", payload: false });
    toast(`${sessionStarted ? "Vehicle tracking session ended" : "Vehicle tracking session started"}`);
  };

  const handlepauseClick = () => {
    dispatch({ type: "SESSIONPAUSE", payload: !sessionPaused });
    toast(`${sessionStarted ? "Vehicle tracking session paused" : "Vehicle tracking session resumed"}`);
  };

  const handleSaveCick = async () => {
    const result = await mutation.mutateAsync({
      operation: "INSERT",
      path: "sessionStats",
      value: dedupedSightings,
    });
    await mutation.mutateAsync({
      operation: "SAVE",
      path: "",
      value: null,
    });
    if (result.reason === "OK") toast.success("Session saved");
  };

  const handleRestartClick = async () => {
    const result = await mutation.mutateAsync({
      operation: "INSERT",
      path: "sessionStats",
      value: [],
    });
    await mutation.mutateAsync({
      operation: "SAVE",
      path: "",
      value: null,
    });
    if (result.reason === "OK") toast.success("Session restarted");
    dispatch({ type: "SESSIONRESTART", payload: [] });
  };

  return (
    <Card className="p-4 col-span-3">
      <CardHeader title="Session" />
      <div className="flex flex-col gap-4 px-3">
        <button
          className={`${sessionStarted ? "bg-red-600" : "bg-[#26B170]"} text-white px-4 py-2 rounded ${
            sessionStarted ? "hover:bg-red-700" : "hover:bg-green-700"
          }  transition w-full`}
          onClick={handleStartClick}
        >
          <div className="flex flex-row gap-3 items-center justify-self-center">
            <FontAwesomeIcon icon={sessionStarted ? faStop : faPlay} />
            <p>{sessionStarted ? "End Session" : "Start Session"}</p>
          </div>
        </button>
        {sessionStarted && (
          <button
            className={`bg-none text-white px-4 py-2 rounded transition w-full border border-gray-500 hover:bg-gray-500 hover:text-gray-900`}
            onClick={handleRestartClick}
          >
            <div className="flex flex-row gap-3 items-center justify-self-center">
              <FontAwesomeIcon icon={faArrowRotateRight} />
              <p>Restart Session</p>
            </div>
          </button>
        )}
        <div className="flex flex-col lg:flex-row gap-5">
          {sessionStarted && (
            <button
              className={`bg-blue-600 text-white px-4 py-2 rounded transition w-full lg:w-[50%]`}
              onClick={handleSaveCick}
            >
              <div className="flex flex-row gap-3 items-center justify-self-center">
                <FontAwesomeIcon icon={faFloppyDisk} />
                <p>Save session</p>
              </div>
            </button>
          )}
          {sessionStarted && (
            <button
              className={`bg-gray-300 text-gray-800 px-4 py-2 rounded transition w-full lg:w-[50%]`}
              onClick={handlepauseClick}
            >
              <div className="flex flex-row gap-3 items-center justify-self-center">
                <FontAwesomeIcon icon={sessionPaused ? faPlay : faPause} />
                <p>{sessionPaused ? "Resume session" : "Pause session"}</p>
              </div>
            </button>
          )}
        </div>

        <ul className="text-white space-y-2">
          <VehicleSessionItem
            sessionNumber={vehicles.vehicles.length}
            textColour="text-green-400"
            vehicleTag={"Number of Vehicles sightings:"}
          />
          <VehicleSessionItem
            sessionNumber={vehicles.notTaxed.length}
            textColour="text-amber-400"
            vehicleTag={"Vehicles without Tax:"}
          />
          <VehicleSessionItem
            sessionNumber={vehicles.notMOT.length}
            textColour="text-red-500"
            vehicleTag={"Vehicles without MOT:"}
          />
          <VehicleSessionItem
            sessionNumber={vehicles.hotlistHit.length}
            textColour="text-blue-400"
            vehicleTag={"Vehicles on Hotlists:"}
          />
          <VehicleSessionItem
            sessionNumber={vehicles.npedCatA.length}
            textColour="text-gray-300"
            vehicleTag={"Vehicles with NPED Cat A:"}
          />
          <VehicleSessionItem
            sessionNumber={vehicles.npedCatB.length}
            textColour="text-gray-300"
            vehicleTag={"Vehicles with NPED Cat B:"}
          />
          <VehicleSessionItem
            sessionNumber={vehicles.npedCatC.length}
            textColour="text-gray-300"
            vehicleTag={"Vehicles with NPED Cat C:"}
          />
          <VehicleSessionItem
            sessionNumber={vehicles.npedCatD.length}
            textColour="text-gray-300"
            vehicleTag={"Vehicles with NPED Cat D:"}
          />
        </ul>
      </div>
    </Card>
  );
};

export default SessionCard;
