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 Skeleton from "react-loading-skeleton";
import { ModalSidebar } from "Components/ModalSidebar";
import * as yup from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { BiFilterAlt, BiSearch } from "react-icons/bi";
import { AiOutlineClose, AiOutlinePlus } from "react-icons/ai";
import { RiDeleteBin5Line } from "react-icons/ri";
import AddAdminEmailPage from "../Add/AddAdminEmailPage";
import EditAdminEmailPage from "../Edit/EditAdminEmailPage";
import AddButton from "Components/AddButton";

let sdk = new MkdSDK();

const columns = [
  {
    header: "ID",
    accessor: "id",
  },
  {
    header: "Email Type",
    accessor: "slug",
  },
  {
    header: "Subject",
    accessor: "subject",
  },
  {
    header: "Tags",
    accessor: "tag",
  },
  {
    header: "Action",
    accessor: "",
  },
];

const AdminEmailListPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const [data, setCurrentTableData] = React.useState([]);
  const [loadingData, setLoadingData] = React.useState(false);
  const [showAddSidebar, setShowAddSidebar] = React.useState(false);
  const [showEditSidebar, setShowEditSidebar] = React.useState(false);
  const [activeEditId, setActiveEditId] = React.useState();
  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 navigate = useNavigate();

  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const schema = yup.object({
    page: yup.string(),
    key: yup.string(),
    type: yup.string(),
  });

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

  const onSubmit = (data) => {
    let page = getNonNullValue(data.page);
    let key = getNonNullValue(data.key);
    let type = getNonNullValue(data.type);
    let filter = { page, content_key: key, content_type: type };
    getData(0, 10, filter);
  };

  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);
  };

  async function getData() {
    try {
      sdk.setTable("email");
      const result = await sdk.callRestAPI({}, "GETALL");

      const { list } = result;

      setCurrentTableData(list);
    } catch (error) {
      console.log("ERROR", error);
      tokenExpireError(dispatch, error.message);
    }
  }

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

    (async function () {
      setLoadingData(true);
      await getData();
      setLoadingData(false);
    })();
  }, []);

  return (
    <>
      <div className="bg-brown-main-bg overflow-x-auto rounded p-5 ">
        <div className="mb-6 flex w-full justify-between text-center ">
          {/* <h4 className="md:text-xl font-medium text-[16px]">Emails </h4> */}
          <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)
                      }
                    />

                    <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>
          <AddButton onClick={() => setShowAddSidebar(true)} />
        </div>
        <div className="overflow-x-auto shadow ">
          <table className="min-w-full divide-y divide-[#1f1d1a]/10">
            <thead>
              <tr>
                {columns.map((column, i) => (
                  <th
                    key={i}
                    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.length == 0 ? (
                <tr>
                  <td colSpan={5}>{loadingData && <Skeleton count={4} />}</td>
                </tr>
              ) : null}
              {console.log(data)}
              {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"
                          >
                            <button
                              className="cursor-pointer text-xs text-[#4F46E5]"
                              onClick={() => {
                                setActiveEditId(row.id);
                                setShowEditSidebar(true);
                                // navigate("/admin/edit-email/" + row.id, {
                                //   state: row,
                                // });
                              }}
                            >
                              {" "}
                              Edit
                            </button>
                          </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>
      </div>
      <ModalSidebar
        isModalActive={showAddSidebar}
        closeModalFn={() => setShowAddSidebar(false)}
      >
        <AddAdminEmailPage setSidebar={setShowAddSidebar} />
      </ModalSidebar>
      <ModalSidebar
        isModalActive={showEditSidebar}
        closeModalFn={() => setShowEditSidebar(false)}
      >
        <EditAdminEmailPage
          activeId={activeEditId}
          setSidebar={setShowEditSidebar}
        />
      </ModalSidebar>
    </>
  );
};

export default AdminEmailListPage;
