import apiInterceptor from "@/interceptor/interceptor";
import Cookies from "js-cookie";
import Image from "next/image";
import {Image as AntImage} from 'antd'
import Link from "next/link";
import React, { useEffect, useState } from "react";
import { userActivity } from "@/components/commonFunctions/userActivity";
import jwt from "jsonwebtoken";


export default function BannerView() {
  const token: any = Cookies.get("jazz_admin_token");

  const decodedToken = jwt.decode(token);

  const userId = decodedToken ? decodedToken.sub : null;
  const [bannerData, setBannerData] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const getBannerData = async () => {
      try {
        setIsLoading(true);

        const response = await apiInterceptor.get(`/api/banner`);
        setBannerData(response.data);
        console.log(response.data, "Banners");
      } catch (error) {
        console.error("Error fetching banner data:", error);
      } finally {
        setIsLoading(false);
      }
    };
    getBannerData();
  }, []);

  const handleDelete = async (id: string) => {
    const accessToken = Cookies.get("jazz_token");
    const result = await apiInterceptor.delete(`/api/admin/banner/${id}`, {
      headers: { authorization: `Bearer ${accessToken}` },
    });
    setBannerData((prevData) =>
      prevData.filter((item) => item._id !== id)
    );
  };

  return (
    <div className="flex flex-col p-3">

<Link
          className="ml-[4rem] lg:ml-4 px-3 mx-4 py-2 hover:bg-[#FE342B] bg-[#383736] transition-all duration-300 rounded max-w-fit text-white my-2"
          href={"/admin/banner/add"}
          onClick={() => {
            if (userId) {
              userActivity(
                userId,
                "admin",
                "Add New Banner",
                {
                  pageVisit: `/`,
                },
                navigator.userAgent
              );
            } else {
              console.error("User ID is not available");
            }
          }}
      >
        Add New Banner
        </Link>



      {isLoading ? (
        <div className="flex justify-center items-center">
          <Image
            src={"/images/loading.gif"}
            height={50}
            width={50}
            alt="loading..."
          />
        </div>
      ) : (
        <>
          <div className="overflow-x-auto">
            <div className="inline-block min-w-full py-2">
              <div className="overflow-hidden">
                <table className="min-w-full text-left text-sm font-light">
                  <thead className="border-b bg-white font-medium">
                    <tr>
                      <th className="px-6 py-4">#</th>
                      <th className="px-6 py-4">Banner</th>
                      <th className="px-[2rem] py-4 text-right">Action</th>
                    </tr>
                  </thead>
                  {bannerData.map((item, index) => (
                    <tbody key={item._id}>
                      <tr className="border-b bg-neutral-100 dark:border-neutral-500 hover:bg-gray-200">
                        <td className="whitespace-nowrap px-6 py-4 font-medium">
                          {index + 1}
                        </td>
                        <td className="px-6 py-4 ">
                       <AntImage
  src={
    item.image
      ? `https://api.jazzagain.com/public/${item.image}`
      : item.desktopImage
      ? `https://api.jazzagain.com/public/${item.desktopImage}`
      : "/images/no-image.png" // fallback image if both are missing
  }
  width={65}
  height={45}
  alt={"Banner Image"}
  className="inline-table mx-2"
/>

                        </td>

                        <td className="whitespace-nowrap px-6 py-4 flex flex-row-reverse ">
                          <button
                            className="bg-[#FE342B]  hover:bg-[#d13931] rounded text-white mx-2 px-3 py-2"
                            onClick={() => handleDelete(item._id)}
                          >
                            Delete
                          </button>
                          {/* <Link
                        href={`/admin/banner/${item._id}`}
                        className="bg-[#383736] transition-all duration-300 hover:bg-[#2d2d2c] rounded text-white px-3 mx-2 py-2"
                      >
                        Update
                      </Link> */}
                        </td>
                      </tr>
                    </tbody>
                  ))}
                </table>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
