import React, { Fragment, useState, useEffect } from "react";
import { LazyLoad } from "Components/LazyLoad";
import { ModalSidebar } from "Components/ModalSidebar";
import { TrashIcon, PencilIcon, MoreVertical } from "Assets/svgs";
import { useContexts } from "Hooks/useContexts";
import { GlobalContext } from "Src/globalContext";
import { ClipLoader } from "react-spinners";
import PaginationBar from "Components/PaginationBar";
import MkdSDK from "Utils/MkdSDK";
import AddButton from "Components/AddButton";
import ConfirmModal from "Components/Modal/ConfirmModal";
import { retrieveAllUserAPI } from "Src/services/userService";

import { PlusIcon } from "@heroicons/react/24/outline";
import CouponForm from "Components/Forms/CouponForm";

const columns = [
  {
    header: "Name",
    accessor: "name",
  },
  {
    header: "Code",
    accessor: "code",
  },
  {
    header: "Discount",
    accessor: "discountAmount",
    render: (row) => {
      return row.discountType === "percentage"
        ? `${row.discountAmount}%`
        : `$${row.discountAmount}`;
    },
  },
  {
    header: "Duration",
    accessor: "durationInMonths",
    render: (row) => `${row.durationInMonths} months`,
  },
  {
    header: "Expires",
    accessor: "expiresAt",
    render: (row) => new Date(row.expiresAt).toLocaleDateString(),
  },
  {
    header: "Max Uses",
    accessor: "maxRedemptions",
  },
  {
    header: "Min Amount",
    accessor: "minimumAmount",
    render: (row) => `$${row.minimumAmount}`,
  },
];

const AdminCouponsListPage = () => {
  const { globalDispatch, deleteOne, showToast } = useContexts();
  const [currentTableData, setCurrentTableData] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pageCount, setPageCount] = useState(0);
  const [dataTotal, setDataTotal] = useState(0);
  const [currentPage, setPage] = useState(1);
  const [canPreviousPage, setCanPreviousPage] = useState(false);
  const [canNextPage, setCanNextPage] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedItemId, setSelectedItemId] = useState(null);
  const [formYes, setFormYes] = useState(false);
  const [showActionMenu, setShowActionMenu] = useState(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);
  const [users, setUsers] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingCoupon, setEditingCoupon] = useState(null);
  const [plans, setPlans] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const sdk = new MkdSDK();

  const onToggleDeleteModal = (show, id = null) => {
    setShowActionMenu(null);
    setShowDeleteModal(show);
    setSelectedItemId(id);
  };

  const handleEdit = (item) => {
    setShowActionMenu(null);
    setSelectedItem(item);
    setIsEditModalOpen(true);
  };

  const toggleActionMenu = (id) => {
    setShowActionMenu(showActionMenu === id ? null : id);
  };

  const onRemove = async (id = null) => {
    try {
      setIsDeleting(true);
      const sdk = new MkdSDK();
      const result = await sdk.callRestAPI(
        `/v3/api/custom/equality_record/subscription/coupon/${id}`,
        {},
        "DELETE"
      );

      if (!result?.error) {
        showToast("Coupon Deleted", 5000, "success");
        getData(currentPage, pageSize);
      }
    } catch (error) {
      showToast(error.message, 5000, "error");
    } finally {
      onToggleDeleteModal(false);
      setIsDeleting(false);
      setFormYes(false);
    }
  };

  const getData = async (pageNum, limitNum) => {
    setIsLoading(true);
    const sdk = new MkdSDK();
    try {
      const result = await sdk.getCoupons();
      console.log(result);
      if (!result?.error) {
        console.log(result, "result");
        setCurrentTableData(result?.coupons || []);
        setPageCount(result?.num_pages || 1);
        setPage(pageNum);
        setDataTotal(result?.total || 0);
        setCanPreviousPage(pageNum > 1);
        setCanNextPage(pageNum + 1 <= result?.num_pages);
      }
    } catch (error) {
      showToast(error?.message, 5000, "error");
    } finally {
      setIsLoading(false);
    }
  };

  const retrieveAllUsers = async () => {
    try {
      let filter = {
        role: "member",
      };
      const result = await retrieveAllUserAPI(1, 10000, filter);
      if (!result?.error) {
        if (result.list.length > 0) {
          let list = result.list;
          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return row;
          });
          list = list.sort((a, b) => {
            return a.user_name.localeCompare(b.user_name);
          });
          setUsers(list);
        }
      }
    } catch (error) {
      showToast(error?.message, 5000, "error");
    }
  };

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

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

  function nextPage() {
    getData(currentPage + 1, pageSize);
  }

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

  React.useEffect(() => {
    if (formYes && selectedItemId) {
      onRemove(selectedItemId);
    }
  }, [formYes]);

  const fetchPlans = async () => {
    try {
      const response = await sdk.callRawAPI(
        `/v4/api/records/stripe_product?page=${1}&limit=${100}`,
        [],
        "GET"
      );
      setPlans(response.list || []);
    } catch (err) {}
  };

  useEffect(() => {
    fetchPlans();
  }, []);

  const handleCreateCoupon = async (data) => {
    console.log(data, "shsh");
    try {
      setIsSubmitting(true);
      await sdk.createCoupon(data);
      showToast("Coupon created successfully", 5000, "success");
      setShowForm(false);
      setEditingCoupon(null);
      getData(1, pageSize);
    } catch (err) {
      showToast(err.message, 5000, "error");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleUpdateCoupon = async (data) => {
    try {
      setIsSubmitting(true);
      await sdk.updateCoupon(editingCoupon.id, data);
      showToast("Coupon updated successfully", 5000, "success");
      setShowForm(false);
      setEditingCoupon(null);
      getData(1, pageSize);
    } catch (err) {
      showToast(err.message, 5000, "error");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDeleteCoupon = async (couponId) => {
    if (!window.confirm("Are you sure you want to delete this coupon?")) {
      return;
    }

    try {
      await sdk.deleteCoupon(couponId);
      showToast("Coupon deleted successfully", 5000, "success");
      getData(1, pageSize);
    } catch (err) {
      showToast(err.message, 5000, "error");
    }
  };

  const handleEditCoupon = (coupon) => {
    setEditingCoupon(coupon);
    setShowForm(true);
  };

  return (
    <div className="custom-overflow min-h-[140px] overflow-x-auto">
      <div className="flex justify-between items-center px-4 py-4 border-b border-strokedark md:px-6 2xl:px-9">
        <h4 className="text-xl font-semibold text-white">Coupons</h4>
        <button
          type="button"
          className="inline-flex justify-center items-center px-4 py-2 h-9 text-sm font-medium text-white rounded bg-primary hover:bg-opacity-90"
          onClick={() => {
            setEditingCoupon(null);
            setShowForm(true);
          }}
        >
          <PlusIcon className="w-5 h-5" />
          Add Coupon
        </button>
      </div>

      <div className="p-4 md:p-6 2xl:p-10">
        <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-xs font-medium tracking-wider text-left uppercase text-bodydark1"
                >
                  {column.header}
                </th>
              ))}
              <th className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase text-bodydark1">
                Action
              </th>
            </tr>
          </thead>
          {!isLoading && currentTableData.length > 0 ? (
            <tbody className="text-white cursor-pointer">
              {currentTableData.map((row, i) => (
                <tr
                  key={i}
                  className="border-b border-strokedark hover:bg-primary/5"
                >
                  {columns.map((cell, index) => (
                    <td key={index} className="px-6 py-4 whitespace-nowrap">
                      {cell.render ? cell.render(row) : row[cell.accessor]}
                    </td>
                  ))}
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="relative">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          toggleActionMenu(row.id);
                        }}
                        className="p-1 rounded-full hover:bg-meta-4"
                      >
                        <MoreVertical className="w-5 h-5 text-white" />
                      </button>

                      {showActionMenu === row.id && (
                        <div className="absolute right-0 z-10 mt-2 w-48 rounded-md border shadow-lg border-strokedark bg-boxdark">
                          <div className="py-1">
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                handleEditCoupon(row);
                              }}
                              className="flex items-center px-4 py-2 w-full text-sm text-white hover:bg-primary/5"
                            >
                              <PencilIcon className="mr-2 w-4 h-4" />
                              Edit
                            </button>
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                onToggleDeleteModal(true, row.id);
                              }}
                              className="flex items-center px-4 py-2 w-full text-sm text-danger hover:bg-primary/5"
                            >
                              <TrashIcon className="mr-2 w-4 h-4" />
                              Delete
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          ) : isLoading ? (
            <tbody>
              <tr>
                <td colSpan={columns.length + 1} className="text-center">
                  <span className="relative p-4 pb-8 m-4 text-xl font-semibold text-white whitespace-nowrap ease-out animate-pulse trans">
                    <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                    Loading Coupons...
                  </span>
                </td>
              </tr>
            </tbody>
          ) : (
            <tbody>
              <tr>
                <td colSpan={columns.length + 1} className="text-center">
                  <span className="relative top-[10px] m-4 p-4 font-semibold text-white">
                    No data found
                  </span>
                </td>
              </tr>
            </tbody>
          )}
        </table>

        {/* Pagination */}
        {currentTableData.length > 0 && !isLoading && (
          <div className="px-4 py-10 w-full">
            <PaginationBar
              currentPage={currentPage}
              pageCount={pageCount}
              pageSize={pageSize}
              canPreviousPage={canPreviousPage}
              canNextPage={canNextPage}
              updatePageSize={updatePageSize}
              previousPage={previousPage}
              nextPage={nextPage}
              dataTotal={dataTotal}
            />
          </div>
        )}
      </div>

      {showDeleteModal && (
        <ConfirmModal
          confirmText="Are you sure you want to delete this coupon?"
          setModalClose={setShowDeleteModal}
          setFormYes={setFormYes}
        />
      )}

      {showForm && (
        <div className="flex fixed inset-0 z-50 justify-center items-center">
          <div
            className="fixed inset-0 backdrop-blur-sm bg-black/50"
            onClick={() => {
              setShowForm(false);
              setEditingCoupon(null);
            }}
          />
          <div className="w-full max-w-xl rounded border transition-all transform shadow-default border-strokedark bg-boxdark">
            <div className="shadow-default sm:p-7.5 bg-w k w-full max-w-xl rounded-sm border border-stroke/50 bg-boxdark p-5">
              <div className="mb-6">
                <h4 className="text-xl font-semibold text-white">
                  {editingCoupon ? "Edit" : "Create"} Coupon
                </h4>
              </div>
              <CouponForm
                onSubmit={
                  editingCoupon ? handleUpdateCoupon : handleCreateCoupon
                }
                initialData={editingCoupon}
                plans={plans}
                isSubmitting={isSubmitting}
              />
            </div>
          </div>{" "}
        </div>
      )}
    </div>
  );
};

export default AdminCouponsListPage;
