import React, { useState, useEffect } from "react";
import MkdSDK from "Utils/MkdSDK";
import { GlobalContext, showToast } from "Src/globalContext";
import { ClipLoader } from "react-spinners";
import PaginationBar from "Components/PaginationBar";

const columns = [
  {
    header: "Customer",
    accessor: "userEmail",
  },
  {
    header: "Status",
    accessor: "status",
    mappingExist: true,
    mappings: {
      active: { text: "Active", bg: "#9DD321", color: "black" },
      canceled: { text: "Canceled", bg: "#F6A13C", color: "black" },
      trialing: { text: "Trialing", bg: "#3C50E0", color: "white" },
    },
  },
  {
    header: "Plan",
    accessor: "planName",
  },
  {
    header: "Type",
    accessor: "planType",
    mappingExist: true,
    mappings: {
      recurring: { text: "Recurring", bg: "#9DD321", color: "black" },
      one_time: { text: "One Time", bg: "#F6A13C", color: "black" },
      lifetime: { text: "Lifetime", bg: "#3C50E0", color: "white" },
    },
  },
  {
    header: "Interval",
    accessor: "interval",
  },
  {
    header: "Start Date",
    accessor: "currentPeriodStart",
    type: "timestamp",
  },
  {
    header: "End Date",
    accessor: "currentPeriodEnd",
    type: "timestamp",
  },
  {
    header: "Amount",
    accessor: "planAmount",
    type: "currency",
  },
];

const AdminStripeSubscriptionsListPage = () => {
  const [currentTableData, setCurrentTableData] = useState([]);
  const [loading, setLoading] = useState(true);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [pageCount, setPageCount] = useState(0);
  const [dataTotal, setDataTotal] = useState(0);
  const [canPreviousPage, setCanPreviousPage] = useState(false);
  const [canNextPage, setCanNextPage] = useState(false);

  const getData = async (pageNum, limitNum) => {
    try {
      setLoading(true);
      const sdk = new MkdSDK();
      const paginationParams = {
        page: pageNum,
        limit: limitNum,
      };

      const result = await sdk.getStripeSubscriptions(paginationParams, {});

      if (!result.error) {
        setCurrentTableData(result.list || []);
        setPageSize(parseInt(result.limit));
        setPageCount(parseInt(result.num_pages));
        setCurrentPage(parseInt(result.page));
        setDataTotal(parseInt(result.total));
        setCanPreviousPage(parseInt(result.page) > 1);
        setCanNextPage(parseInt(result.page) + 1 <= parseInt(result.num_pages));
      } else {
        showToast(globalDispatch, "Failed to fetch subscriptions", "error");
      }
    } catch (error) {
      console.error("Error fetching subscriptions:", error);
      showToast(globalDispatch, "Error loading subscriptions", "error");
    } finally {
      setLoading(false);
    }
  };

  console.log(currentTableData);

  useEffect(() => {
    getData(1, pageSize);
  }, []);

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

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

  function nextPage() {
    getData(currentPage + 1 <= pageCount ? currentPage + 1 : 1, pageSize);
  }

  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">
            Subscriptions
          </h4>
        </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>
                  ))}
                </tr>
              </thead>
              {!loading && currentTableData.length > 0 ? (
                <tbody className="cursor-pointer text-white">
                  {currentTableData.map((subscription, i) => (
                    <tr
                      key={subscription.subId}
                      className="border-b border-strokedark hover:bg-primary/5"
                    >
                      <td className="whitespace-nowrap px-4 py-4">
                        <div>
                          <p className="text-white">{subscription.userEmail}</p>
                          <p className="text-xs text-bodydark2">
                            {subscription.first_name} {subscription.last_name}
                          </p>
                        </div>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <span
                          className={`inline-block rounded px-2.5 py-0.5 text-sm font-medium ${
                            subscription.status === "active"
                              ? "bg-success/10 text-success"
                              : subscription.status === "canceled"
                              ? "bg-danger/10 text-danger"
                              : "bg-warning/10 text-warning"
                          }`}
                        >
                          {subscription.status}
                        </span>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <span>{subscription.planName}</span>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <span
                          className={`inline-block rounded px-2.5 py-0.5 text-sm font-medium ${
                            subscription.planType === "recurring"
                              ? "bg-success/10 text-success"
                              : subscription.planType === "lifetime"
                              ? "bg-primary/10 text-primary"
                              : "bg-warning/10 text-warning"
                          }`}
                        >
                          {subscription.planType}
                        </span>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <span className="capitalize">
                          {subscription.interval}
                        </span>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <span>
                          {new Date(
                            parseInt(subscription.currentPeriodStart) * 1000
                          ).toLocaleDateString()}
                        </span>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <span>
                          {subscription.planType === "lifetime"
                            ? "Infinity"
                            : new Date(
                                parseInt(subscription.currentPeriodEnd) * 1000
                              ).toLocaleDateString()}
                        </span>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <span>${subscription.planAmount.toFixed(2)}</span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              ) : loading ? (
                <tbody>
                  <tr>
                    <td colSpan={columns.length} 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 Subscriptions...
                      </span>
                    </td>
                  </tr>
                </tbody>
              ) : (
                <tbody>
                  <tr>
                    <td colSpan={columns.length} className="text-center">
                      <span className="relative top-[10px] m-4 p-4 font-semibold text-white">
                        No subscriptions found
                      </span>
                    </td>
                  </tr>
                </tbody>
              )}
            </table>
          </div>

          {/* Pagination */}
          {currentTableData.length > 0 && !loading && (
            <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>
    </div>
  );
};

export default AdminStripeSubscriptionsListPage;
