import React, { useState } from "react";
import {
  EXPENSE_DRAFT,
  EXPENSE_REJECTEDBY,
  FREQUENCY_FOR_RECURRING,
  ITEMS_PER_PAGE,
  PAYEE_RECURRING_EXPENSE,
} from "../../utils/constants";
import { formatCurrency, useDebounce } from "../../utils/appUtils";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { ExpenseTableSkeleton } from "../Expenses/ExpenseSkeleton";
import ConfirmModal from "../common/ConfirmModal";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import Error from "../common/Error";
import { useRecurringExpenseContext } from "../../pages/RecurringExpense/RecurringExpensePage";
import { useRecurringExpenseList } from "../../hooks/useExpense";
import Pagination from "../common/Pagination";

const RecurringExpenseList = ({ search, filterStatuses }) => {
  const { setManageRequest, setVieRequest, setViewRecurring } = useRecurringExpenseContext();
  const navigate = useNavigate();
  const [IsDeleteModalOpen, setIsDeleteModalOpen,] = useState(false);
  const [deletingId, setDeletingId] = useState(null);

  const SelfId = useSelector(
    (store) => store?.globalVariables?.loginUser?.employeeInfo?.id
  );

  const statusColorMap = {
    "da462422-13b2-45cc-a175-910a225f6fc8": "primary",      // Active
    "306856fb-5655-42eb-bf8b-808bb5e84725": "success",      // Completed
    "3ec864d2-8bf5-42fb-ba70-5090301dd816": "danger",       // De-Activated
    "8bfc9346-e092-4a80-acbf-515ae1ef6868": "warning",      // Paused
  };

  const recurringExpenseColumns = [
    {
      key: "expenseCategory",
      label: "Category",
      align: "text-start",
      getValue: (e) => e?.expenseCategory?.name || "N/A",
    },
    {
      key: "title",
      label: "Title",
      align: "text-start",
      getValue: (e) => e?.title || "N/A",
    },
    {
      key: "payee",
      label: "Payee",
      align: "text-start",
      getValue: (e) => e?.payee || "N/A",
    },
    {
      key: "frequency",
      label: "Frequency",
      align: "text-start",
      getValue: (e) =>
        e?.frequency !== undefined && e?.frequency !== null
          ? FREQUENCY_FOR_RECURRING[e.frequency] || "N/A"
          : "N/A",
    },
    {
      key: "amount",
      label: "Amount",
      align: "text-end",
      getValue: (e) =>
        e?.amount
          ? `${e?.currency?.symbol || ""}${e.amount.toLocaleString()}`
          : "N/A",
    },
    {
      key: "createdAt",
      label: "Next Generation Date",
      align: "text-center",
      getValue: (e) =>
        e?.createdAt ? formatUTCToLocalTime(e.createdAt) : "N/A",
    },
    {
      key: "status",
      label: "Status",
      align: "text-center",
      getValue: (e) => {
        const color = statusColorMap[e?.status?.id] || "secondary";
        const label = PAYEE_RECURRING_EXPENSE.find(
          (s) => s.id === e?.status?.id
        )?.label;
        return (
          <span className={`badge bg-label-${color}`}>
            {label || e?.status?.name || "N/A"}
          </span>
        );
      },
    },
  ];

  const [currentPage, setCurrentPage] = useState(1);
  const debouncedSearch = useDebounce(search, 500);

  const { data, isLoading, isError, error, isRefetching, refetch } =
    useRecurringExpenseList(
      ITEMS_PER_PAGE,
      currentPage,
      {},
      true,
      debouncedSearch
    );


   const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };

  if (isError) {
    return <Error error={error} isFeteching={isRefetching} refetch={refetch} />;
  }

  const header = [
    "Category",
    "Title",
    "Amount",
    "Payee",
    "Frequency",
    "Next Generation",
    "Status",
    "Action",
  ];

  if (isLoading) return <ExpenseTableSkeleton headers={header} />;

  const canEditExpense = (recurringExpense) => {
    // return (
    //     (recurringExpense?.expenseStatus?.id === EXPENSE_DRAFT ||
    //         EXPENSE_REJECTEDBY.includes(recurringExpense?.expenseStatus.id)) &&
    //     recurringExpense?.createdBy?.id === SelfId
    // );
  };

  const canDeleteExpense = (request) => {
    return (
      request?.expenseStatus?.id === EXPENSE_DRAFT &&
      request?.createdBy?.id === SelfId
    );
  };

  const filteredData = data?.data?.filter((item) =>
    filterStatuses.includes(item?.status?.id)
  );

  const handleDelete = (id) => {
    setDeletingId(id);
    DeleteExpense(
      { id },
      {
        onSettled: () => {
          setDeletingId(null);
          setIsDeleteModalOpen(false);
        },
      }
    );
  };

  return (
    <>
      {IsDeleteModalOpen && (
        <ConfirmModal
          isOpen={IsDeleteModalOpen}
          type="delete"
          header="Delete Recurring Expense"
          message="Under the working"
          onSubmit={handleDelete}
          onClose={() => setIsDeleteModalOpen(false)}
          paramData={deletingId}
        />
      )}

      <div className="card page-min-h table-responsive px-sm-4">
        <div className="card-datatable" id="payment-request-table">
          <table className="table border-top dataTable text-nowrap align-middle">
            <thead>
              <tr>
                {recurringExpenseColumns.map((col) => (
                  <th key={col.key} className={`sorting ${col.align}`}>
                    {col.label}
                  </th>
                ))}
                <th className="text-center">Action</th>
              </tr>
            </thead>

            <tbody>
              {filteredData?.length > 0 ? (
                filteredData?.map((recurringExpense) => (
                  <tr
                    key={recurringExpense.id}
                    className="align-middle"
                    style={{ height: "50px" }}
                  >
                    {recurringExpenseColumns.map((col) => (
                      <td
                        key={col.key}
                        className={`d-table-cell ${col.align ?? ""} py-3`}
                      >
                        {col?.customRender
                          ? col?.customRender(recurringExpense)
                          : col?.getValue(recurringExpense)}
                      </td>
                    ))}
                    <td className="sticky-action-column bg-white">
                      <div className="d-flex flex-row gap-2 gap-0">
                        <i
                          className="bx bx-show text-primary cursor-pointer"
                          onClick={() =>
                            setViewRecurring({
                              recurringId: recurringExpense?.id,
                              view: true,
                            })
                          }
                        ></i>

                        <div className="dropdown z-2">
                          <button
                            type="button"
                            className="btn btn-xs btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0 m-0"
                            data-bs-toggle="dropdown"
                          >
                            <i className="bx bx-dots-vertical-rounded text-muted p-0"></i>
                          </button>
                          <ul className="dropdown-menu dropdown-menu-end w-auto">
                            <li
                              onClick={() =>
                                setManageRequest({
                                  IsOpen: true,
                                  RecurringId: recurringExpense?.id,
                                })
                              }
                            >
                              <a className="dropdown-item px-2 cursor-pointer py-1">
                                <i className="bx bx-edit text-primary bx-xs me-2"></i>
                                Modify
                              </a>
                            </li>

                            <li
                              onClick={() => {
                                setIsDeleteModalOpen(true);
                                setDeletingId(recurringExpense.id);
                              }}
                            >
                              <a className="dropdown-item px-2 cursor-pointer py-1">
                                <i className="bx bx-trash text-danger bx-xs me-2"></i>
                                Delete
                              </a>
                            </li>
                          </ul>
                        </div>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td
                    colSpan={recurringExpenseColumns?.length + 1}
                    className="text-center border-0 py-8"
                  >
                    <p>No Recurring Expense Found</p>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
      <Pagination
                currentPage={currentPage}
                totalPages={data?.totalPages}
                onPageChange={paginate}
              />
      </div>
    </>
  );
};

export default RecurringExpenseList;
