import React, { useMemo } from 'react';
import { getTagColorStyle } from '../../utils/colors';
import type { Document, DocumentTag } from '../../types/documents';
import type { Identifier } from '../../types/identifiers';
import type { TagDragHandlers } from '../interactions/useTagInteractions';

interface DocumentTagsProps {
    tags: DocumentTag[];
    tagLookupById?: Map<Identifier, DocumentTag> | null;
    onTagClick?: (tagId: Identifier) => void;
    doc: Document;
    tagDragHandlers?: TagDragHandlers;
}

const DocumentTags: React.FC<DocumentTagsProps> = ({
    tags,
    tagLookupById,
    onTagClick,
    doc,
    tagDragHandlers,
}) => {
    const sortedTags = useMemo(() => {
        return [...tags].sort((a, b) => {
            const labelA = (a.label || '').toLowerCase();
            const labelB = (b.label || '').toLowerCase();
            return labelA.localeCompare(labelB);
        });
    }, [tags]);

    if (tags.length === 0) {
        return null;
    }

    return (
        <>
            {sortedTags.map((tag, index) => {
                const colorSource = tag?.color || tagLookupById?.get(tag.id)?.color;
                const style = getTagColorStyle(colorSource);
                const tagId = tag?.id ?? null;
                const clickable = tagId != null && typeof onTagClick === 'function';
                const key = tagId ?? `${doc.id}-tag-${index}`;

                return (
                    <span
                        key={key}
                        className="badge tag-chip"
                        style={style || undefined}
                        title={tag.label}
                        role={clickable ? 'button' : undefined}
                        onClick={clickable ? (event) => {
                            event.stopPropagation();
                            if (tagId == null) return;
                            onTagClick?.(tagId);
                        } : undefined}
                        draggable={!!tagId}
                        onDragStart={(event) => tagId && tagDragHandlers?.onTagDragStart(event, doc, tag)}
                        onDragEnd={tagDragHandlers?.onTagDragEnd}
                        onKeyDown={clickable ? (event) => {
                            if (event.key === 'Enter' || event.key === ' ') {
                                event.preventDefault();
                                event.stopPropagation();
                                if (tagId == null) return;
                                onTagClick?.(tagId);
                            }
                        } : undefined}
                    >
                        {tag.label}
                    </span>
                );
            })}
        </>
    );
};

export default DocumentTags;
