import { useEffect, useState } from "react";
import { SavedDrafts, deleteListing } from "../../api/api";
import { RootState } from "../../store";
import { useDispatch, useSelector } from "react-redux";
import Results from "./SallerResults";
import Listing from "../../assets/Nolisting.png";
import { toast } from "react-toastify";
import Image from "next/image";

const SavedDraft = () => {
  const dispatch = useDispatch<any>();
  const [refreshTrigger, setRefreshTrigger] = useState(false);
  const { savedDraftListing } = useSelector(
    (state: RootState) => state.DraftReducer
  );

  const handleDeleteListing = async (id: number) => {
    try {
      const response = await dispatch(deleteListing({ id }));
      if (response?.payload?.success) {
        toast.success("Draft deleted successfully");
        dispatch(SavedDrafts()); // Refresh list after deletion
      } else {
        toast.error(response?.payload?.error || "Failed to delete listing");
      }
    } catch (error: any) {
      toast.error(error?.message || "Failed to delete listing");
    }
  };
  const handleRefresh = () => {
    setRefreshTrigger((prev) => !prev); // toggles the value to trigger useEffect
  };

  useEffect(() => {
    dispatch(SavedDrafts());
  }, [dispatch, refreshTrigger]);

  return (
    <>
      {/* {savedDraftListing?.data?.listing && "testing"} */}
      {savedDraftListing?.data?.listings?.length > 0 ? (
        <Results
          listData={savedDraftListing?.data?.listings}
          onDelete={handleDeleteListing}
          onRefresh={handleRefresh}
        />
      ) : (
        <div className="flex justify-center items-center  lg:mt-20">
          <Image
            unoptimized
            src={Listing}
            alt="image"
            height={80}
            width={80}
            className="h-80"
          />
        </div>
      )}
    </>
  );
};

export default SavedDraft;
