import React, { useState } from 'react';
import { SilkeButton } from '../silke-button';
import { SilkeIcon } from '../silke-icon/silke-icon';
import { SilkePopover } from '../silke-popover/silke-popover';
import { getFileIcon, truncateFilename } from './file-utils';
import { imageValueToDataUrl } from './image-utils';
import styles from './silke-command-text-field.module.scss';
import { isImage, SilkeFileValue, SilkeImageValue } from './utils';

interface AttachmentChipProps {
  attachment: SilkeImageValue | SilkeFileValue;
  disabled?: boolean;
  onRemove?: () => void;
}

export function AttachmentChip({ attachment, disabled, onRemove }: AttachmentChipProps) {
  const name = isImage(attachment) ? attachment.name || 'Image' : attachment.name;
  const [showPreview, setShowPreview] = useState(false);

  return (
    <div
      className={`${styles.attachmentChip}${isImage(attachment) ? ` ${styles.imageChip}` : ''}`}
      title={name}
    >
      {isImage(attachment) ? (
        <>
          <div
            className={styles.chipThumbnail}
            onClick={() => setShowPreview((v) => !v)}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                setShowPreview((v) => !v);
              }
            }}
          >
            <img src={imageValueToDataUrl(attachment)} alt={name} />
          </div>
          <SilkePopover
            hide={!showPreview}
            shadow="level3"
            contextId="attachment-preview"
            onRequestClose={() => setShowPreview(false)}
          >
            <div className={styles.imagePreview}>
              <img src={imageValueToDataUrl(attachment)} alt={name} />
            </div>
          </SilkePopover>
        </>
      ) : (
        <SilkeIcon icon={getFileIcon(attachment.mimeType)} />
      )}
      <span className={styles.chipName}>{truncateFilename(name)}</span>
      {!disabled && onRemove && (
        <SilkeButton
          kind="ghost"
          size="s"
          icon="close"
          className={styles.chipRemove}
          onClick={(e) => {
            e.stopPropagation();
            onRemove();
          }}
          aria-label={`Remove ${name}`}
        />
      )}
    </div>
  );
}
