import { Avatar } from '@/components/base/avatar/avatar';
import { Badge } from '@/components/base/badges/badges';
import type { PatientMessage, MessageStatus } from '@/types/entities';

interface MessageListProps {
    messages: PatientMessage[];
}

const statusConfig: Record<
    MessageStatus,
    { label: string; color: 'blue' | 'success' | 'gray' | 'error' }
> = {
    READ: { label: 'Read', color: 'blue' },
    DELIVERED: { label: 'Delivered', color: 'success' },
    SENT: { label: 'Sent', color: 'gray' },
    FAILED: { label: 'Failed', color: 'error' },
};

const getInitials = (name: string | null | undefined): string => {
    if (!name) return '?';
    const parts = name.trim().split(' ');
    if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
};

const formatTime = (sentAt: string | null): string => {
    if (!sentAt) return '';
    const date = new Date(sentAt);
    return date.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', hour12: true });
};

export const MessageList = ({ messages }: MessageListProps) => {
    return (
        <div className="bg-primary rounded-2xl border border-secondary overflow-hidden">
            {/* Header */}
            <div className="flex items-center justify-between px-5 py-4 border-b border-secondary">
                <p className="text-md font-bold text-primary">Recent Messages</p>
                <button type="button" className="text-sm text-brand-secondary hover:text-brand-secondary_hover transition duration-100 ease-linear cursor-pointer">
                    View All →
                </button>
            </div>

            {/* Message rows */}
            <div className="divide-y divide-secondary">
                {messages.slice(0, 5).map((message) => {
                    const recipientName = message.recipientName ?? message.senderName ?? 'Unknown';
                    const status = message.status ?? 'SENT';
                    const statusInfo = statusConfig[status];

                    return (
                        <div key={message.id} className="flex items-center gap-3 px-5 py-3.5 hover:bg-secondary transition duration-100 ease-linear">
                            {/* Avatar */}
                            <Avatar
                                initials={getInitials(recipientName)}
                                size="sm"
                            />

                            {/* Name + preview */}
                            <div className="flex-1 min-w-0">
                                <p className="text-sm font-semibold text-primary">{recipientName}</p>
                                <p className="text-xs text-tertiary overflow-hidden text-ellipsis whitespace-nowrap">
                                    {message.subject ?? message.body ?? '—'}
                                </p>
                            </div>

                            {/* Time + status */}
                            <div className="flex flex-col items-end gap-1 flex-shrink-0">
                                <span className="text-xs text-quaternary">{formatTime(message.sentAt)}</span>
                                <Badge type="pill-color" color={statusInfo.color} size="sm">
                                    {statusInfo.label}
                                </Badge>
                            </div>
                        </div>
                    );
                })}

                {messages.length === 0 && (
                    <p className="py-8 text-center text-sm text-tertiary">No messages yet.</p>
                )}
            </div>
        </div>
    );
};
