import { useEffect, useRef, useState } from "react";
import { MessageSquare, Info, Check, CheckCheck, FileText, Download, ArrowDown, Clock, AlertCircle, RefreshCw, Trash2, FileImage, FileSpreadsheet, FileArchive, File as FileIconGeneric, Loader2 } from "lucide-react";

interface TypingUser {
    userId: string;
    userName: string;
    conversationId: string;
    expiresAt: number;
}

export interface ThreadMessage {
    id: string;
    content: string;
    messageType: string;
    attachmentUrl: string | null;
    senderId: string;
    senderName: string;
    senderAvatar: string | null;
    senderRole: string;
    isRead: boolean;
    createdAt: string;
    status?: "sending" | "sent" | "delivered" | "seen" | "failed";
    attachments?: {
        id: string;
        filename: string;
        fileUrl: string;
        fileSize: number;
        mimeType: string;
        thumbnailUrl: string | null;
    }[];
}

interface MessageThreadProps {
    messages: ThreadMessage[];
    currentUserId: string;
    otherUserName: string;
    jobTitle: string;
    typingUsers?: TypingUser[];
    onRetry?: (messageId: string) => void;
    onDeleteFailed?: (messageId: string) => void;
}

function getDateLabel(dateStr: string): string {
    const date = new Date(dateStr);
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    if (date.toDateString() === today.toDateString()) return "Today";
    if (date.toDateString() === yesterday.toDateString()) return "Yesterday";
    return date.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" });
}

export function MessageThread({ messages, currentUserId, otherUserName, jobTitle, typingUsers = [], onRetry, onDeleteFailed }: MessageThreadProps) {
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const scrollContainerRef = useRef<HTMLDivElement>(null);
    const [showScrollButton, setShowScrollButton] = useState(false);

    // Auto-scroll to bottom on load and new messages
    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    }, [messages.length]);

    const handleScroll = () => {
        if (!scrollContainerRef.current) return;
        const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.current;
        // Show button if we are scrolled up more than 150px from the bottom
        const isScrolledUp = scrollHeight - scrollTop - clientHeight > 150;
        setShowScrollButton(isScrolledUp);
    };

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    // Group messages by date for separators
    const messagesByDate: { label: string; messages: ThreadMessage[] }[] = [];
    let currentLabel = "";
    messages.forEach((msg) => {
        const label = getDateLabel(msg.createdAt);
        if (label !== currentLabel) {
            currentLabel = label;
            messagesByDate.push({ label, messages: [] });
        }
        messagesByDate[messagesByDate.length - 1].messages.push(msg);
    });

    return (
        <div className="flex-1 overflow-hidden relative flex flex-col bg-slate-50/30">
            <div
                ref={scrollContainerRef}
                onScroll={handleScroll}
                className="flex-1 overflow-y-auto px-5 py-4 space-y-1"
            >
                {messages.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-full text-center">
                        <div className="p-4 rounded-2xl bg-slate-100 mb-4">
                            <MessageSquare className="w-8 h-8 text-slate-300" />
                        </div>
                        <h3 className="font-bold text-slate-700">Start the conversation</h3>
                        <p className="text-sm text-slate-500 mt-1 max-w-xs">
                            Send your first message to {otherUserName} about the {jobTitle} position.
                        </p>
                    </div>
                ) : (
                    messagesByDate.map((group) => (
                        <div key={group.label}>
                            {/* Date separator */}
                            <div className="flex items-center gap-3 my-4">
                                <div className="flex-1 h-px bg-slate-200" />
                                <span className="text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
                                    {group.label}
                                </span>
                                <div className="flex-1 h-px bg-slate-200" />
                            </div>

                            {group.messages.map((msg) => {
                                const isMine = msg.senderId === currentUserId;
                                const isSystem = msg.messageType === "system";

                                if (isSystem) {
                                    return (
                                        <div key={msg.id} className="flex justify-center my-3">
                                            <div className="px-4 py-2 bg-slate-100 rounded-lg text-xs text-slate-500 italic max-w-md text-center">
                                                <Info className="w-3 h-3 inline mr-1 -mt-0.5" />
                                                {msg.content}
                                            </div>
                                        </div>
                                    );
                                }

                                return (
                                    <div
                                        key={msg.id}
                                        className={`flex gap-2.5 mb-3 animate-message-in ${isMine ? "justify-end" : "justify-start"}`}
                                    >
                                        {/* Sender avatar (received only) */}
                                        {!isMine && (
                                            <div className="w-7 h-7 rounded-full bg-slate-300 flex items-center justify-center text-white text-[10px] font-bold shrink-0 mt-1 select-none">
                                                {msg.senderAvatar ? (
                                                    <img src={msg.senderAvatar} alt="" className="w-7 h-7 rounded-full object-cover" />
                                                ) : (
                                                    (msg.senderName || "?")[0]?.toUpperCase()
                                                )}
                                            </div>
                                        )}

                                        <div className={`max-w-[70%] ${isMine ? "items-end" : "items-start"}`}>
                                            <div
                                                className={`px-3.5 py-2.5 rounded-2xl text-sm leading-relaxed whitespace-pre-wrap ${isMine
                                                    ? "bg-primary text-white rounded-br-sm"
                                                    : "bg-white border border-slate-100 text-slate-700 rounded-bl-sm shadow-sm"
                                                    }`}
                                            >
                                                {msg.content}
                                                {msg.attachments && msg.attachments.length > 0 && (
                                                    <div className="mt-2 space-y-2">
                                                        {msg.attachments.map(att => {
                                                            const isImage = att.mimeType.startsWith('image/') || ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(att.filename.split('.').pop()?.toLowerCase() || '');

                                                            const getFileIcon = (className = "w-5 h-5") => {
                                                                const ext = att.filename.split('.').pop()?.toLowerCase() || '';
                                                                if (isImage) return <FileImage className={className} />;
                                                                if (['pdf', 'doc', 'docx', 'txt'].includes(ext)) return <FileText className={className} />;
                                                                if (['csv', 'xls', 'xlsx'].includes(ext)) return <FileSpreadsheet className={className} />;
                                                                if (['zip', 'rar', 'tar', 'gz'].includes(ext)) return <FileArchive className={className} />;
                                                                return <FileIconGeneric className={className} />;
                                                            };

                                                            return (
                                                                <div key={att.id} className={`flex items-center gap-2 p-2 rounded-lg border relative ${isMine ? 'bg-primary/20 border-white/20' : 'bg-slate-50 border-slate-200'}`}>
                                                                    {isImage && att.thumbnailUrl ? (
                                                                        <a href={att.fileUrl} target="_blank" rel="noopener noreferrer" className="block w-10 h-10 shrink-0 relative rounded overflow-hidden">
                                                                            <img src={att.thumbnailUrl} alt={att.filename} className="w-full h-full object-cover bg-slate-100" />
                                                                            {msg.status === "sending" && (
                                                                                <div className="absolute inset-0 bg-white/60 backdrop-blur-[1px] flex items-center justify-center">
                                                                                    <Loader2 className="w-4 h-4 animate-spin text-primary" />
                                                                                </div>
                                                                            )}
                                                                        </a>
                                                                    ) : (
                                                                        <div className={`w-10 h-10 shrink-0 rounded flex items-center justify-center relative overflow-hidden ${isMine ? 'bg-primary/30' : 'bg-slate-200'}`}>
                                                                            {getFileIcon()}
                                                                            {msg.status === "sending" && (
                                                                                <div className="absolute inset-0 bg-white/60 backdrop-blur-[1px] flex items-center justify-center">
                                                                                    <Loader2 className="w-4 h-4 animate-spin text-primary" />
                                                                                </div>
                                                                            )}
                                                                        </div>
                                                                    )}
                                                                    <div className="flex-1 min-w-0">
                                                                        <p className="text-xs font-semibold truncate" title={att.filename}>{att.filename}</p>
                                                                        {msg.status === "sending" ? (
                                                                            <p className="text-[10px] text-primary font-medium animate-pulse">Uploading...</p>
                                                                        ) : (
                                                                            <p className="text-[10px] opacity-80">{(att.fileSize / 1024 / 1024).toFixed(2)} MB</p>
                                                                        )}
                                                                    </div>
                                                                    {msg.status !== "sending" && (
                                                                        <a href={att.fileUrl} download={att.filename} target="_blank" rel="noopener noreferrer" className={`p-1.5 rounded-full ${isMine ? 'hover:bg-primary/30' : 'hover:bg-slate-200'}`}>
                                                                            <Download className="w-3.5 h-3.5" />
                                                                        </a>
                                                                    )}
                                                                </div>
                                                            )
                                                        })}
                                                    </div>
                                                )}
                                            </div>

                                            {/* Timestamp + Status Indicator */}
                                            <div className={`flex items-center gap-1 mt-1 ${isMine ? "justify-end" : "justify-start"}`}>
                                                {msg.status === "failed" ? (
                                                    <div className="flex items-center gap-2">
                                                        <AlertCircle className="w-3.5 h-3.5 text-red-400" />
                                                        <span className="text-[10px] text-red-400 font-medium">Failed to send</span>
                                                        {onRetry && (
                                                            <button
                                                                onClick={() => onRetry(msg.id)}
                                                                className="flex items-center gap-0.5 text-[10px] text-primary hover:text-primary/80 font-medium transition-colors"
                                                            >
                                                                <RefreshCw className="w-3 h-3" />
                                                                Retry
                                                            </button>
                                                        )}
                                                        {onDeleteFailed && (
                                                            <button
                                                                onClick={() => onDeleteFailed(msg.id)}
                                                                className="flex items-center gap-0.5 text-[10px] text-slate-400 hover:text-red-500 font-medium transition-colors"
                                                            >
                                                                <Trash2 className="w-3 h-3" />
                                                            </button>
                                                        )}
                                                    </div>
                                                ) : (
                                                    <>
                                                        <span className="text-[10px] text-slate-400 select-none">
                                                            {new Date(msg.createdAt).toLocaleTimeString("en-US", {
                                                                hour: "numeric",
                                                                minute: "2-digit",
                                                            })}
                                                        </span>
                                                        {isMine && (
                                                            msg.status === "sending" ? (
                                                                <Clock className="w-3.5 h-3.5 text-slate-300 animate-pulse" />
                                                            ) : msg.status === "seen" || msg.isRead ? (
                                                                <CheckCheck className="w-3.5 h-3.5 text-blue-400" />
                                                            ) : msg.status === "sent" ? (
                                                                <Check className="w-3.5 h-3.5 text-slate-400" />
                                                            ) : (
                                                                <CheckCheck className="w-3.5 h-3.5 text-slate-300" />
                                                            )
                                                        )}
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    ))
                )}
                {/* Typing indicator */}
                {typingUsers.length > 0 && (
                    <div className="flex items-center gap-2.5 mb-3 px-1 animate-fadeIn">
                        <div className="w-7 h-7 rounded-full bg-slate-300 flex items-center justify-center text-white text-[10px] font-bold shrink-0">
                            {typingUsers[0].userName[0]?.toUpperCase()}
                        </div>
                        <div className="bg-white border border-slate-100 rounded-2xl rounded-bl-sm px-4 py-3 shadow-sm">
                            <div className="flex items-center gap-1">
                                <span className="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style={{ animationDelay: "0ms" }} />
                                <span className="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style={{ animationDelay: "150ms" }} />
                                <span className="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style={{ animationDelay: "300ms" }} />
                            </div>
                        </div>
                        <span className="text-[10px] text-slate-400">
                            {typingUsers.map(t => t.userName.split(" ")[0]).join(", ")} {typingUsers.length === 1 ? "is" : "are"} typing...
                        </span>
                    </div>
                )}
                <div ref={messagesEndRef} />
            </div>

            {/* Floating Jump to Latest Button */}
            {showScrollButton && (
                <div className="absolute bottom-4 right-1/2 translate-x-1/2 md:translate-x-0 md:right-8 z-10">
                    <button
                        onClick={scrollToBottom}
                        className="flex items-center justify-center w-10 h-10 bg-white border border-slate-200 shadow-md rounded-full text-primary hover:bg-slate-50 transition-all hover:shadow-lg animate-fadeIn"
                        title="Jump to latest messages"
                    >
                        <ArrowDown className="w-5 h-5" />
                    </button>
                </div>
            )}
        </div>
    );
}
