import React from "react";
import { Button } from "@mui/material";
import PropTypes from "prop-types";
import { Close } from "@mui/icons-material";
import "./TableDataPopup.css";


function PopupForAuditLogs({ togglePopup, data }) {

  // Parse "key: value" strings into array of objects
  const parseToMap = (part) => {
    if (!part) return [];
    return part.split(",").map((section) => {
      const [key, value] = section.split(":").map((s) => s.trim());
      return { key, value };
    });
  };

  const oldParsed = parseToMap(data?.old_data);
  const newParsed = parseToMap(data?.new_data);

  // Merge based on keys
  const parsedResult = [];
  const allKeys = new Set([
    ...oldParsed.map((o) => o.key),
    ...newParsed.map((n) => n.key),
  ]);

  allKeys.forEach((key) => {
    parsedResult.push({
      data: key,
      old: oldParsed?.find((o) => o.key === key)?.value || "-",
      new: newParsed?.find((n) => n.key === key)?.value || "-",
    });
  });

  return (
    <div className="popup" style={{ backgroundColor: "rgba(0,0,0,0.7)" }}>
      <div className="popup-content">
        <div className="d-flex headingpop">
          <h4 className="Heading">
              Updated By : <span className="text-cap">{data?.changed_by}</span>
            </h4>
          <Button onClick={togglePopup}>
            <Close />
          </Button>
        </div>

        <div className="table-outer">
          <div className="changedby" />

          {/* Table-like structure */}
          <div className="data-for-table wd-100">
            {/* Header row */}
            <div className="d-flex table-header">
              <div className="wd-100 heading-col bold">Name</div>
              <div className="wd-100 heading-col bold">Old Data</div>
              <div className="wd-100 heading-col bold">New Data</div>
            </div>

            {/* Data rows */}
            {parsedResult?.map((item) => (
              <div key={item.id || item.data} className="d-flex table-row">
                <div className="wd-100 old-data">{item?.data}</div>
                <div className="wd-100 old-data">{item?.old}</div>
                <div className="wd-100 new-data">{item?.new}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

PopupForAuditLogs.propTypes = {
  togglePopup: PropTypes.func.isRequired,
  data: PropTypes.shape({
    old_data: PropTypes.string,
    new_data: PropTypes.string,
    changed_by: PropTypes.string,
  })
};


PopupForAuditLogs.defaultProps = {
  data: {
    old_data: "",
    new_data: "",
    changed_by: "",
  }
};


export default PopupForAuditLogs;
