import { useRef, useState } from 'react';
import { Tooltip } from '@mui/material';

import { notify } from '../utils/notify';

interface Props {
  label: string;
  children: React.ReactNode;
}

// Controlled MUI Tooltip mirrors the AI Agent workaround for the legacy
// `removeTooltipOnButtonClick` (common.js) detaching tooltip portals out
// from under React on button clicks: setting `open` ourselves lets us close
// the tooltip before React reconciles the click handler.
//
// The icon is hidden via the legacy `copy-inner-text` class
// (`*:hover > .copy-inner-text { display: inline-block }`) so it only
// appears on row hover, matching the legacy copy-to-clipboard partial.
export const HostInfoRow = ({ label, children }: Props) => {
  const valueRef = useRef<HTMLSpanElement>(null);
  const [tooltipOpen, setTooltipOpen] = useState(false);

  const handleCopy = () => {
    setTooltipOpen(false);
    const text = valueRef.current?.textContent?.trim();
    if (!text) return;
    navigator.clipboard
      .writeText(text)
      .then(() => notify('success', 'Copied to clipboard'))
      .catch(() => notify('error', 'Copy failed'));
  };

  return (
    <div className="row-fluid">
      <span className="span5">{label}:</span>
      <span className="span6" style={{ wordWrap: 'break-word', wordBreak: 'break-all' }}>
        <span ref={valueRef}>{children}</span>{' '}
        <Tooltip
          title="Copy to clipboard"
          placement="top"
          arrow
          open={tooltipOpen}
          onOpen={() => setTooltipOpen(true)}
          onClose={() => setTooltipOpen(false)}
        >
          <i
            className="icon icon-copy copy-inner-text bi bi-clipboard"
            onClick={handleCopy}
            role="button"
            style={{ cursor: 'pointer', marginLeft: 4 }}
          />
        </Tooltip>
      </span>
    </div>
  );
};
