import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useAlertHitContext } from "../../context/AlertHitContext";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
import type { CameraBlackBoardOptions, SightingType } from "../../types/types";
import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader";
import AlertItem from "./AlertItem";
import { faTrash } from "@fortawesome/free-solid-svg-icons";

const HistoryList = () => {
  const { state, dispatch, isLoading, error } = useAlertHitContext();
  const { mutation } = useCameraBlackboard();

  const handleDeleteClick = (alertItem: SightingType, idx?: number) => {
    dispatch({ type: "REMOVE", payload: alertItem });
    mutation.mutate({ operation: "POP", path: "alertHistory", value: idx });
  };

  const handleClearListClick = (listName: CameraBlackBoardOptions) => {
    dispatch({ type: "DELETE", payload: [] });
    mutation.mutate({
      operation: "DELETE",
      path: listName.path,
    });
  };

  return (
    <Card className="h-100">
      <CardHeader title="Alert History" />
      <button
        className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition md:w-[10%] mb-2"
        onClick={() => handleClearListClick({ path: "alertHistory" })}
      >
        Clear List
      </button>
      {isLoading && <p>Loading...</p>}
      {error && <p className="text-red-500">Error: {error.message}</p>}
      <div className="flex flex-col gap-1">
        {state?.alertList?.length > 0 ? (
          state?.alertList?.map((alertItem, index) => (
            <div key={index} className="flex flex-row space-x-2">
              <AlertItem item={alertItem} />
              <button onClick={() => handleDeleteClick(alertItem, index)}>
                <div className="p-4">
                  <FontAwesomeIcon icon={faTrash} size="2x" />
                </div>
              </button>
            </div>
          ))
        ) : (
          <p>No Alert results</p>
        )}
      </div>
    </Card>
  );
};

export default HistoryList;
