import React, { useState } from "react";
import { useDeleteExpense, useExpenseList } from "../../hooks/useExpense";
import Avatar from "../common/Avatar";
import { useExpenseContext } from "../../pages/Expense/ExpensePage";
import { formatDate, formatUTCToLocalTime } from "../../utils/dateUtils";
import Pagination from "../common/Pagination";
import {
  APPROVE_EXPENSE,
  EXPENSE_DRAFT,
  EXPENSE_REJECTEDBY,
  ITEMS_PER_PAGE,
} from "../../utils/constants";
import {
  formatCurrency,
  getColorNameFromHex,
  useDebounce,
} from "../../utils/appUtils";
import { ExpenseTableSkeleton } from "./ExpenseSkeleton";
import ConfirmModal from "../common/ConfirmModal";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { useSelector } from "react-redux";
import ExpenseFilterChips from "./ExpenseFilterChips";
import { defaultFilter } from "./ExpenseSchema";
import { useNavigate } from "react-router-dom";

const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
  const [deletingId, setDeletingId] = useState(null);
  const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const { setViewExpense, setManageExpenseModal, filterData, removeFilterChip } = useExpenseContext();
  const IsExpenseEditable = useHasUserPermission();
  const IsExpesneApprpve = useHasUserPermission(APPROVE_EXPENSE);
  const [currentPage, setCurrentPage] = useState(1);
  const debouncedSearch = useDebounce(searchText, 500);
  const navigate = useNavigate();


  const { mutate: DeleteExpense, isPending } = useDeleteExpense();
  const { data, isLoading, isError, isInitialLoading, error } = useExpenseList(
    ITEMS_PER_PAGE,
    currentPage,
    filters,
    debouncedSearch
  );

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

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

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

  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 expenseColumns = [
    {
      key: "expenseUId",
      label: "Expense Id",
      getValue: (e) => e.expenseUId || "N/A",
      align: "text-start mx-2",
    },
    {
      key: "expensesType",
      label: "Expense Type",
      getValue: (e) => e.expensesType?.name || "N/A",
      align: "text-start",
    },
    {
      key: "paymentMode",
      label: "Payment Mode",
      getValue: (e) => e.paymentMode?.name || "N/A",
      align: "text-start",
    },
    {
      key: "Submitted By",
      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: "submitted",
      label: "Submitted",
      getValue: (e) => formatUTCToLocalTime(e?.createdAt),
      isAlwaysVisible: true,
    },
    {
      key: "amount",
      label: "Amount",
      getValue: (e) => <>{formatCurrency(e?.amount)}</>,
      isAlwaysVisible: true,
      align: "text-end",
    },
    {
      key: "status",
      label: "Status",
      align: "text-center",
      getValue: (e) => (
        <span
          className={`badge bg-label-${getColorNameFromHex(e?.status?.color) || "secondary"
            }`}
        >
          {e.status?.name || "Unknown"}
        </span>
      ),
    },
  ];

  if (isInitialLoading && !data) return <ExpenseTableSkeleton />;
  if (isError) return <div>{error?.message}</div>;

  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 = (expense) => {
    return (
      (expense?.status?.id === EXPENSE_DRAFT ||
        EXPENSE_REJECTEDBY.includes(expense?.status?.id)) &&
      expense?.createdBy?.id === SelfId
    );
  };

  const canDetetExpense = (expense) => {
    return (
      expense?.status?.id === EXPENSE_DRAFT && expense?.createdBy?.id === SelfId
    );
  };


  return (
    <>
      {IsDeleteModalOpen && (
        <ConfirmModal
          isOpen={IsDeleteModalOpen}
          type="delete"
          header="Delete Expense"
          message="Are you sure you want delete?"
          onSubmit={handleDelete}
          onClose={() => setIsDeleteModalOpen(false)}
          loading={isPending}
          paramData={deletingId}
        />
      )}

      <div className="card page-min-h px-sm-4">
        {/* Filter Chips */}
        <ExpenseFilterChips
          filters={filters}
          filterData={filterData}
          removeFilterChip={removeFilterChip}
          groupBy={groupBy}
        />
        <div
          className="card-datatable table-responsive "
          id="horizontal-example"
        >



          <div className="dataTables_wrapper no-footer px-2 ">
            <table className="table border-top dataTable text-nowrap">
              <thead>
                <tr>
                  {expenseColumns.map(
                    (col) =>
                      (col.isAlwaysVisible || groupBy !== col.key) && (
                        <th
                          key={col.key}
                          className={`sorting d-table-cell`}
                          aria-sort="descending"
                        >
                          <div className={`${col.align}`}>{col.label}</div>
                        </th>
                      )
                  )}
                  <th className="sticky-action-column bg-white 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((expense) => (
                        <tr key={expense.id}>
                          {expenseColumns.map(
                            (col) =>
                              (col.isAlwaysVisible || groupBy !== col.key) && (
                                <td
                                  key={col.key}
                                  className={`d-table-cell ${col.align ?? ""}`}
                                >
                                  {col.customRender
                                    ? col.customRender(expense)
                                    : col.getValue(expense)}
                                </td>
                              )
                          )}
                          <td className="sticky-action-column bg-white">
                            <div className="d-flex justify-content-center gap-2">
                              <i
                                className="bx bx-show text-primary cursor-pointer"
                                onClick={() =>
                                  setViewExpense({
                                    expenseId: expense.id,
                                    view: true,
                                  })
                                }
                              ></i>
                              {canDetetExpense(expense) &&
                                canEditExpense(expense) && (
                                  <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">
                                      {canDetetExpense(expense) && (
                                        <li
                                          onClick={() =>
                                            setManageExpenseModal({
                                              IsOpen: true,
                                              expenseId: expense.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(expense) && (
                                        <li
                                          onClick={() => {
                                            setIsDeleteModalOpen(true);
                                            setDeletingId(expense.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 Expense Found</p>
                      </div>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
            {data?.data?.length > 0 && (
              <Pagination
                currentPage={currentPage}
                totalPages={data.totalPages}
                onPageChange={paginate}
              />
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default ExpenseList;
