import React, { useState } from "react";
import { FwToggle, FwIcon } from "@freshworks/crayons/react";

const calculateLastModified = (updated_at) => {
  const updatedDate = new Date(updated_at);
  const currentDate = new Date();
  const diffInMilliseconds = currentDate - updatedDate;
  const seconds = Math.floor(diffInMilliseconds / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const months = Math.floor(days / 30);
  const years = Math.floor(days / 365);

  if (years > 0) return years === 1 ? "a year ago" : `${years} years ago`;
  if (months > 0) return months === 1 ? "a month ago" : `${months} months ago`;
  if (days > 0) return `${days} day${days > 1 ? "s" : ""} ago`;
  if (hours > 0) return `${hours} hour${hours > 1 ? "s" : ""} ago`;
  if (minutes > 0) return `${minutes} minute${minutes > 1 ? "s" : ""} ago`;
  return "Just now";
};

const AutomationCard = ({
  rule = {},
  index,
  isFirstInGroup = false,
  onDelete,
  agent,
  activeTab,
  onSelect,
}) => {
  const {
    id,
    name = "Default Rule Name",
    summary = "",
    description = "",
    updated_at = "N/A",
    last_updated_by = "Unknown",
    affected_tickets_count = "--",
    active = false,
    position = position,
    automation_type_id,
  } = rule;

  const [menuOpen, setMenuOpen] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  const handleConfirmDelete = () => {
    setShowDeleteModal(false);
    if (onDelete) onDelete(rule);
  };

  const handleClick = () => {
    if (onSelect) {
      onSelect(rule);
    }
  };

  // const renderAgentName = () => {

  //   if (rule.agentName) {
  //     return rule.agentName;
  //   }
    
  //   const foundAgent = agent.find((e) => e.value === last_updated_by);

  //   return foundAgent ? foundAgent.text : last_updated_by || "Unknown";
  // };


  const renderAgentName = () => {
    if (rule.agentName) {
      return rule.agentName;
    }
  
    if (!agent || !Array.isArray(agent)) {
      // agent data not ready or invalid
      return last_updated_by || "Unknown";
    } else {
      const foundAgent = agent.find((e) => e.value === last_updated_by);
      return foundAgent ? foundAgent.text : last_updated_by || "Unknown";
    }
  };

  function extractText(htmlString) {
    if (!htmlString || typeof htmlString !== "string") return "";
    let text = htmlString.replace(/<[^>]+>/g, "").trim();
    if (text.toLowerCase().startsWith("if ")) {
      text = text.substring(3).trim();
    }
    return text.toLowerCase();
  }

  function generateSummary(summary) {
    if (!summary) return "";

    if (typeof summary === "string") {
      return summary;
    }

    let conditionTexts = [];
    if (summary.conditions) {
      for (const setKey in summary.conditions) {
        if (Object.prototype.hasOwnProperty.call(summary.conditions, setKey)) {
          const conditionsVal = summary.conditions[setKey];
          const conditionsArray = Array.isArray(conditionsVal) ? conditionsVal : [conditionsVal];
          const cleanConditions = conditionsArray.map(extractText);
          conditionTexts.push(cleanConditions.join(", "));
        }
      }
    }

    const conditionsStr = conditionTexts.join(", ");

    let actionsStr = "";
    if (summary.actions && Array.isArray(summary.actions)) {
      const cleanActions = summary.actions.map(extractText);
      actionsStr = cleanActions.join(", ");
    }

    if (conditionsStr && actionsStr) {
      return `if ${conditionsStr}, then ${actionsStr}`;
    } else if (conditionsStr) {
      return `if ${conditionsStr}`;
    } else if (actionsStr) {
      return actionsStr;
    }

    return "";
  }

  function MenuList({ visible, onEdit, onClone, onDelete }) {
    return (
      <ul
        style={{
          position: "absolute",
          backgroundColor: "white",
          boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
          borderRadius: 4,
          padding: "8px 0",
          minWidth: 160,
          right: 0,
          top: 28,
          listStyle: "none",
          zIndex: 9999,
          opacity: visible ? 1 : 0,
          transform: visible ? "translateY(0)" : "translateY(-10px)",
          pointerEvents: visible ? "auto" : "none",
          transition: "opacity 0.2s, transform 0.2s",
          margin: 0,
        }}
      >
        {[
          { name: "edit", label: "Edit", onClick: onEdit },
          { name: "clone", label: "Clone", onClick: onClone },
          {
            name: "delete",
            label: "Delete",
            onClick: () => {
              // Immediately call onDelete prop with current rule
              setMenuOpen(false); // close menu
              if (onDelete) onDelete(rule);
            },
          },
        ].map(({ name, label, onClick }) => (
          <li
            key={name}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              padding: "8px 16px",
              cursor: "pointer",
              color: "#333",
              fontWeight: 500,
              userSelect: "none",
              backgroundColor: "transparent",
              transition: "background-color 0.2s",
            }}
            onClick={(e) => {
              e.stopPropagation();
              onClick?.();
              setMenuOpen(false);
            }}
            onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = "#f5f7f9")}
            onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = "transparent")}
          >
            <FwIcon name={name} size={18} color="#333" />
            <div>{label}</div>
          </li>
        ))}
      </ul>
    );
  }



  
  return (
    <>
      <div
        className="fw-card-1 fw-flex fw-flex-column"
        style={{
          overflow: "visible", 
          border: "0.5px solid #ddd",
          backgroundColor: isFirstInGroup ? "#fff" : "#e5f2fd",
          cursor: "pointer",
        }}
        onClick={handleClick}
      >
        <section
          className="fw-flex-grow fw-px-16 fw-flex fw-flex-row"
          style={{
            justifyContent: "space-between",
            alignItems: "center",
            marginBottom : "40px"
          }}
        >
          <div
            style={{
              paddingLeft: "16px",
              maxWidth: "80%",
              flexBasis: "80%",
              flexShrink: 0,
              whiteSpace: "normal",
            }}
          >
            <h5 className="fw-type-h1 fw-mt-0 fw-mb-8">
              {position}. {name}
            </h5>
            <p
  className="fw-type-xs fw-mt-0 fw-mb-20"
  style={{ marginBottom: "10px", fontSize: "14px" }}  // <-- reduced size
>
  {generateSummary(rule.summary)}
</p>

          </div>

          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: "8px",
              padding: "8px 16px",
              flexBasis: "20%",
              flexShrink: 0,
              marginTop: "-50px",
              justifyContent: "flex-end",
              // ! This is the menu trigger wrapper; make it relative for dropdown
              position: "relative",
            }}
          >
            <FwToggle size="medium" checked={active} />
            <div
              style={{
                position: "relative", // key: this must be relative for the dropdown
              }}
            >
              <div
                className="ember-basic-dropdown-trigger"
                role="button"
                tabIndex="0"
                onClick={(e) => {
                  e.stopPropagation();
                  setMenuOpen(!menuOpen);
                }}
                style={{
                  zIndex: 1,
                  background: "none",
                  border: "none",
                  cursor: "pointer",
                }}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  className="app-icon dropdown-toggle"
                >
                  <path
                    fillRule="evenodd"
                    d="M12 5c-1.38 0-2.5-1.12-2.5-2.5S10.62 0 12 0s2.5 1.12 2.5 2.5S13.38 5 12 5zM12 14c-1.38 0-2.5-1.12-2.5-2.5S10.62 9 12 9s2.5 1.12 2.5 2.5S13.38 14 12 14zM12 24c-1.38 0-2.5-1.12-2.5-2.5S10.62 19 12 19s2.5 1.12 2.5 2.5S13.38 24 12 24z"
                  ></path>
                </svg>
              </div>
              <MenuList
                visible={menuOpen}
                onEdit={() => alert("Edit clicked")}
                onClone={() => alert("Clone clicked")}
                onDelete={handleConfirmDelete}
              />
            </div>
          </div>

        </section>

        <section
          className="fw-type-xs fw-flex fw-flex-row fw-items-center options"
          style={{
            // width: "100%",
            background: "#f5f7f9",
            padding: "10px 16px",
            borderRadius: "5px",
          }}
        >
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-evenly",
              width: "100%",
              fontSize: "14px",
              color: "#666",
              textAlign: "center",
            }}
          >
            <span>
              Last Modified: <strong>{calculateLastModified(updated_at)}</strong>
            </span>
            <span>|</span>
            <span>By: {renderAgentName()}</span>
            <span>|</span>
            <span>Impacted tickets (Last 7 days): {affected_tickets_count}</span>
          </div>
        </section>
      </div>
    </>
  );


  
};

export default AutomationCard;

import React from "react";
import { FwInput, FwLabel } from "@freshworks/crayons/react";

export default function SummaryContent({ ruleObj}) {
    console.log("ruleObj in summary", ruleObj.summary);

    const summaryContent =  {
        "name": "Copy of test rule",
        "position": 2,
        "active": true,
        "outdated": false,
        "last_updated_by": 82175529665,
        "id": 82000718988,
        "summary": {
            "conditions": {
                "condition_set_1": [
                    "If <div class = SummaryKey>Group</div> <div class = SummaryOperator>is</div> <div class = SummaryValue>NONE</div>"
                ]
            },
            "actions": [
                " <div class = SummaryKey>Assign to Group</div> <div class = SummaryValue>Billing</div>"
            ]
        },
        "created_at": "2025-02-05T10:29:26Z",
        "updated_at": "2025-04-15T03:21:18Z",
        "affected_tickets_count": 63,
        "conditions": [
            {
                "name": "condition_set_1",
                "match_type": "any",
                "properties": [
                    {
                        "field_name": "group_id",
                        "resource_type": "ticket",
                        "operator": "in",
                        "value": [
                            ""
                        ]
                    }
                ]
            }
        ],
        "actions": [
            {
                "field_name": "group_id",
                "value": 82000523993
            }
        ],
        "description": null
    };

    const mappingKeyValues = {
        "group_id": ["Group", "Assign to Group"]
    }

    const keysOfChoices = Object.keys(mappingKeyValues);
    const valuesOfChoices = Object.values(mappingKeyValues);
    const summaryKey = keysOfChoices.filter(e=> e === ruleObj.conditions.properties.field_name)
    // const summaryValue = 
    //keys/values of text
    const contentFormation = {
        "conditions": {
            "condition_set_1": [
                "If <div class = SummaryKey>{valuesOfChoices[0]}</div> <div class = SummaryOperator>is</div> <div class = SummaryValue>NONE</div>"
            ]
        },
        "actions": [
            " <div class = SummaryKey>Assign to Group</div> <div class = SummaryValue>Billing</div>"
        ]
    }
    
    const [summary, setSummary] = React.useState(null);
    console.log("summary", summary);


    const SetText = ({ ele }) => {
        const ref = React.useRef(null);
        React.useEffect(() => {
            if (ref.current) {
                const element = ref.current;
                element.innerHTML = ele;
            }
        }, [ref, ele])
        return <div style={{ display: 'flex', gap: '5px', marginLeft: "10px" }} ref={ref}></div>
    }

    React.useEffect(() => {
        if (ruleObj.summary)
            setSummary(ruleObj.summary)
    }, [JSON.stringify(ruleObj.summary)])

    if (!summary) {
        return null;
    }

    return (<>
        <div className='summary_text'>
            <h3>Summary</h3>
            <div className="fw-flex fw-flex-column" style={{ fontWeight: '600', gap: '15px' }}>
                <div className="flex-item-border fw-flex-grow">
                    <FwLabel value="Conditions" style={{ backgroundColor: '#475867' }}></FwLabel>
                    <div style={{ display: "flex", alignItems: 'baseline' }}>
                        <span className='list-icon' ></span>
                        <div style={{ marginLeft: '10px' }}>When <span style={{ fontWeight: '600' }}>Ticket</span> is <span style={{ color: '#007958' }}>created</span></div>
                    </div>
                </div>
                <div className="flex-item-border fw-flex-grow">
                    <div style={{ display: "flex", alignItems: 'baseline' }}>
                        <span className='list-icon'></span>
                        <SetText ele={summary.conditions.condition_set_1}></SetText>
                    </div>
                </div>
                <div className="flex-item-border fw-flex-grow">
                    <FwLabel value="Actions" style={{ backgroundColor: '#475867' }}></FwLabel>
                    <div style={{ display: "flex", alignItems: 'baseline' }}>
                        <span className='list-icon'></span> <SetText ele={summary.actions}></SetText>
                    </div>
                </div>
            </div>
        </div>
    </>)
}


Add this inlne to automationcard