import React, { useState, useEffect } from "react";
import Cookies from "js-cookie";
import apiInterceptor from "@/interceptor/interceptor";
import Link from "next/link";
import toast, { Toaster } from "react-hot-toast";
import { userActivity } from "@/components/commonFunctions/userActivity";
import jwt from "jsonwebtoken";

const Index = () => {
  const token: any = Cookies.get("jazz_admin_token");
  const decodedToken = jwt.decode(token);
  const userId = decodedToken ? decodedToken.sub : null;

  const [users, setUsers] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);

  const successNotify = () => toast.success("Deleted Successfully!");
  const errorNotify = () => toast.error("Something went wrong!");

  useEffect(() => {
    const getUsers = async () => {
      try {
        const accessToken = Cookies.get("jazz_token");
        const response = await apiInterceptor.get(
          `/api/admin/userManagement?page=${currentPage}`,
          {
            headers: {
              authorization: `Bearer ${accessToken}`,
            },
          }
        );
        setUsers(response.data.users.data);
        setTotalPage(response.data.users.pagination.total_pages);
      } catch (error) {
        console.error("Error:", error);
        errorNotify();
      }
    };

    getUsers();
  }, [currentPage]);

  const handleDelete = async (userId: string) => {
    try {
      const accessToken = Cookies.get("jazz_token");
      await apiInterceptor.delete(`/api/admin/userManagement/${userId}`, {
        headers: {
          authorization: `Bearer ${accessToken}`,
        },
      });
      setUsers((prevData) => prevData.filter((item) => item._id !== userId));
      successNotify();
    } catch (error) {
      console.error("error", error);
      errorNotify();
    }
  };

  const filteredUsers = users.filter((user) =>
    `${user.firstName} ${user.lastName} ${user.email} ${user.phone}`
      .toLowerCase()
      .includes(searchTerm.toLowerCase())
  );

  return (
    <>
      <div className="flex flex-col">
     
<div className="flex items-center gap-4 px-4 my-4 flex-wrap">
  <Link
    className="px-4 py-2 bg-[#383736] hover:bg-[#FE342B] transition-all duration-300 rounded text-white"
    href={"/admin/user/addUser"}
    onClick={() => {
      if (userId) {
        userActivity(
          userId,
          "admin",
          "Add New User",
          { pageVisit: `/` },
          navigator.userAgent
        );
      }
    }}
  >
    Add New User
  </Link>

  <input
    type="text"
    placeholder="Search by name, email or phone..."
    value={searchTerm}
    onChange={(e) => {
      setSearchTerm(e.target.value);
      setCurrentPage(1);
    }}
    className="border px-4 py-2 rounded shadow-sm w-full sm:w-[300px]"
  />
</div>

        <div className="overflow-x-auto">
          <div className="inline-block min-w-full py-2">
            <div className="overflow-hidden">
              <Toaster />
              <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">USER</th>
                    <th className="px-6 py-4">PHONE NUMBER</th>
                    <th className="px-6 py-4">EMAIL</th>
                    <th className="px-6 py-4">ADDRESS</th>
                    <th className="px-6 py-4">CREATED ON</th>
                    <th className="py-4 text-right px-[2rem]">Action</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredUsers.map((item, index) => (
                    <tr
                      key={item._id}
                      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="whitespace-nowrap px-6 py-4">
                        {item.firstName} {item.lastName}
                      </td>
                      <td className="whitespace-nowrap px-6 py-4">
                        {item.phoneCode} {item.phone}
                      </td>
                      <td className="whitespace-nowrap px-6 py-4">
                        {item.email}
                      </td>
                      <td className="whitespace-nowrap px-6 py-4">
                        {item.address}
                      </td>
                      <td className="whitespace-nowrap px-6 py-4">
                        {item.createdBy?.dateTime || "-"}
                      </td>
                      <td className="whitespace-nowrap px-6 py-4 flex flex-row-reverse">
                        <button
                          className="bg-[#FE342B] hover:bg-[#d13931] rounded text-white px-3 mx-2 py-1"
                          onClick={() => handleDelete(item._id)}
                        >
                          Delete
                        </button>
                        <Link
                          href={`/admin/user/update-user/${item._id}`}
                          className="bg-[#383736] hover:bg-[#2d2d2c] rounded text-white px-3 mx-2 py-1"
                        >
                          Update
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {filteredUsers.length === 0 && (
                <div className="text-center p-4 text-gray-600">
                  No users found.
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="ml-3 mt-4 flex justify-between sm:px-[2rem]">
          <button
            onClick={() => currentPage > 1 && setCurrentPage(currentPage - 1)}
            className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded"
          >
            Previous
          </button>
          <button
            onClick={() =>
              currentPage < totalPage && setCurrentPage(currentPage + 1)
            }
            className="bg-[#383736] hover:bg-[#FE342B] text-white px-4 py-2 rounded"
          >
            Next
          </button>
        </div>
      </div>
    </>
  );
};

export default Index;
