import React from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import StripePaginationBar from "./StripePaginationBar";
import { ClipLoader } from "react-spinners";
import MkdSDK from "../utils/MkdSDK";

const columns = [
  {
    header: "Product",
    type: "metadata",
    pre_accessor: "metadata",
    accessor: "app_product_name",
  },
  {
    header: "Status",
    accessor: "status",
  },
  {
    header: "Currency",
    accessor: "currency",
  },
  {
    header: "Amount",
    accessor: "amount",
    type: "currency",
  },
  {
    header: "Amount captured",
    accessor: "amount_captured",
    type: "currency",
  },
  {
    header: "Amount refunded",
    accessor: "amount_refunded",
    type: "currency",
  },
  {
    header: "Created at",
    accessor: "created",
    type: "timestamp",
  },
];

const StripeChargesComponent = () => {
  const sdk = new MkdSDK();
  const { dispatch, state } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [initialId, setInitialId] = React.useState(null);
  const [data, setData] = React.useState({});
  const [pageSize, setPageSize] = React.useState(10);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  function updatePageSize(limit) {
    (async function () {
      setPageSize(limit);
      await getData({ limit });
    })();
  }

  function previousPage() {
    (async function () {
      await getData({ limit: pageSize, before: data?.data[0].id });
    })();
  }

  function nextPage() {
    (async function () {
      await getData({
        limit: pageSize,
        after: data?.data[data?.data.length - 1].id,
      });
    })();
  }

  async function getData(paginationParams) {
    try {
      setLoading(true);
      const {
        list: charges,
        limit,
        error,
        message,
      } = await sdk.getCustomerStripeCharges(paginationParams);

      if (error) {
        showToast(globalDispatch, message, 5000);
      }
      if (!charges) {
        return;
      }

      if (!initialId) {
        setInitialId(charges?.data[0]?.id ?? "");
      }
      setData(charges);
      setPageSize(+limit);
      setCanPreviousPage(initialId && initialId !== charges.data[0]?.id);
      setCanNextPage(charges.has_more);
    } catch (error) {
      console.error("ERROR", error);
      showToast(globalDispatch, error.message, 5000);
      tokenExpireError(dispatch, error.message);
    } finally {
      setLoading(false);
    }
  }

  React.useEffect(() => {
    getData({});
  }, []);

  return (
    <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
      <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 dark:text-white">
          Charges
        </h4>
      </div>

      <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, index) => (
                <th
                  key={index}
                  className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                >
                  {column.header}
                  <span>
                    {column.isSorted ? (column.isSortedDesc ? " ▼" : " ▲") : ""}
                  </span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="text-white">
            {loading ? (
              <tr>
                <td colSpan={columns.length} className="px-4 py-3 text-center">
                  <span className="trans relative top-[30px] 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 Charges...
                  </span>
                </td>
              </tr>
            ) : !data?.data?.length ? (
              <tr>
                <td colSpan={columns.length} className="px-4 py-3 text-center">
                  <span className="relative top-[10px] m-4 p-4 font-semibold text-white">
                    No charges found
                  </span>
                </td>
              </tr>
            ) : (
              data?.data?.map((row, i) => (
                <tr
                  key={i}
                  className="border-b border-strokedark hover:bg-primary/5"
                >
                  {columns.map((cell, index) => {
                    if (cell.accessor === "") {
                      return (
                        <td
                          key={index}
                          className="whitespace-nowrap px-4 py-3"
                        ></td>
                      );
                    }
                    if (cell.mapping) {
                      return (
                        <td key={index} className="whitespace-nowrap px-4 py-3">
                          {cell.mapping[row[cell.accessor]]}
                        </td>
                      );
                    }
                    if (cell.type === "timestamp") {
                      return (
                        <td key={index} className="whitespace-nowrap px-4 py-3">
                          {new Date(row[cell.accessor] * 1000).toLocaleString(
                            "en-US"
                          )}
                        </td>
                      );
                    } else if (cell.type === "currency") {
                      return (
                        <td key={index} className="whitespace-nowrap px-4 py-3">
                          ${Number(row[cell.accessor] / 100).toFixed(2)}
                        </td>
                      );
                    } else if (cell.type === "metadata") {
                      return (
                        <td key={index} className="whitespace-nowrap px-4 py-3">
                          {row[cell.pre_accessor][cell.accessor] ?? "n/a"}
                        </td>
                      );
                    }
                    return (
                      <td key={index} className="whitespace-nowrap px-4 py-3">
                        {row[cell.accessor]}
                      </td>
                    );
                  })}
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <div className="w-full px-4 py-10 md:px-6 2xl:px-9">
        <StripePaginationBar
          pageSize={pageSize}
          canPreviousPage={canPreviousPage}
          canNextPage={canNextPage}
          updatePageSize={updatePageSize}
          previousPage={previousPage}
          nextPage={nextPage}
        />
      </div>
    </div>
  );
};

export default StripeChargesComponent;
