import { useState,useMemo } from "react";
import Avatar from "../common/Avatar";
import { formatUTCToLocalTime } from "../../utils/dateUtils";


const ExpenseStatusLogs = ({ data }) => {
  const [visibleCount, setVisibleCount] = useState(4);

  const sortedLogs = useMemo(() => {
    if (!data?.expenseLogs) return [];
    return [...data.expenseLogs].sort(
      (a, b) => new Date(b.updateAt) - new Date(a.updateAt)
    );
  }, [data?.expenseLogs]);

  const logsToShow = sortedLogs.slice(0, visibleCount);

  const handleShowMore = () => {
    setVisibleCount((prev) => prev + 4);
  };

  return (
    <>
      <div className="row g-2">
        {logsToShow.map((log) => (
          <div key={log.id} className="col-12 d-flex align-items-start mb-1">
            <Avatar
              size="xs"
              firstName={log.updatedBy.firstName}
              lastName={log.updatedBy.lastName}
            />

            <div className="flex-grow-1">
              <div className="text-start">
                <div className="flex">
                  <span>{`${log.updatedBy.firstName} ${log.updatedBy.lastName}`}</span>
                  <small className="text-secondary text-tiny ms-2">
                    <em>{log.action}</em>
                  </small>
                  <span className="text-tiny text-secondary d-block" >
                    {formatUTCToLocalTime(log.updateAt,true)}
                  </span>
                </div>
                <div className="d-flex align-items-center text-muted small mt-1">
                  <span>{log.comment}</span>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {sortedLogs.length > visibleCount && (
        <div className="text-center my-1">
          <button
            className="btn btn-xs btn-outline-primary"
            onClick={handleShowMore}
          >
            Show More
          </button>
        </div>
      )}
    </>
  );
};


export default ExpenseStatusLogs;
