import React, { Fragment, useState } from "react";
import { useNavigate } from "react-router-dom";
import { LazyLoad } from "Components/LazyLoad";
import { ModalSidebar } from "Components/ModalSidebar";
import AddAdminStripeProductPage from "Pages/Admin/Add/AddAdminStripeProductPage";
import EditAdminStripePlanPage from "Pages/Admin/Edit/EditAdminStripePlanPage";
import { TrashIcon, PencilIcon, MoreVertical } from "Assets/svgs";
import { useContexts } from "Hooks/useContexts";
import { GlobalContext } from "Src/globalContext";
import { ClipLoader } from "react-spinners";
import PaginationBar from "Components/PaginationBar";
import MkdSDK from "Utils/MkdSDK";
import AddButton from "Components/AddButton";
import ConfirmModal from "Components/Modal/ConfirmModal";

const columns = [
  {
    header: "Row",
    accessor: "row",
  },
  {
    header: "ID",
    accessor: "id",
  },
  {
    header: "Name",
    accessor: "name",
  },
  {
    header: "Stripe ID",
    accessor: "stripe_id",
  },
  {
    header: "Status",
    accessor: "status",
    mappingExist: true,
    mappings: {
      0: { text: "Inactive", bg: "#F6A13C", color: "black" },
      1: { text: "Active", bg: "#9DD321", color: "black" },
    },
  },
  {
    header: "Created At",
    accessor: "create_at",
  },
  {
    header: "Updated At",
    accessor: "update_at",
  },
];

const AdminStripePlansListPage = () => {
  const navigate = useNavigate();
  const { globalDispatch, deleteOne, showToast } = useContexts();

  const [currentTableData, setCurrentTableData] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pageCount, setPageCount] = useState(0);
  const [dataTotal, setDataTotal] = useState(0);
  const [currentPage, setPage] = useState(1);
  const [canPreviousPage, setCanPreviousPage] = useState(false);
  const [canNextPage, setCanNextPage] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedItemId, setSelectedItemId] = useState(null);
  const [formYes, setFormYes] = useState(false);
  const [showActionMenu, setShowActionMenu] = useState(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);

  const onToggleDeleteModal = (show, id = null) => {
    setShowActionMenu(null);
    setShowDeleteModal(show);
    setSelectedItemId(id);
  };

  const handleEdit = (item) => {
    setShowActionMenu(null);
    setSelectedItem(item);
    setIsEditModalOpen(true);
  };

  const toggleActionMenu = (id) => {
    setShowActionMenu(showActionMenu === id ? null : id);
  };

  const onRemove = async (id = null) => {
    try {
      setIsDeleting(true);
      const result = await deleteOne("stripe_product", id);
      if (!result?.error) {
        showToast("Plan Deleted", 5000, "success");
        getData(currentPage, pageSize);
      }
    } catch (error) {
      showToast(error.message, 5000, "error");
    } finally {
      onToggleDeleteModal(false);
      setIsDeleting(false);
      setFormYes(false);
    }
  };

  const getData = async (pageNum, limitNum) => {
    setIsLoading(true);
    const sdk = new MkdSDK();
    try {
      const paginationParams = {
        page: pageNum,
        limit: limitNum,
      };
      const filterParams = {}; // Add any filter parameters if needed
      await sdk.getCustomerStripeSubscriptions(paginationParams, filterParams);
      const result = await sdk.callRawAPI(
        `/v4/api/records/stripe_product?page=${pageNum}&limit=${limitNum}`,
        [],
        "GET"
      );

      const { list, total, limit, num_pages, page } = result;

      setCurrentTableData(list);
      setPageSize(limit);
      setPageCount(num_pages);
      setPage(page);
      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);
    } catch (error) {
      console.error(error);
      showToast(error.message, 5000, "error");
    } finally {
      setIsLoading(false);
    }
  };

  function updatePageSize(limit) {
    setPageSize(limit);
    getData(1, limit);
  }

  function previousPage() {
    getData(currentPage - 1, pageSize);
  }

  function nextPage() {
    getData(currentPage + 1, pageSize);
  }

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "plans",
      },
    });
    getData(1, pageSize);
  }, []);

  React.useEffect(() => {
    if (formYes && selectedItemId) {
      onRemove(selectedItemId);
    }
  }, [formYes]);
  console.log(isOpen);
  return (
    <div className="max-w-screen h-full p-4 md:p-6 2xl:p-10">
      <div className="shadow-default rounded border border-strokedark bg-boxdark">
        {/* Header Section */}
        <div className="flex items-center justify-between border-b border-strokedark px-4 md:px-6 2xl:px-9">
          <h4 className="my-3 text-2xl font-semibold text-white">Plans</h4>
          <button
            type="button"
            className="inline-flex h-9 items-center justify-center rounded bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
            onClick={() => setIsOpen(true)}
          >
            +
          </button>
        </div>

        {/* Table Content */}
        <div className="p-4 md:p-6 2xl:p-10">
          <div className="custom-overflow min-h-[140px] overflow-x-auto">
            <table className="w-full table-auto">
              <thead className="bg-meta-4">
                <tr>
                  {columns.map((column, i) => (
                    <th
                      key={i}
                      className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1"
                    >
                      {column.header}
                    </th>
                  ))}
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                    Action
                  </th>
                </tr>
              </thead>
              {!isLoading && currentTableData.length > 0 ? (
                <tbody className="cursor-pointer text-white">
                  {currentTableData.map((row, i) => (
                    <tr
                      key={i}
                      className="border-b border-strokedark hover:bg-primary/5"
                    >
                      {columns.map((cell, index) => {
                        if (cell.mappingExist) {
                          const mapping = cell.mappings[row[cell.accessor]];
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              <span
                                className="rounded px-2 py-1"
                                style={{
                                  backgroundColor: mapping?.bg,
                                  color: mapping?.color,
                                }}
                              >
                                {mapping?.text}
                              </span>
                            </td>
                          );
                        }
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.accessor]}
                          </td>
                        );
                      })}
                      <td className="whitespace-nowrap px-6 py-4">
                        <div className="relative">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              toggleActionMenu(row.id);
                            }}
                            className="rounded-full p-1 hover:bg-meta-4"
                          >
                            <MoreVertical className="h-5 w-5 text-white" />
                          </button>

                          {showActionMenu === row.id && (
                            <div className="absolute right-0 z-10 mt-2 w-48 rounded-md border border-strokedark bg-boxdark shadow-lg">
                              <div className="py-1">
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    handleEdit(row);
                                  }}
                                  className="flex w-full items-center px-4 py-2 text-sm text-white hover:bg-primary/5"
                                >
                                  <PencilIcon className="mr-2 h-4 w-4" />
                                  Edit
                                </button>
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    onToggleDeleteModal(true, row.id);
                                  }}
                                  className="flex w-full items-center px-4 py-2 text-sm text-danger hover:bg-primary/5"
                                >
                                  <TrashIcon className="mr-2 h-4 w-4" />
                                  Delete
                                </button>
                              </div>
                            </div>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              ) : isLoading ? (
                <tbody>
                  <tr>
                    <td colSpan={columns.length + 1} className="text-center">
                      <span className="trans relative m-4 animate-pulse whitespace-nowrap p-4 pb-8 text-xl font-semibold text-white ease-out">
                        <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                        Loading Plans...
                      </span>
                    </td>
                  </tr>
                </tbody>
              ) : (
                <tbody>
                  <tr>
                    <td colSpan={columns.length + 1} className="text-center">
                      <span className="relative top-[10px] m-4 p-4 font-semibold text-white">
                        No data found
                      </span>
                    </td>
                  </tr>
                </tbody>
              )}
            </table>
          </div>

          {/* Pagination */}
          {currentTableData.length > 0 && !isLoading && (
            <div className="w-full px-4 py-10">
              <PaginationBar
                currentPage={currentPage}
                pageCount={pageCount}
                pageSize={pageSize}
                canPreviousPage={canPreviousPage}
                canNextPage={canNextPage}
                updatePageSize={updatePageSize}
                previousPage={previousPage}
                nextPage={nextPage}
                dataTotal={dataTotal}
              />
            </div>
          )}
        </div>
      </div>

      {isOpen && (
        <LazyLoad>
          <div className="absolute top-0 flex h-full w-full items-center justify-center">
            <div
              className="fixed inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm"
              onClick={() => setIsOpen(false)}
            />
            <div className="shadow-default w-full max-w-xl transform justify-center rounded border border-strokedark bg-boxdark transition-all">
              <div className="flex items-center justify-between border-b border-stroke px-6 py-4">
                <h3 className="text-xl font-medium text-white">Add a Plan</h3>
                <button
                  onClick={() => setIsOpen(false)}
                  className="text-2xl hover:text-primary"
                >
                  ×
                </button>
              </div>
              <div className="bg-black p-6">
                <LazyLoad>
                  <AddAdminStripeProductPage
                    onSuccess={() => {
                      setIsOpen(false);
                      getData(currentPage, pageSize);
                    }}
                  />
                </LazyLoad>
              </div>
            </div>
          </div>
        </LazyLoad>
      )}

      {isEditModalOpen && (
        <ModalSidebar
          isModalActive={isEditModalOpen}
          closeModalFn={() => {
            setIsEditModalOpen(false);
            setSelectedItem(null);
          }}
        >
          <EditAdminStripePlanPage
            activeId={selectedItem?.id}
            setSidebar={setIsEditModalOpen}
            onSuccess={() => {
              setIsEditModalOpen(false);
              getData(currentPage, pageSize);
            }}
          />
        </ModalSidebar>
      )}

      {showDeleteModal && (
        <ConfirmModal
          confirmText="Are you sure you want to delete this plan?"
          setModalClose={setShowDeleteModal}
          setFormYes={setFormYes}
        />
      )}
    </div>
  );
};

export default AdminStripePlansListPage;
