import Style from "@/styles/modules/chat.module.css";
import {
  getAttachmentFileKey,
  isImageAttachment,
  isVideoAttachment,
} from "@/utils/chatHelpers";

interface MediaPreviewComposerProps {
  files: File[];
  previewMap: Record<string, string>;
  caption: string;
  onCaptionChange: (value: string) => void;
  onRemoveFile: (index: number) => void;
  onClose: () => void;
  onSend: () => void;
  sending: boolean;
  peerName: string;
}

const MediaPreviewComposer = ({
  files,
  previewMap,
  caption,
  onCaptionChange,
  onRemoveFile,
  onClose,
  onSend,
  sending,
  peerName,
}: MediaPreviewComposerProps) => {
  return (
    <div className={Style.mediaPreviewOverlay}>
      <div className={Style.mediaPreviewHeader}>
        <button type="button" className={Style.mediaPreviewClose} onClick={onClose}>
          ✕
        </button>
        <span>Send to {peerName}</span>
        <button
          type="button"
          className={Style.mediaPreviewSend}
          onClick={onSend}
          disabled={sending}
        >
          {sending ? "Sending…" : "Send"}
        </button>
      </div>

      <div className={Style.mediaPreviewGrid}>
        {files.map((file, index) => {
          const key = getAttachmentFileKey(file);
          const preview = previewMap[key];
          const isImage = isImageAttachment(file);
          const isVideo = isVideoAttachment(file);

          return (
            <div key={key} className={Style.mediaPreviewItem}>
              <button
                type="button"
                className={Style.mediaPreviewRemove}
                onClick={() => onRemoveFile(index)}
                aria-label="Remove"
              >
                ✕
              </button>
              {isImage && preview ? (
                <img src={preview} alt={file.name} className={Style.mediaPreviewImage} />
              ) : isVideo && preview ? (
                <video src={preview} className={Style.mediaPreviewImage} controls />
              ) : (
                <div className={Style.mediaPreviewFile}>
                  📎 {file.name}
                </div>
              )}
            </div>
          );
        })}
      </div>

      <div className={Style.mediaPreviewCaption}>
        <input
          type="text"
          placeholder="Add a caption…"
          value={caption}
          onChange={(e) => onCaptionChange(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.shiftKey) {
              e.preventDefault();
              onSend();
            }
          }}
        />
      </div>
    </div>
  );
};

export default MediaPreviewComposer;
