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;


in this, when user click delete icon, log that whole rule