import React from "react";
import { useExpenseTransactions } from "../../hooks/useExpense";
import Error from "../common/Error";
import { formatUTCToLocalTime } from "../../utils/dateUtils";

const AdvancePaymentList = ({ employeeId }) => {
  const { data, isError, isLoading, error } =
    useExpenseTransactions(employeeId);

  const records = data?.json || [];

  let currentBalance = 0;

  const rowsWithBalance = data?.map((r) => {
    const isCredit = r.amount > 0;
    const credit = isCredit ? r.amount : 0;
    const debit = !isCredit ? Math.abs(r.amount) : 0;
    currentBalance += credit - debit;

    return {
      id: r.id,
      description: r.title,
      projectName: r.project?.name,
      createdAt: r.createdAt,
      credit,
      debit,
      balance: currentBalance,
    };
  });

  const columns = [
    { key: "description", label: "Description", align: "text-start" },
    {
      key: "credit",
      label: (
        <span>
          Credit (<i className="bx bx-rupee text-success"></i>)
        </span>
      ),
      align: "text-end",
    },
    {
      key: "debit",
      label: (
        <span>
          Debit (<i className="bx bx-rupee text-danger"></i>)
        </span>
      ),
      align: "text-end",
    },
    {
      key: "balance",
      label: (
        <span>
          Balance <i className="bi bi-currency-rupee text-primary"></i>
        </span>
      ),
      align: "text-end fw-bold",
    },
  ];

  if (isLoading) return <div>Loading...</div>;
  if (isError){
     return <div>{error.status  === 404 ? "No advance payment transactions found." : <Error error={error}/>}</div>
  };

  return (
    <div className="row ">
      <div className="table-responsive">
      {employeeId ? ( <table className="table align-middle">
        <thead className="table_header_border">
          <tr>
            {columns.map((col) => (
              <th key={col.key} className={col.align}>
                {col.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rowsWithBalance?.map((row) => (
            <tr key={row.id}>
              {columns.map((col) => (
                <td key={col.key} className={`${col.align} p-2`}>
                  {["balance", "credit", "debit"].includes(col.key) ? (
                    row[col.key].toLocaleString("en-IN", {
                      style: "currency",
                      currency: "INR",
                    })
                  ) : (
                    <div className="d-flex flex-column text-start ">
                      <small className="text-muted">
                        {formatUTCToLocalTime(row.createdAt)}
                      </small>
                      <small className="fw-semibold text-dark">
                        {row.projectName}
                      </small>
                      <small>{row.description}</small>
                    </div>
                  )}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
        <tfoot className="table-secondary fw-bold">
          <tr>
            <td className="text-start p-3">Final Balance</td>
            <td className="text-end" colSpan="3">
              {currentBalance.toLocaleString("en-IN", {
                style: "currency",
                currency: "INR",
              })}
            </td>
          </tr>
        </tfoot>
      </table>):(
         <div className="d-flex justify-content-center align-items-center" style={{ height: "200px" }}>
        <p className="text-muted  m-0">Please Select Employee</p>
      </div>
      )}
    </div>
    </div>
  );
};

export default AdvancePaymentList;
