import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import DeleteModal from "../../../../components/DeleteModal";
import Table from "../../../../components/Table";
import TableLoading from "../../../../components/TableLoading";
import { useDeleteBadgeMutation, useGetBadgesQuery } from "../../../../features/badges/badgesApi";
import cn from "../../../../utils/cn";
import formatISODate from "../../../../utils/formatISODate";
import { replaceWithDynamicValue } from "../../../../utils/utils";
import BadgeActions from "./BadgeActions";
import EmptyBadge from "./EmptyBadge";
import StatusToggler from "./StatusToggler";

const BadgesTable = () => {
  const navigate = useNavigate();
  const { data, isLoading, isError } = useGetBadgesQuery("", {
    refetchOnMountOrArgChange: false,
  });
  const [deleteBadge, { isLoading: deleting }] = useDeleteBadgeMutation();
  const [sortedData, setSortedData] = useState([]);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleteId, setDeleteId] = useState(null);

  const handleDelete = async () => {
    if (deleteId) {
      const result = await deleteBadge(deleteId).unwrap();
      if (result.id) {
        setShowDeleteModal(false);
        setDeleteId(null);
        toast.success("Badge deleted successfully");
      }
    }
  };

  useEffect(() => {
    if (isError) {
      setSortedData([]);

      return;
    }

    if (data && data.length > 0) {
      const dataCopy = [...data];
      setSortedData(dataCopy.sort((a, b) => Number(b.priority) - Number(a.priority)));
    }
  }, [data, isError]);

  return isError ? (
    <EmptyBadge />
  ) : (
    <div className="wmx-shadow wmx-rounded-lg wmx-border wmx-border-gray-100">
      <Table>
        <thead className="wmx-bg-blue-100">
          <tr>
            <Table.Heading className="wmx-pl-4 wmx-py-4 wmx-rounded-tl-lg">Status</Table.Heading>
            <Table.Heading>Badge Name</Table.Heading>
            <Table.Heading className="wmx-text-center">Preview</Table.Heading>
            <Table.Heading>Validity</Table.Heading>
            <Table.Heading className="wmx-w-20 wmx-text-center wmx-rounded-tr-lg">Actions</Table.Heading>
          </tr>
        </thead>
        {isLoading ? (
          <TableLoading type="badge" column={5} row={5} />
        ) : (
          <tbody className=" wmx-bg-white">
            {sortedData.map((badge, idx) => (
              <tr
                className={cn({
                  "wmx-bg-slate-100": idx % 2 !== 0,
                })}
                key={badge.id}
              >
                <Table.Data
                  className={cn("wmx-pl-4", {
                    "wmx-rounded-bl-lg": sortedData.length === idx + 1,
                  })}
                >
                  <StatusToggler badge={badge} />
                </Table.Data>
                <Table.Data>
                  <button
                    className="wmx-font-semibold wmx-text-left wmx-text-primary"
                    onClick={() => {
                      navigate(`editor?id=${badge.id}`, { state: { badge } });
                    }}
                  >
                    {badge.badge_name}
                  </button>
                </Table.Data>
                <Table.Data className="wmx-text-center">
                  <div
                    style={{ display: "inline-flex" }}
                    dangerouslySetInnerHTML={{
                      __html: replaceWithDynamicValue(badge?.badge_style || "").replace("absolute", "static"),
                    }}
                  />
                </Table.Data>
                <Table.Data>
                  <div className="wmx-flex wmx-flex-col">
                    <p className="wmx-whitespace-nowrap">
                      <span className="wmx-font-bold">From:</span> {formatISODate(badge.valid_from)}
                    </p>
                    <p className="wmx-whitespace-nowrap">
                      <span className="wmx-font-bold">To:</span> {formatISODate(badge.valid_to)}
                    </p>
                  </div>
                </Table.Data>
                <Table.Data
                  className={cn("wmx-pr-4", {
                    "wmx-rounded-br-lg": sortedData.length === idx + 1,
                  })}
                >
                  <BadgeActions badge={badge} setDeleteId={setDeleteId} setShowDeleteModal={setShowDeleteModal} />
                </Table.Data>
              </tr>
            ))}
          </tbody>
        )}
      </Table>
      <DeleteModal
        isOpen={showDeleteModal}
        setIsOpen={setShowDeleteModal}
        handleDelete={handleDelete}
        isLoading={deleting}
      />
    </div>
  );
};
export default BadgesTable;
