import { FiCopy, FiRefreshCw } from 'react-icons/fi';
import { FilePreview } from './file-preview';
import { StreamingMessage } from './streaming-message';
import { ChatMessage } from '../../types/chat';

export interface ChatMessageProps {
	message: ChatMessage;
	isStreaming?: boolean;
	onRetry?: () => void;
	onCopy?: () => void;
	onDelete?: () => void;
	showActions?: boolean;
}

export function ChatMessageComponent({
	message,
	isStreaming = false,
	onRetry,
	onCopy,
	showActions = true,
}: ChatMessageProps) {
	const isUser = message.role === 'user';
	const files = message.metadata?.files || [];

	const handleCopy = () => {
		if (message.content) {
			navigator.clipboard.writeText(message.content);
			onCopy?.();
		}
	};

	const formatTime = (dateString: string) => {
		const date = new Date(dateString);
		return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
	};

	return (
		<div className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-4`}>
			<div className={`max-w-[80%] ${isUser ? 'items-end' : 'items-start'} flex flex-col gap-1.5`}>
				<div
					className={`
						rounded-2xl px-4 py-3 shadow-sm
						${isUser ? 'bg-sidebar-bg text-sidebar-text' : 'bg-white border border-gray-200'}
					`}
				>
					{isStreaming ? (
						<StreamingMessage content={message.content} isStreaming={isStreaming} />
					) : (
						<p
							className={`text-sm whitespace-pre-wrap leading-relaxed ${
								isUser ? 'text-sidebar-text' : 'text-gray-800'
							}`}
						>
							{message.content}
						</p>
					)}

					{files.length > 0 && (
						<div className='mt-3 grid grid-cols-2 sm:grid-cols-3 gap-2'>
							{files.map((file, index) => (
								<FilePreview key={index} file={file} compact={true} />
							))}
						</div>
					)}

					{message.audioUrl && (
						<div className='mt-3'>
							<audio controls className='w-full max-w-xs'>
								<source src={message.audioUrl} />
							</audio>
						</div>
					)}
				</div>

				<div
					className={`flex items-center gap-2 text-xs ${isUser ? 'text-sidebar-text/70' : 'text-text-muted'}`}
				>
					<span>{formatTime(message.createdAt)}</span>
					{showActions && !isUser && (
						<div className='flex items-center gap-1'>
							{onCopy && (
								<button
									onClick={handleCopy}
									className='p-1 hover:bg-bg-hover rounded transition-colors'
									aria-label='Copy message'
								>
									<FiCopy
										className={`w-3 h-3 ${isUser ? 'text-sidebar-text/70' : 'text-text-muted'}`}
									/>
								</button>
							)}
							{onRetry && (
								<button
									onClick={onRetry}
									className='p-1 hover:bg-bg-hover rounded transition-colors'
									aria-label='Retry message'
								>
									<FiRefreshCw
										className={`w-3 h-3 ${isUser ? 'text-sidebar-text/70' : 'text-text-muted'}`}
									/>
								</button>
							)}
						</div>
					)}
				</div>
			</div>
		</div>
	);
}
