import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { windowService } from '../../services/window.service';
import { AppIcon } from '../app-icon';

interface CopyButtonProps {
  text: string;
  buttonRef?: React.Ref<HTMLButtonElement>;
}

export function CopyButton({ text, buttonRef }: CopyButtonProps): JSX.Element {
  const [isCopied, setIsCopied] = useState<boolean>(false);

  const handleCopyClick = async (): Promise<void> => {
    try {
      await windowService.copyToClipboard(text);
      setIsCopied(true);
      setTimeout(() => {
        setIsCopied(false);
      }, 2000);
    } catch (err) {
      alert(__('Failed to copy. Please copy manually.', 'timetailor-salon-booking'));
    }
  };

  return (
    <button
      ref={buttonRef}
      className="w-28 h-8 flex justify-center items-center gap-1 bg-white text-primary border border-primary rounded-md"
      onClick={handleCopyClick}
      >
        <AppIcon
          name={isCopied ? 'check' : 'copy'}
          className={`w-4 h-4 text-primary ${isCopied ? '' : ''}`}
          aria-hidden="true"
        />
      <span className={`${isCopied ? 'hidden' : ''}`}>{__('Copy', 'timetailor-salon-booking')}</span>
      <span className={`${isCopied ? '' : 'hidden'}`}>{__('Copied', 'timetailor-salon-booking')}</span>
    </button>
  );
}
