"use client";

import { useState, useTransition, useEffect, useRef, useCallback } from "react";
import { MessageSquare, Send, Reply, Trash2, Loader2, AtSign, X } from "lucide-react";
import {
    addTeamComment,
    getTeamComments,
    deleteTeamComment,
    searchTeamCandidates,
} from "@/app/actions/teamActions";

interface Author {
    id: string;
    name: string;
    avatar_url?: string | null;
}

interface Mention {
    user: { id: string; name: string };
}

interface Comment {
    id: string;
    content: string;
    author: Author;
    mentions: Mention[];
    created_at: string;
    is_edited: boolean;
    replies?: Comment[];
    parent_id?: string | null;
}

interface Props {
    applicationId: string;
    currentUserId: string;
}

export function TeamComments({ applicationId, currentUserId }: Props) {
    const [comments, setComments] = useState<Comment[]>([]);
    const [newComment, setNewComment] = useState("");
    const [replyingTo, setReplyingTo] = useState<string | null>(null);
    const [isPending, startTransition] = useTransition();
    const [isLoading, setIsLoading] = useState(true);
    const [mentionQuery, setMentionQuery] = useState<string | null>(null);
    const [mentionResults, setMentionResults] = useState<any[]>([]);
    const [selectedMentions, setSelectedMentions] = useState<{ id: string; name: string }[]>([]);
    const inputRef = useRef<HTMLTextAreaElement>(null);

    useEffect(() => {
        loadComments();
    }, [applicationId]);

    const loadComments = async () => {
        setIsLoading(true);
        const r = await getTeamComments(applicationId);
        if (r.success && r.comments) setComments(r.comments as unknown as Comment[]);
        setIsLoading(false);
    };

    const handleSubmit = () => {
        if (!newComment.trim()) return;
        startTransition(async () => {
            const mentionIds = selectedMentions.map((m) => m.id);
            const r = await addTeamComment(applicationId, newComment, replyingTo, mentionIds.length ? mentionIds : undefined);
            if (r.success) {
                setNewComment("");
                setReplyingTo(null);
                setSelectedMentions([]);
                await loadComments();
            }
        });
    };

    const handleDelete = (commentId: string) => {
        if (!confirm("Delete this comment?")) return;
        startTransition(async () => {
            await deleteTeamComment(commentId);
            await loadComments();
        });
    };

    const handleMentionSearch = useCallback(async (q: string) => {
        if (q.length < 2) { setMentionResults([]); return; }
        const r = await searchTeamCandidates(q);
        if (r.success && r.users) setMentionResults(r.users);
    }, []);

    const handleInputChange = (value: string) => {
        setNewComment(value);
        // Detect @mention pattern
        const match = value.match(/@(\w*)$/);
        if (match) {
            setMentionQuery(match[1]);
            handleMentionSearch(match[1]);
        } else {
            setMentionQuery(null);
            setMentionResults([]);
        }
    };

    const insertMention = (user: { id: string; name: string }) => {
        const before = newComment.replace(/@\w*$/, "");
        setNewComment(`${before}@${user.name} `);
        setSelectedMentions((prev) => [...prev.filter((m) => m.id !== user.id), user]);
        setMentionQuery(null);
        setMentionResults([]);
        inputRef.current?.focus();
    };

    const getInitials = (name: string) =>
        name.split(" ").map((n) => n[0]).join("").toUpperCase().substring(0, 2);

    const timeAgo = (dateStr: string) => {
        const d = new Date(dateStr);
        const now = new Date();
        const diff = Math.floor((now.getTime() - d.getTime()) / 1000);
        if (diff < 60) return "just now";
        if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
        if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
        return `${Math.floor(diff / 86400)}d ago`;
    };

    const renderComment = (comment: Comment, isReply = false) => (
        <div
            key={comment.id}
            className={`${isReply ? "ml-10 pl-4 border-l-2 border-slate-100" : ""}`}
        >
            <div className="flex gap-3 group py-3">
                <div
                    className="w-8 h-8 rounded-full bg-gradient-to-br from-cyan-400 to-blue-500 text-white text-xs font-bold flex items-center justify-center flex-shrink-0"
                    style={{ fontSize: "10px" }}
                >
                    {comment.author.avatar_url ? (
                        <img src={comment.author.avatar_url} alt="" className="w-full h-full rounded-full object-cover" />
                    ) : getInitials(comment.author.name)}
                </div>
                <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                        <span className="text-sm font-semibold text-slate-800">{comment.author.name}</span>
                        <span className="text-xs text-slate-400">{timeAgo(comment.created_at)}</span>
                        {comment.is_edited && (
                            <span className="text-xs text-slate-300">(edited)</span>
                        )}
                    </div>
                    <p className="text-sm text-slate-600 whitespace-pre-wrap break-words">{
                        renderMentions(comment.content)
                    }</p>
                    {comment.mentions.length > 0 && (
                        <div className="flex flex-wrap gap-1 mt-1">
                            {comment.mentions.map((m: Mention) => (
                                <span key={m.user.id} className="text-xs text-cyan-600 bg-cyan-50 px-1.5 py-0.5 rounded">
                                    @{m.user.name}
                                </span>
                            ))}
                        </div>
                    )}
                    <div className="flex items-center gap-2 mt-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        {!isReply && (
                            <button
                                onClick={() => setReplyingTo(comment.id)}
                                className="flex items-center gap-1 text-xs text-slate-400 hover:text-cyan-600 transition-colors"
                            >
                                <Reply className="w-3 h-3" /> Reply
                            </button>
                        )}
                        {comment.author.id === currentUserId && (
                            <button
                                onClick={() => handleDelete(comment.id)}
                                className="flex items-center gap-1 text-xs text-slate-400 hover:text-red-500 transition-colors"
                            >
                                <Trash2 className="w-3 h-3" /> Delete
                            </button>
                        )}
                    </div>
                </div>
            </div>
            {/* Replies */}
            {comment.replies?.map((reply) => renderComment(reply, true))}
        </div>
    );

    const renderMentions = (text: string) => {
        // Highlight @Name mentions in the text
        return text.replace(/@(\w+\s?\w*)/g, "👤 $1");
    };

    return (
        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
            {/* Header */}
            <div className="flex items-center gap-3 p-5 border-b border-slate-100">
                <div className="p-2 bg-cyan-50 rounded-xl">
                    <MessageSquare className="w-5 h-5 text-cyan-600" />
                </div>
                <div>
                    <h3 className="text-sm font-bold text-slate-800">Team Discussion</h3>
                    <p className="text-xs text-slate-400">{comments.length} comment{comments.length !== 1 ? "s" : ""}</p>
                </div>
            </div>

            {/* Comment List */}
            <div className="max-h-[500px] overflow-y-auto px-5 divide-y divide-slate-50">
                {isLoading ? (
                    <div className="flex items-center justify-center py-8">
                        <Loader2 className="w-5 h-5 animate-spin text-slate-400" />
                    </div>
                ) : comments.length === 0 ? (
                    <div className="text-center py-8">
                        <MessageSquare className="w-8 h-8 text-slate-200 mx-auto mb-2" />
                        <p className="text-sm text-slate-400">No comments yet</p>
                        <p className="text-xs text-slate-300">Start a team discussion about this candidate</p>
                    </div>
                ) : (
                    comments.map((c) => renderComment(c))
                )}
            </div>

            {/* Input Area */}
            <div className="p-4 border-t border-slate-100 bg-slate-50">
                {replyingTo && (
                    <div className="flex items-center gap-2 mb-2 text-xs text-cyan-600">
                        <Reply className="w-3 h-3" />
                        <span>Replying to comment</span>
                        <button onClick={() => setReplyingTo(null)} className="text-slate-400 hover:text-slate-600">
                            <X className="w-3 h-3" />
                        </button>
                    </div>
                )}

                {/* Mention Autocomplete */}
                {mentionQuery !== null && mentionResults.length > 0 && (
                    <div className="mb-2 bg-white border border-slate-200 rounded-xl shadow-lg max-h-32 overflow-y-auto">
                        {mentionResults.map((u: any) => (
                            <button
                                key={u.id}
                                onClick={() => insertMention(u)}
                                className="flex items-center gap-2 w-full px-3 py-2 text-left hover:bg-slate-50 transition-colors"
                            >
                                <AtSign className="w-3 h-3 text-cyan-500" />
                                <span className="text-sm font-medium text-slate-700">{u.name}</span>
                                <span className="text-xs text-slate-400">{u.email}</span>
                            </button>
                        ))}
                    </div>
                )}

                <div className="flex gap-2">
                    <textarea
                        ref={inputRef}
                        value={newComment}
                        onChange={(e) => handleInputChange(e.target.value)}
                        onKeyDown={(e) => {
                            if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSubmit(); }
                        }}
                        placeholder="Add a comment... (type @ to mention)"
                        rows={2}
                        className="flex-1 px-3 py-2 border border-slate-200 rounded-xl text-sm resize-none focus:ring-2 focus:ring-cyan-200 focus:border-cyan-400 outline-none"
                    />
                    <button
                        onClick={handleSubmit}
                        disabled={isPending || !newComment.trim()}
                        className="self-end px-4 py-2 bg-cyan-600 text-white text-sm font-bold rounded-xl hover:bg-cyan-700 transition-colors disabled:opacity-50 flex items-center gap-1.5"
                    >
                        {isPending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Send className="w-3.5 h-3.5" />}
                    </button>
                </div>

                {selectedMentions.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                        {selectedMentions.map((m) => (
                            <span key={m.id} className="flex items-center gap-1 text-xs bg-cyan-50 text-cyan-700 px-2 py-0.5 rounded-full">
                                @{m.name}
                                <button onClick={() => setSelectedMentions((prev) => prev.filter((p) => p.id !== m.id))}>
                                    <X className="w-3 h-3" />
                                </button>
                            </span>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
