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

// {
//   "id": 21,
//   "name": "business",
//   "product_id": 6,
//   "stripe_id": "price_1QWNWXBgOlWo0lDUkYN2FfzY",
//   "is_usage_metered": 0,
//   "usage_limit": null,
//   "object": "{\"id\":\"price_1QWNWXBgOlWo0lDUkYN2FfzY\",\"object\":\"price\",\"active\":true,\"billing_scheme\":\"per_unit\",\"created\":1734291041,\"currency\":\"usd\",\"custom_unit_amount\":null,\"livemode\":false,\"lookup_key\":null,\"metadata\":{\"projectId\":\"goodbadugly\"},\"nickname\":\"business\",\"product\":\"prod_RPBHVJZLY9QbP6\",\"recurring\":{\"aggregate_usage\":null,\"interval\":\"month\",\"interval_count\":1,\"meter\":null,\"trial_period_days\":null,\"usage_type\":\"licensed\"},\"tax_behavior\":\"unspecified\",\"tiers_mode\":null,\"transform_quantity\":null,\"type\":\"recurring\",\"unit_amount\":4999,\"unit_amount_decimal\":\"4999\"}",
//   "amount": 49.99,
//   "trial_days": null,
//   "type": "recurring",
//   "status": 1,
//   "create_at": "2024-12-15",
//   "update_at": "2024-12-15T19:30:41.000Z"
// }
const columns = [
  {
    header: "Row",
    accessor: "row",
  },
  {
    header: "Stripe Id",
    accessor: "stripe_id",
  },
  {
    header: "Product",
    accessor: "name",
    join: "stripe_product",
  },
  {
    header: "Nickname",
    accessor: "name",
  },
  {
    header: "Type",
    accessor: "type",
    mappingExist: true,
    mappings: {
      one_time: { text: "One Time", bg: "#9DD321", color: "black" },
      recurring: { text: "Recurring", bg: "#9DD321", color: "black" },
      lifetime: { text: "Lifetime", bg: "#9DD321", color: "black" },
    },
  },
  {
    header: "Price",
    accessor: "amount",
  },
  {
    header: "Trial",
    accessor: "trial_days",
  },
  {
    header: "Status",
    accessor: "status",
    mappingExist: true,
    mappings: {
      0: { text: "Inactive", bg: "#F6A13C", color: "black" },
      1: { text: "Active", bg: "#9DD321", color: "black" },
    },
  },
];

const titles = {
  add: "Add a Price",
};

const AdminStripePricesListPage = ({ onSuccess = null }) => {
  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);

  console.log(isOpen);

  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_price", id);
      if (!result?.error) {
        showToast("Price 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 {
      // Replace this with your actual API call
      const result = await sdk.callRawAPI(
        `/v4/api/records/stripe_price?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: "pricing",
      },
    });
    getData(1, pageSize);
  }, []);

  React.useEffect(() => {
    if (formYes && selectedItemId) {
      onRemove(selectedItemId);
    }
  }, [formYes]);

  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">Prices</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 Prices...
                      </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>

      <LazyLoad>
        {isOpen && (
          <div className="absolute top-0 flex h-full w-full items-center justify-center">
            <div
              className="fixed inset-0 bg-black/50 backdrop-blur-sm"
              onClick={() => setIsOpen(false)}
            />
            <div className="shadow-default w-full max-w-xl transform 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 Price</h3>
                <button
                  onClick={() => setIsOpen(false)}
                  className="text-2xl hover:text-primary"
                >
                  ×
                </button>
              </div>
              <div className="p-6">
                <LazyLoad>
                  <AdminStripePricesAddPage
                    onSuccess={() => {
                      setIsOpen(false);
                      getData(currentPage, pageSize);
                    }}
                  />
                </LazyLoad>
              </div>
            </div>
          </div>
        )}
      </LazyLoad>

      <LazyLoad>
        <ModalSidebar
          isModalActive={isEditModalOpen}
          closeModalFn={() => {
            setIsEditModalOpen(false);
            setSelectedItem(null);
          }}
          customMinWidthInTw="w-full max-w-xl"
          customClassNames="fixed inset-0 z-50 flex items-center justify-center"
        >
          <div
            className="fixed inset-0 bg-black/50 backdrop-blur-sm"
            onClick={() => {
              setIsEditModalOpen(false);
              setSelectedItem(null);
            }}
          />
          <div className="shadow-default w-full max-w-xl transform 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">Edit Price</h3>
              <button
                onClick={() => {
                  setIsEditModalOpen(false);
                  setSelectedItem(null);
                }}
                className="text-2xl hover:text-primary"
              >
                ×
              </button>
            </div>
            <div className="p-6">
              <LazyLoad>
                <EditAdminStripePricePage
                  activeId={selectedItem?.id}
                  setSidebar={setIsEditModalOpen}
                  onSuccess={() => {
                    setIsEditModalOpen(false);
                    setSelectedItem(null);
                    getData(currentPage, pageSize);
                  }}
                />
              </LazyLoad>
            </div>
          </div>
        </ModalSidebar>
      </LazyLoad>

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

export default AdminStripePricesListPage;
