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

export default function SallerListing() {
  const dispatch = useDispatch<any>();
  const [refreshTrigger, setRefreshTrigger] = useState(false);
  const { sellerListData } = useSelector(
    (state: RootState) => state.sellerListDataReducer
  );

  const handleDeleteListing = async (id: number) => {
    try {
      const response = await dispatch(deleteListing({ id }));
      if (response?.payload?.success) {
        toast.success("Listing deleted successfully");
        dispatch(sellerGetList()); // 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(sellerGetList());
  }, [dispatch, refreshTrigger]);

  return (
    <>
      {sellerListData?.data?.length > 0 ? (
        <Results
          listData={sellerListData?.data}
          onDelete={handleDeleteListing}
          onRefresh={handleRefresh}
        />
      ) : (
        <div className="flex justify-center items-center lg:mt-20">
          <Image
            unoptimized
            src={listing}
            className="h-80"
            height={80}
            width={80}
            alt="No Listings Available"
          />
        </div>
      )}
    </>
  );
}
