import { types as t } from '@babel/core';

export function hasAttribute(node: t.JSXOpeningElement, name: string) {
  return node.attributes.some(
    (attr) => t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name, { name })
  );
}

export function getAttribute(node: t.JSXOpeningElement, name: string) {
  return node.attributes.find(
    (attr): attr is t.JSXAttribute =>
      t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name, { name })
  );
}

export function removeAttribute(node: t.JSXOpeningElement, name: string) {
  node.attributes = node.attributes.filter(
    (attr) =>
      !(t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name, { name }))
  );
  return node;
}

export function setAttribute(
  node: t.JSXOpeningElement,
  name: string,
  value: any
) {
  // Remove existing attribute if it exists
  const filteredAttributes = node.attributes.filter(
    (attr) =>
      !(t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name, { name }))
  );

  // Create value node based on the type of value
  let valueNode: t.StringLiteral | t.JSXExpressionContainer | null;
  if (typeof value === 'string') {
    valueNode = t.stringLiteral(value);
    // } else if (typeof value === 'number') {
    //   valueNode = t.numericLiteral(value);
  } else if (typeof value === 'boolean') {
    valueNode = t.jsxExpressionContainer(t.booleanLiteral(value));
  } else if (value === null) {
    // No value for boolean attributes
    valueNode = null;
  } else {
    // For objects or arrays, wrap in expression
    valueNode = t.jsxExpressionContainer(t.valueToNode(value));
  }

  // Add the attribute
  filteredAttributes.push(t.jsxAttribute(t.jsxIdentifier(name), valueNode));

  // Replace attributes
  node.attributes = filteredAttributes;

  return node;
}
