import React from "react";
import { AuthContext, tokenExpireError } from "Src/authContext";
import MkdSDK from "Utils/MkdSDK";
import { useNavigate } from "react-router-dom";
import { GlobalContext } 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 { BiFilterAlt, BiSearch } from "react-icons/bi";
import { AiOutlineClose, AiOutlinePlus } from "react-icons/ai";
import { RiDeleteBin5Line } from "react-icons/ri";
import { SkeletonLoader } from "Components/Skeleton";

const columns = [
  {
    header: "Status",
    accessor: "status",
  },
  {
    header: "Currency",
    accessor: "currency",
  },
  {
    header: "Amount due",
    accessor: "amount_due",
    type: "currency",
  },
  {
    header: "Amount paid",
    accessor: "amount_paid",
    type: "currency",
  },
  {
    header: "Amount remaining",
    accessor: "amount_remaining",
    type: "currency",
  },
  {
    header: "Created at",
    accessor: "created_at",
    type: "timestamp",
  },
];

const AdminStripeInvoicesListPageV2 = () => {
  const sdk = new MkdSDK();

  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 navigate = useNavigate();
  console.log("data in invoice", data);

  const schema = yup.object({
    customer_email: yup.string(),
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const selectStatus = [{ key: "", value: "All" }];

  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 { list, total, limit, num_pages, page, error, message } =
        await sdk.getStripeInvoicesV2(
          { page: pageNum, limit: limitNum },
          `filter=${filterParams.toString()}`
        );

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

      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 customer_email = getNonNullValue(data.customer_email);
    getData(1, pageSize, { customer_email, product_name });
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "invoices",
      },
    });

    const delay = 700;
    const timeoutId = setTimeout(async () => {
      await getData(1, pageSize, filterConditions);
    }, delay);

    return () => {
      clearTimeout(timeoutId);
    };
  }, [searchValue, filterConditions, optionValue]);

  return (
    <>
      {/* <form
          className="p-5 bg-brown-main-bg shadow rounded mb-10"
          onSubmit={ handleSubmit( onSubmit ) }
        >
          <h4 className="md:text-xl font-medium text-[16px]">Search</h4>
          <div className="filter-form-holder mt-10 flex flex-wrap">
            <div className="mb-4 w-full md:w-1/2 pr-2 pl-2">
              <label className="capitalize capitalize block text-gray-700 text-sm font-bold mb-2">Customer</label>
              <input
                type="text"
                placeholder="Email"
                { ...register( "customer_email" ) }
                className="shadow appearance-none border  rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
              />
              <p className="text-red-500 text-xs italic">{ errors.customer_email?.message }</p>
            </div>
          </div>
          <div className="search-buttons pl-2">
            <button
              type="submit"
              className="mr-2 inline-block px-6 py-2.5 bg-blue-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out"
            >
              Search
            </button>
  
            <button
              type="reset"
              onClick={ () => getData( 1, pageSize ) }
              className="inline-block px-6 py-2.5 bg-gray-800 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-gray-900 hover:shadow-lg focus:bg-gray-900 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-gray-900 active:shadow-lg transition duration-150 ease-in-out"
            >
              Reset
            </button>
          </div>
        </form> */}
      <div className="flex items-center justify-between py-3">
        <form
          className="bg-brown-main-bg relative rounded"
          onSubmit={handleSubmit(onSubmit)}
        >
          <div className="flex items-center gap-4 text-gray-700">
            <div
              className="flex cursor-pointer items-center justify-between gap-3 rounded-md border border-[#0003] 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 > 0 ? selectedOptions.length : null}
                </span>
              )}
            </div>
            <div className=" flex cursor-pointer items-center justify-between gap-3 rounded-md border border-[#0003] 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>
          {openFilter && (
            <div className="top-fill filter-form-holder bg-brown-main-bg absolute  left-0 z-20 mt-4 min-w-[70%] rounded-md border border-[#0003] p-5 shadow-xl">
              {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-black/60 px-3 py-2 leading-tight text-gray-700 outline-none">
                    {option}
                  </div>
                  <select
                    className="w-[30%] appearance-none border-none outline-0"
                    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)
                    }
                  />
                  {/* <p className="text-xs italic text-red-500">
                         {errors.id?.message}
                       </p> */}

                  <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 className="search-buttons relative flex items-center justify-between font-semibold">
                <div
                  // type="submit"
                  className="bg-brown-main-bg mr-2 flex w-auto cursor-pointer items-center gap-2 rounded 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="bg-brown-main-bg absolute top-11 z-10 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>
          )}
        </form>
      </div>
      {isLoading ? (
        <SkeletonLoader />
      ) : (
        <div className="overflow-x-auto rounded-md border border-[#0003] shadow ">
          <table className="min-w-full divide-y divide-[#1f1d1a]/10">
            <thead>
              <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="font-iowan-regular divide-y divide-[#1f1d1a]/10">
              {data.map((row, i) => {
                return (
                  <tr className="  md:h-[60px]" key={i}>
                    {columns.map((cell, index) => {
                      if (cell.accessor == "") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          ></td>
                        );
                      }
                      if (cell.mapping) {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {cell.mapping[row[cell.accessor]]}
                          </td>
                        );
                      }
                      if (cell.type === "timestamp") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {new Date(row[cell.accessor] * 1000).toLocaleString(
                              "en-US"
                            )}
                          </td>
                        );
                      } else if (cell.type === "currency") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            ${Number(row[cell.accessor] / 100).toFixed(2)}
                          </td>
                        );
                      } else if (cell.type === "metadata") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.pre_accessor][cell.accessor] ?? "n/a"}
                          </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}
      />
    </>
  );
};

export default AdminStripeInvoicesListPageV2;
