import React, { useCallback, useImperativeHandle, useRef } from 'react';
import { AttachmentChip } from './attachment-chip';
import { fileToAttachmentValue } from './file-utils';
import styles from './silke-command-text-field.module.scss';
import { SilkeFileValue, SilkeImageValue } from './utils';

interface AttachmentListProps {
  acceptedTypes: string[];
  attachments: (SilkeImageValue | SilkeFileValue)[];
  disabled?: boolean;
  onAdd: (attachments: (SilkeImageValue | SilkeFileValue)[]) => void;
  onRemove: (index: number) => void;
}

export interface AttachmentListHandle {
  /** Open the file picker dialog */
  openFilePicker: () => void;
}

export const AttachmentList = React.forwardRef<AttachmentListHandle, AttachmentListProps>(
  ({ acceptedTypes, attachments, disabled, onAdd, onRemove }, ref) => {
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleFileSelect = useCallback(
      (e: React.ChangeEvent<HTMLInputElement>) => {
        const { files } = e.target;
        if (!files || files.length === 0) return;

        Promise.all(
          Array.from(files).map((file) => fileToAttachmentValue(file, acceptedTypes)),
        ).then((results) => {
          const valid = results.filter((v): v is SilkeImageValue | SilkeFileValue => v !== null);
          if (valid.length > 0) onAdd(valid);
        });
        // Reset so the same file can be selected again
        e.target.value = '';
      },
      [acceptedTypes, onAdd],
    );

    useImperativeHandle(ref, () => ({
      openFilePicker: () => fileInputRef.current?.click(),
    }));

    return (
      <>
        {attachments.length > 0 && (
          <div className={styles.attachmentList}>
            {attachments.map((attachment, idx) => (
              <AttachmentChip
                key={idx}
                attachment={attachment}
                disabled={disabled}
                onRemove={() => onRemove(idx)}
              />
            ))}
          </div>
        )}
        <input
          ref={fileInputRef}
          type="file"
          className={styles.fileInput}
          accept={acceptedTypes.join(',')}
          multiple
          onChange={handleFileSelect}
        />
      </>
    );
  },
);

AttachmentList.displayName = 'AttachmentList';
