
  import React, { useEffect, useState } from "react";
  import { AuthContext, tokenExpireError } from "Context/Auth";
  import MkdSDK from "Utils/MkdSDK";
  import { useNavigate } from "react-router-dom";
  import { GlobalContext, showToast } from "Context/Global";
  import { yupResolver } from "@hookform/resolvers/yup";
  import { useForm } from "react-hook-form";
  import * as yup from "yup";
  import { getNonNullValue } from "Utils/utils";
  import { PaginationBar } from "Components/PaginationBar";
  import { AddButton } from "Components/AddButton";
  import { BiFilterAlt, BiSearch } from "react-icons/bi";
  import { AiOutlineClose, AiOutlinePlus } from "react-icons/ai";
  import { RiDeleteBin5Line } from "react-icons/ri";
  import { SkeletonLoader } from "Components/Skeleton";
  import { ModalSidebar } from "Components/ModalSidebar";
  import {
    AddAdminStripePricePage,
  } from "Pages/Admin/Add";
  import {
    EditAdminStripePricePage,
  } from "Pages/Admin/Edit";
  
  let sdk = new MkdSDK();
  
  const columns = [
    {
      header: "Stripe Id",
      accessor: "stripe_id",
    },
    {
      header: "Product",
      accessor: "product_name",
    },
    {
      header: "Nickname",
      accessor: "name",
    },
    {
      header: "Type",
      accessor: "type",
      mapping: {
        one_time: "One Time",
        recurring: "Recurring",
        lifetime: "Lifetime",
      },
    },
    {
      header: "Price",
      accessor: "amount",
    },
    {
      header: "Trial",
      accessor: "trial_days",
    },
    {
      header: "Status",
      accessor: "status",
      mapping: {
        0: "Inactive",
        1: "Active",
      },
    },
    {
      header: "Action",
      accessor: "",
    },
  ];
  
  const AdminStripePricesListPage = () => {
    const { dispatch: globalDispatch } = React.useContext(GlobalContext);
    const { dispatch } = React.useContext(AuthContext);
    const [query, setQuery] = React.useState("");
    const [data, setCurrentTableData] = React.useState([]);
    const [pageSize, setPageSize] = React.useState(10);
    const [pageCount, setPageCount] = React.useState(0);
    const [dataTotal, setDataTotal] = React.useState(0);
    const [currentPage, setPage] = React.useState(0);
    const [canPreviousPage, setCanPreviousPage] = React.useState(false);
    const [canNextPage, setCanNextPage] = React.useState(false);
    const [openFilter, setOpenFilter] = React.useState(false);
    const [showFilterOptions, setShowFilterOptions] = React.useState(false);
    const [selectedOptions, setSelectedOptions] = React.useState([]);
    const [filterConditions, setFilterConditions] = React.useState([]);
    const [searchValue, setSearchValue] = React.useState("");
    const [optionValue, setOptionValue] = React.useState("eq");
    const [isLoading, setIsLoading] = React.useState(false);
    const [showEditSidebar, setShowEditSidebar] = useState(false);
    const [showAddSidebar, setShowAddSidebar] = useState(false);
    const [activeEditId, setActiveEditId] = useState();
    const navigate = useNavigate();
    const dropdownFilterRef = React.useRef(null);
  
    const schema = yup.object({
      stripe_id: yup.string(),
      name: yup.string(),
      status: yup.string(),
      product_name: yup.string(),
      amount: yup.string(),
      type: yup.string(),
    });
  
    const {
      register,
      handleSubmit,
      formState: { errors },
    } = useForm({
      resolver: yupResolver(schema),
    });
  
    const selectStatus = [
      { key: "", value: "All" },
      { key: 0, value: "Archived" },
      { key: 1, value: "Active" },
    ];
    const typeStatus = [
      { key: "", value: "All" },
      { key: "one_time", value: "One time" },
      { key: "recurring", value: "Recurring" },
    ];
  
    function copyToClipboard(text) {
      navigator.clipboard.writeText(text);
      showToast(globalDispatch, "Copied to clipboard");
    }
  
    const addFilterCondition = (option, selectedValue, inputValue) => {
      const input =
        selectedValue === "eq" && isNaN(inputValue)
          ? `"${inputValue}"`
          : inputValue;
      const condition = `${option},${selectedValue},${input}`;
      setFilterConditions((prevConditions) => {
        const newConditions = prevConditions.filter(
          (condition) => !condition.includes(option)
        );
        return [...newConditions, condition];
      });
      setSearchValue(inputValue);
    };
  
    function updatePageSize(limit) {
      (async function () {
        setPageSize(limit);
        await getData(1, limit);
      })();
    }
    function previousPage() {
      (async function () {
        await getData(currentPage - 1 > 1 ? currentPage - 1 : 1, pageSize);
      })();
    }
  
    function nextPage() {
      (async function () {
        await getData(
          currentPage + 1 <= pageCount ? currentPage + 1 : 1,
          pageSize
        );
      })();
    }
  
    async function getData(pageNum, limitNum, filterParams) {
      setIsLoading(true);
      try {
        const result = await sdk.getStripePrices(
          { page: pageNum, limit: limitNum },
          `filter=${filterParams.toString()}`
        );
        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.log("ERROR", error);
        tokenExpireError(dispatch, error.message);
      }
      setIsLoading(false);
    }
  
    const onSubmit = (data) => {
      const stripe_id = getNonNullValue(data.stripe_id);
      const product_name = getNonNullValue(data.product_name);
      const name = getNonNullValue(data.name);
      const amount = getNonNullValue(data.amount);
      const type = getNonNullValue(data.type);
      const status = getNonNullValue(data.status);
      getData(1, pageSize, {
        stripe_id,
        product_name,
        name,
        amount,
        type,
        status,
      });
    };
  
    React.useEffect(() => {
      globalDispatch({
        type: "SETPATH",
        payload: {
          path: "prices",
        },
      });
  
      const delay = 700;
      const timeoutId = setTimeout(async () => {
        await getData(1, pageSize, filterConditions);
      }, delay);
  
      return () => {
        clearTimeout(timeoutId);
      };
    }, [searchValue, filterConditions, optionValue]);
  
    useEffect(() => {
      if (!showEditSidebar) {
        getData(1, pageSize, filterConditions);
      }
    }, [showEditSidebar, activeEditId, showAddSidebar]);
  
    const handleClickOutside = (event) => {
      if (dropdownFilterRef.current && !dropdownFilterRef.current.contains(event.target)) {
        setOpenFilter(false);
      }
    };

    React.useEffect(() => {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }, []);
  
    return (
      <>
        <div className="flex items-center justify-between py-3">
          <form
            className="relative rounded bg-white"
            onSubmit={handleSubmit(onSubmit)}
          >
            <div className="flex items-center gap-4 text-gray-700 text-nowrap" >
              <div className="relative" ref={dropdownFilterRef}>
                <div
                  className="flex cursor-pointer items-center justify-between gap-3 rounded-md border border-gray-200 px-3 py-1"
                  onClick={() => setOpenFilter(!openFilter)}
                >
                  <BiFilterAlt />
                  <span>Filters</span>
                  {selectedOptions.length > 0 && (
                    <span className="flex h-6 w-6 items-center justify-center rounded-full bg-gray-800 text-start text-white">
                      {selectedOptions.length}
                    </span>
                  )}
                </div>
                {openFilter && (
                  <div className="absolute z-10 mt-4 w-fit min-w-[90%] top-fill left-0 filter-form-holder bg-white border border-gray-200 rounded-md shadow-lg">
                    <div className="p-4">
                      {selectedOptions?.map((option, index) => (
                        <div key={index} className="mb-2 flex w-full items-center justify-between gap-3 text-gray-600">
                          <div className=" mb-3 w-1/3 rounded-md border border-gray-300 px-3 py-2 leading-tight text-gray-700 outline-none">
                            {option}
                          </div>
                          <select
                            className="mb-3 w-2/4 rounded-md border px-3 py-2 leading-tight text-gray-700 outline-none"

                            onChange={(e) => {
                              setOptionValue(e.target.value);
                            }}
                          >
                            <option value="eq" selected>equals</option>
                            <option value="cs">contains</option>
                            <option value="sw">start with</option>
                            <option value="ew">ends with</option>
                            <option value="lt">lower than</option>
                            <option value="le">lower or equal</option>
                            <option value="ge">greater or equal</option>
                            <option value="gt">greater than</option>
                            <option value="bt">between</option>
                            <option value="in">in</option>
                            <option value="is">is null</option>
                          </select>

                          <input
                            type="text"
                            placeholder="Enter value..."
                            className=" mb-3 w-1/3 rounded-md border px-3 py-2 leading-tight text-gray-700 outline-none"
                            onChange={(e) =>
                              addFilterCondition(
                                option,
                                optionValue,
                                e.target.value
                              )
                            }
                          />

                          <div className="w-1/12 mt-[-10px]">
                            <RiDeleteBin5Line
                              className=" cursor-pointer text-xl"
                              onClick={() => {
                                setSelectedOptions((prevOptions) =>
                                  prevOptions.filter((op) => op !== option)
                                );
                                setFilterConditions((prevConditions) => {
                                  return prevConditions.filter(
                                    (condition) => !condition.includes(option)
                                  );
                                });
                              }}
                            />
                          </div>

                        </div>
                      ))}

                      <div className="search-buttons relative flex items-center justify-between font-semibold">
                        <div
                          // type="submit"
                          className="mr-2 flex w-auto cursor-pointer items-center gap-2 rounded bg-gray-100 px-4 py-2.5 font-medium leading-tight text-gray-600 transition duration-150 ease-in-out "
                          onClick={() => {
                            setShowFilterOptions(!showFilterOptions);
                          }}
                        >
                          <AiOutlinePlus />
                          Add filter
                        </div>

                        {showFilterOptions && (
                          <div className="absolute top-11 z-10 bg-white px-5 py-3 text-gray-600 shadow-md">
                            <ul className="flex flex-col gap-2 text-gray-500">
                              {columns.slice(0, -1).map((column) => (
                                <li
                                  key={column.header}
                                  className={`${selectedOptions.includes(column.header)
                                    ? "cursor-not-allowed text-gray-400"
                                    : "cursor-pointer"
                                    }`}
                                  onClick={() => {
                                    if (!selectedOptions.includes(column.header)) {
                                      setSelectedOptions((prev) => [
                                        ...prev,
                                        column.header,
                                      ]);
                                    }
                                    setShowFilterOptions(false);
                                  }}
                                >
                                  {column.header}
                                </li>
                              ))}
                            </ul>
                          </div>
                        )}
                        {selectedOptions.length > 0 && (
                          <div
                            // type="reset"
                            onClick={() => {
                              setSelectedOptions([]);
                              setFilterConditions([]);
                            }}
                            className="inline-block cursor-pointer  rounded px-6  py-2.5 font-medium leading-tight text-gray-600  transition duration-150 ease-in-out"
                          >
                            Clear all filter
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </div>
              <div className=" flex cursor-pointer items-center justify-between gap-3 rounded-md border border-gray-200 px-2 py-1 focus-within:border-gray-400">
                <BiSearch className="text-xl text-gray-200" />
                <input
                  type="text"
                  placeholder="search..."
                  className="border-none p-0 placeholder:text-left  focus:outline-none"
                  style={{ boxShadow: "0 0 transparent" }}
                  onInput={(e) => addFilterCondition("name", "cs", e.target?.value)}
                />
                <AiOutlineClose className="text-lg text-gray-200" />
              </div>
            </div>
          </form>
          <AddButton onClick={() => setShowAddSidebar(true)} />
        </div>
        {isLoading ? (
          <SkeletonLoader />
        ) : (
          <div className="overflow-x-auto border-b border-gray-200 shadow ">
            <table className="min-w-full divide-y divide-gray-200 rounded-lg">
              <thead className="bg-gray-50">
                <tr>
                  {columns.map((column, index) => (
                    <th
                      key={index}
                      scope="col"
                      className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500"
                    >
                      {column.header}
                      <span>
                        {column.isSorted
                          ? column.isSortedDesc
                            ? " ▼"
                            : " ▲"
                          : ""}
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 bg-white">
                {data.map((row, i) => {
                  return (
                    <tr key={i}>
                      {columns.map((cell, index) => {
                        if (cell.accessor == "") {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              <button
                                className="mx-1 inline-block cursor-pointer p-1 text-sm font-medium text-[#4F46E5] transition duration-150 ease-in-out hover:underline"
                                onClick={() => {
                                  setActiveEditId(row.id);
                                  setShowEditSidebar(true);
                                  // navigate("/admin/edit-price/" + row.id, {
                                  //   state: row,
                                  // });
                                }}
                              >
                                {" "}
                                Edit
                              </button>
                            </td>
                          );
                        }
                        if (cell.accessor === "stripe_id") {
                          return (
                            <td key={index} className="px-6 py-4 whitespace-nowrap">
                              <div className="w-full flex items-center justify-between">
                                <span>{row[cell.accessor]} </span>
                                <span className="cursor-pointer" onClick={() => copyToClipboard(row[cell.accessor])}>
                                  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
                                    <g clipPath="url(#clip0_948_1315)">
                                      <path d="M6.66663 6.6665V4.33317C6.66663 3.39975 6.66663 2.93304 6.84828 2.57652C7.00807 2.26292 7.26304 2.00795 7.57664 1.84816C7.93316 1.6665 8.39987 1.6665 9.33329 1.6665H15.6666C16.6 1.6665 17.0668 1.6665 17.4233 1.84816C17.7369 2.00795 17.9918 2.26292 18.1516 2.57652C18.3333 2.93304 18.3333 3.39975 18.3333 4.33317V10.6665C18.3333 11.5999 18.3333 12.0666 18.1516 12.4232C17.9918 12.7368 17.7369 12.9917 17.4233 13.1515C17.0668 13.3332 16.6 13.3332 15.6666 13.3332H13.3333M4.33329 18.3332H10.6666C11.6 18.3332 12.0668 18.3332 12.4233 18.1515C12.7369 17.9917 12.9918 17.7368 13.1516 17.4232C13.3333 17.0666 13.3333 16.5999 13.3333 15.6665V9.33317C13.3333 8.39975 13.3333 7.93304 13.1516 7.57652C12.9918 7.26292 12.7369 7.00795 12.4233 6.84816C12.0668 6.6665 11.6 6.6665 10.6666 6.6665H4.33329C3.39987 6.6665 2.93316 6.6665 2.57664 6.84816C2.26304 7.00795 2.00807 7.26292 1.84828 7.57652C1.66663 7.93304 1.66663 8.39975 1.66663 9.33317V15.6665C1.66663 16.5999 1.66663 17.0666 1.84828 17.4232C2.00807 17.7368 2.26304 17.9917 2.57664 18.1515C2.93316 18.3332 3.39987 18.3332 4.33329 18.3332Z" stroke="#8D8D8D" stroke-width="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                    </g>
                                    <defs>
                                      <clipPath id="clip0_948_1315">
                                        <rect width="20" height="20" fill="white" />
                                      </clipPath>
                                    </defs>
                                  </svg>
                                </span>
                              </div>
                            </td>
                          );
                        }
                        if (cell.mapping && cell.accessor === "status") {
                          return (
                            <td
                              key={index}
                              className="px-6 py-5 whitespace-nowrap inline-block text-sm"
                            >
                              {row[cell.accessor] === 1 ? (
                                <span className="rounded-md bg-[#D1FAE5] px-3 py-1 text-[#065F46]">
                                  {cell.mapping[row[cell.accessor]]}
                                </span>
                              ) : (
                                <span className="rounded-md bg-[#F4F4F4] px-3 py-1 text-[#393939]">
                                  {cell.mapping[row[cell.accessor]]}
                                </span>
                              )}
                            </td>
                          );
                        }
                        if (cell.mapping) {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              {cell.mapping[row[cell.accessor]]}
                            </td>
                          );
                        }
                        return (
                          <td key={index} className="whitespace-nowrap px-6 py-4">
                            {row[cell.accessor]}
                          </td>
                        );
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
        <PaginationBar
          currentPage={currentPage}
          pageCount={pageCount}
          pageSize={pageSize}
          canPreviousPage={canPreviousPage}
          canNextPage={canNextPage}
          updatePageSize={updatePageSize}
          previousPage={previousPage}
          nextPage={nextPage}
        />
        <ModalSidebar
          isModalActive={showEditSidebar}
          closeModalFn={() => setShowEditSidebar(false)}
        >
          <EditAdminStripePricePage
            activeId={activeEditId}
            setSidebar={setShowEditSidebar}
          />
        </ModalSidebar>
  
        <ModalSidebar
          isModalActive={showAddSidebar}
          closeModalFn={() => setShowAddSidebar(false)}
        >
          <AddAdminStripePricePage setSidebar={setShowAddSidebar} />
        </ModalSidebar>
      </>
    );
  };
  
  export default AdminStripePricesListPage;
  
  