import React, { useState } from "react";
import {
  EXPENSE_DRAFT,
  EXPENSE_REJECTEDBY,
  ITEMS_PER_PAGE,
} from "../../utils/constants";
import {
  formatCurrency,
  getColorNameFromHex,
  useDebounce,
} from "../../utils/appUtils";
import { usePaymentRequestList } from "../../hooks/useExpense";
import { formatDate, formatUTCToLocalTime } from "../../utils/dateUtils";
import Avatar from "../../components/common/Avatar";
import { usePaymentRequestContext } from "../../pages/PaymentRequest/PaymentRequestPage";
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";

const PaymentRequestList = ({ filters, groupBy = "submittedBy", search }) => {
  const { setManageRequest, setVieRequest } = usePaymentRequestContext();
  const navigate = useNavigate();
  const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [deletingId, setDeletingId] = useState(null);
  const SelfId = useSelector(
    (store) => store?.globalVariables?.loginUser?.employeeInfo?.id
  );
  const groupByField = (items, field) => {
    return items.reduce((acc, item) => {
      let key;
      let displayField;

      switch (field) {
        case "transactionDate":
          key = item?.transactionDate?.split("T")[0];
          displayField = "Transaction Date";
          break;
        case "status":
          key = item?.status?.displayName || "Unknown";
          displayField = "Status";
          break;
        case "submittedBy":
          key = `${item?.createdBy?.firstName ?? ""} ${
            item.createdBy?.lastName ?? ""
          }`.trim();
          displayField = "Submitted By";
          break;
        case "project":
          key = item?.project?.name || "Unknown Project";
          displayField = "Project";
          break;
        case "paymentMode":
          key = item?.paymentMode?.name || "Unknown Mode";
          displayField = "Payment Mode";
          break;
        case "expensesType":
          key = item?.expensesType?.name || "Unknown Type";
          displayField = "Expense Category";
          break;
        case "createdAt":
          key = item?.createdAt?.split("T")[0] || "Unknown Date";
          displayField = "Created Date";
          break;
        default:
          key = "Others";
          displayField = "Others";
      }

      const groupKey = `${field}_${key}`; // unique key for object property
      if (!acc[groupKey]) {
        acc[groupKey] = { key, displayField, items: [] };
      }

      acc[groupKey].items.push(item);
      return acc;
    }, {});
  };

  const paymentRequestColumns = [
    {
      key: "paymentRequestUID",
      label: "Request ID",
      align: "text-start mx-2",
      getValue: (e) => e.paymentRequestUID || "N/A",
    },
    {
      key: "title",
      label: "Request Title",
      align: "text-start",
      getValue: (e) => e.title || "N/A",
    },
    // { key: "payee", label: "Payee", align: "text-start" },
    {
      key: "SubmittedBy",
      label: "Submitted By",
      align: "text-start",
      getValue: (e) =>
        `${e.createdBy?.firstName ?? ""} ${
          e.createdBy?.lastName ?? ""
        }`.trim() || "N/A",
      customRender: (e) => (
        <div
          className="d-flex align-items-center cursor-pointer"
          onClick={() => navigate(`/employee/${e.createdBy?.id}`)}
        >
          <Avatar
            size="xs"
            classAvatar="m-0"
            firstName={e.createdBy?.firstName}
            lastName={e.createdBy?.lastName}
          />
          <span className="text-truncate">
            {`${e.createdBy?.firstName ?? ""} ${
              e.createdBy?.lastName ?? ""
            }`.trim() || "N/A"}
          </span>
        </div>
      ),
    },
    {
      key: "createdAt",
      label: "Submitted On",
      align: "text-start",
      getValue: (e) => formatUTCToLocalTime(e?.createdAt),
    },
    {
      key: "amount",
      label: " Amount",
      align: "text-start",
      getValue: (e) => (
        <>
          {formatCurrency(e?.amount)}&nbsp;{e.currency.currencyCode}
        </>
      ),

      align: "text-end px-3",
    },
    {
      key: "expenseStatus",
      label: "Status",
      align: "text-center",
      getValue: (e) => (
        <span
          className={`badge bg-label-${
            getColorNameFromHex(e?.expenseStatus?.color) || "secondary"
          }`}
        >
          {e?.expenseStatus?.name || "Unknown"}
        </span>
      ),
    },
  ];

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

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

  const paymentRequestData = data?.data || [];
  const totalPages = data?.data?.totalPages || 1;

  if (isError) {
    return <Error error={error} isFeteching={isRefetching} refetch={refetch} />;
  }
  const header = [
    "Request ID",
    "Request Title",
    "Submitted By",
    "Submitted On",
    "Amount",
    "Status",
    "Action",
  ];
  if (isLoading) return <ExpenseTableSkeleton headers={header} />;

  const grouped = groupBy
    ? groupByField(data?.data ?? [], groupBy)
    : { All: data?.data ?? [] };
  const IsGroupedByDate = [
    { key: "transactionDate", displayField: "Transaction Date" },
    { key: "createdAt", displayField: "created Date" },
  ]?.includes(groupBy);

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

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

  return (
    <>
      {IsDeleteModalOpen && (
        <ConfirmModal
          isOpen={IsDeleteModalOpen}
          type="delete"
          header="Delete Expense"
          message="Under the woring?"
          onSubmit={handleDelete}
          onClose={() => setIsDeleteModalOpen(false)}
          // loading={isPending}
          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>
                {paymentRequestColumns.map((col) => (
                  <th key={col.key} className={`sorting ${col.align}`}>
                    {col.label}
                  </th>
                ))}
                <th className="text-center">Action</th>
              </tr>
            </thead>

            <tbody>
              {Object.keys(grouped).length > 0 ? (
                Object.values(grouped).map(({ key, displayField, items }) => (
                  <React.Fragment key={key}>
                    <tr className="tr-group text-dark">
                      <td colSpan={8} className="text-start">
                        <div className="d-flex align-items-center">
                          {" "}
                          <small className="fs-6 py-1">
                            {displayField} :{" "}
                          </small>{" "}
                          <small className="fs-6  ms-3">
                            {IsGroupedByDate ? formatUTCToLocalTime(key) : key}
                          </small>
                        </div>
                      </td>
                    </tr>
                    {items?.map((paymentRequest) => (
                      <tr key={paymentRequest.id}>
                        {paymentRequestColumns.map(
                          (col) =>
                            (col.isAlwaysVisible || groupBy !== col.key) && (
                              <td
                                key={col.key}
                                className={`d-table-cell ${col.align ?? ""}`}
                              >
                                {col?.customRender
                                  ? col?.customRender(paymentRequest)
                                  : col?.getValue(paymentRequest)}
                              </td>
                            )
                        )}
                        <td className="sticky-action-column bg-white">
                          <div className="d-flex flex-row gap-2">
                            <i
                              className="bx bx-show text-primary cursor-pointer"
                              onClick={() =>
                                setVieRequest({
                                  requestId: paymentRequest.id,
                                  view: true,
                                })
                              }
                            ></i>
                            {canEditExpense(paymentRequest) && (
                              <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"
                                  aria-expanded="false"
                                >
                                  <i
                                    className="bx bx-dots-vertical-rounded text-muted p-0"
                                    data-bs-toggle="tooltip"
                                    data-bs-offset="0,8"
                                    data-bs-placement="top"
                                    data-bs-custom-class="tooltip-dark"
                                    title="More Action"
                                  ></i>
                                </button>
                                <ul className="dropdown-menu dropdown-menu-end w-auto">
                                  <li
                                    onClick={() =>
                                      setManageRequest({
                                        IsOpen: true,
                                        RequestId: paymentRequest.id,
                                      })
                                    }
                                  >
                                    <a className="dropdown-item px-2 cursor-pointer py-1">
                                      <i className="bx bx-edit text-primary  bx-xs me-2"></i>
                                      <span className="align-left ">
                                        Modify
                                      </span>
                                    </a>
                                  </li>

                                  {canDetetExpense(paymentRequest) && (
                                    <li
                                      onClick={() => {
                                        setIsDeleteModalOpen(true);
                                        setDeletingId(paymentRequest.id);
                                      }}
                                    >
                                      <a className="dropdown-item  px-2 cursor-pointer py-1">
                                        <i className="bx bx-trash text-danger  bx-xs me-2"></i>
                                        <span className="align-left">
                                          Delete
                                        </span>
                                      </a>
                                    </li>
                                  )}
                                </ul>
                              </div>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </React.Fragment>
                ))
              ) : (
                <tr>
                  <td colSpan={8} className="text-center border-0 ">
                    <div className="py-8">
                      <p>No Request Found</p>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="d-flex justify-content-end py-3 pe-3">
            <nav>
              <ul className="pagination mb-0">
                {[...Array(totalPages)].map((_, index) => (
                  <li
                    key={index}
                    className={`page-item ${
                      currentPage === index + 1 ? "active" : ""
                    }`}
                  >
                    <button
                      className="page-link"
                      onClick={() => setCurrentPage(index + 1)}
                    >
                      {index + 1}
                    </button>
                  </li>
                ))}
              </ul>
            </nav>
          </div>
        )}
      </div>
    </>
  );
};

export default PaymentRequestList;
