
// imports
import yaml from 'yaml';
import React, { useEffect, useState } from 'react';

// icons
import Tooltip from '../../../Tooltip';
import Loading from '../../../Loading';
import ApiSignal from '../../../../signals/Api';
import ButtonIcon from '../../../Button/Icon';
import { useSignal } from '../../../../signal';
import { ComponentsSignal } from '../../../../signals/Nodes';
import { IconTrash, IconRefresh } from '@chirper/react/src/icons';

/**
 * component studio messages
 * 
 * @param props 
 * @returns 
 */
const ComponentWorkflowChatItem = (props = {}) => {
  // signals
  const [api] = useSignal(ApiSignal);
  const [components] = useSignal(ComponentsSignal);
  
  // retrying
  const [retrying, setRetrying] = useState(false);

  // parse nodes
  const [nodes, setNodes] = useState([]);

  // use effect
  useEffect(() => {
    setNodes(yaml.parse(props.item?.value || props.workflow?.commit?.value || '[]'));
  }, [props.item?.value, props.workflow?.commit?.value]);

  /**
   * on retry
   */
  const onRetry = () => {
    // retrying
    setRetrying(true);

    // retry
    props.onRetry(props.item).then(() => {
      // retrying
      setRetrying(false);
    }).catch(() => {
      // retrying
      setRetrying(false);
    });
  };

  // return messages
  return (
    <div className="py-3">
      {!props.isFirst && (
        <div className="mb-3">
          <hr />
        </div>
      )}
      <div className="flex relative flex-col space-y-3 w-full">
        {(props.item.path || []).map((key, i) => {
          // is last
          const isLast = ((props.item.state === 'failed') && (props.item.node === key)) || (i === props.item.path.length - 1);
          
          // node
          const node = nodes.find((n) => n.id === key);

          // check node
          if (!node?.type) return;
          if (node?.spec?.hidden) return;

          // component
          const Component = components[node.type];

          // check component
          if (!Component) return null;

          // return jsx
          return (
            <Component
              id={key}
              key={key}
              data={node}
              state={props.item.state}
              input={props.item.input}
              isLast={isLast}
              output={props.item.output}
              isFirst={i === 0}
              variant="message"
              current={props.item.type}
              message={props.item.message}
              running={props.item.running}

              shouldLog={props.item.state === 'executing'}
            />
          );
        })}
        
        <div className="flex flex-row space-x-3 w-full">
          <div className="w-12 h-12" />
          <div className="flex flex-row flex-1 justify-end items-center space-x-1 min-w-0">
            <Tooltip title={api.translate('workflow:tooltip.message.retry', 'Retry')}>
              <ButtonIcon
                color="primary"
                onClick={onRetry}
              >
                {retrying ? (
                  <Loading className="w-5 h-5 fill-primary-500" />
                ) : (
                  <IconRefresh className="w-5 h-5" />
                )}
              </ButtonIcon>
            </Tooltip>
            <Tooltip title={api.translate('workflow:tooltip.message.remove', 'Remove Message')}>
              <ButtonIcon
                color="error"
                onClick={(e) => props.onDelete(props.frame)}
              >
                {props.removing ? (
                  <Loading className="w-5 h-5 fill-red-500" />
                ) : (
                  <IconTrash className="w-5 h-5" />
                )}
              </ButtonIcon>
            </Tooltip>
          </div>
        </div>
      </div>
    </div>
  );
};

/**
 * export component
 */
export default ComponentWorkflowChatItem;