/**
 * Team Workspace — Premium team collaboration workspace.
 * Features: real user names, comments, inline edit, review flow, reactions, search.
 */

import { useEffect, useState, useRef, useMemo, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
    ArrowLeftIcon,
    BookmarkIcon,
    CheckCircle2Icon,
    CopyIcon,
    TrashIcon,
    UndoIcon,
    UsersIcon,
    MessageCircleIcon,
    SendIcon,
    PencilIcon,
    XIcon,
    SearchIcon,
    SendHorizonal,
    ShieldCheckIcon,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import {
    getTeam,
    listDrafts,
    listMain,
    createDraft,
    mergeMemo,
    unmergeMemo,
    deleteTeamMemo,
    pinMemo,
    updateTeamMemo,
    requestReview,
    submitReview,
    listComments,
    createComment,
    deleteComment,
    toggleReaction,
} from "@/service/teamService";
import type { Team, TeamMemo, TeamComment } from "@/service/teamService";
import "./TeamWorkspace.css";

type Tab = "draft" | "main";

const STATUS_MAP: Record<string, { label: string; css: string; icon: string }> = {
    draft: { label: "Nháp", css: "status-draft", icon: "📝" },
    pending_review: { label: "Chờ duyệt", css: "status-pending", icon: "👀" },
    approved: { label: "Đã duyệt", css: "status-approved", icon: "✅" },
    merged: { label: "Đã merge", css: "status-merged", icon: "🎯" },
};

const REACTION_EMOJIS = ["👍", "💡", "❓", "✅", "🔥", "❤️"];

const TeamWorkspace = () => {
    const { teamId } = useParams<{ teamId: string }>();
    const navigate = useNavigate();
    const editorRef = useRef<HTMLTextAreaElement>(null);

    const [team, setTeam] = useState<Team | null>(null);
    const [drafts, setDrafts] = useState<TeamMemo[]>([]);
    const [mainMemos, setMainMemos] = useState<TeamMemo[]>([]);
    const [tab, setTab] = useState<Tab>("draft");
    const [content, setContent] = useState("");
    const [loading, setLoading] = useState(true);
    const [showMembers, setShowMembers] = useState(false);
    const [copied, setCopied] = useState(false);
    const [searchQuery, setSearchQuery] = useState("");

    // Edit state
    const [editingId, setEditingId] = useState<string | null>(null);
    const [editContent, setEditContent] = useState("");

    // Comment state
    const [openCommentId, setOpenCommentId] = useState<string | null>(null);
    const [comments, setComments] = useState<TeamComment[]>([]);
    const [commentText, setCommentText] = useState("");
    const [loadingComments, setLoadingComments] = useState(false);

    // Review
    const [reviewMemoId, setReviewMemoId] = useState<string | null>(null);
    const [reviewReason, setReviewReason] = useState("");

    const isOwner = useMemo(() => {
        return team?.members?.some((m) => m.role === "owner") ?? false;
    }, [team]);

    const fetchAll = useCallback(async () => {
        if (!teamId) return;
        try {
            setLoading(true);
            const [t, d, m] = await Promise.all([getTeam(teamId), listDrafts(teamId), listMain(teamId)]);
            setTeam(t);
            setDrafts(d);
            setMainMemos(m);
        } catch (e: any) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    }, [teamId]);

    useEffect(() => { fetchAll(); }, [fetchAll]);

    // ========================= ACTIONS =========================

    const handleSave = async () => {
        if (!content.trim() || !teamId) return;
        const tags: string[] = [];
        let m;
        const re = /#(\w+)/g;
        while ((m = re.exec(content)) !== null) tags.push(m[1]);
        await createDraft(teamId, content.trim(), tags);
        setContent("");
        fetchAll();
        editorRef.current?.focus();
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSave(); }
    };

    const onMerge = async (id: string) => { if (teamId) { await mergeMemo(teamId, id); fetchAll(); } };
    const onUnmerge = async (id: string) => { if (teamId) { await unmergeMemo(teamId, id); fetchAll(); } };
    const onDelete = async (id: string) => { if (teamId && confirm("Xóa note này?")) { await deleteTeamMemo(teamId, id); fetchAll(); } };
    const onPin = async (id: string) => { if (teamId) { await pinMemo(teamId, id); fetchAll(); } };

    const startEdit = (memo: TeamMemo) => { setEditingId(memo.id); setEditContent(memo.content); };
    const cancelEdit = () => { setEditingId(null); setEditContent(""); };
    const saveEdit = async () => {
        if (!teamId || !editingId || !editContent.trim()) return;
        const tags: string[] = [];
        let m;
        const re = /#(\w+)/g;
        while ((m = re.exec(editContent)) !== null) tags.push(m[1]);
        await updateTeamMemo(teamId, editingId, editContent.trim(), tags);
        cancelEdit();
        fetchAll();
    };

    const onRequestReview = async (id: string) => { if (teamId) { await requestReview(teamId, id); fetchAll(); } };
    const onSubmitReview = async (id: string, action: "approve" | "reject") => {
        if (teamId) { await submitReview(teamId, id, action, reviewReason); setReviewMemoId(null); setReviewReason(""); fetchAll(); }
    };

    const toggleComments = async (memoId: string) => {
        if (openCommentId === memoId) { setOpenCommentId(null); return; }
        setOpenCommentId(memoId);
        setLoadingComments(true);
        try { if (teamId) { setComments(await listComments(teamId, memoId)); } }
        catch (e) { console.error(e); }
        finally { setLoadingComments(false); }
    };

    const onSendComment = async () => {
        if (!teamId || !openCommentId || !commentText.trim()) return;
        const newComment = await createComment(teamId, openCommentId, commentText.trim());
        setComments((prev) => [...prev, newComment]);
        setCommentText("");
        const updateMemos = (memos: TeamMemo[]) => memos.map((m) => m.id === openCommentId ? { ...m, comment_count: m.comment_count + 1 } : m);
        setDrafts(updateMemos);
        setMainMemos(updateMemos);
    };

    const onDeleteComment = async (commentId: string) => { if (teamId) { await deleteComment(teamId, commentId); setComments((prev) => prev.filter((c) => c.id !== commentId)); } };

    const onToggleReaction = async (memoId: string, emoji: string) => {
        if (!teamId) return;
        const result = await toggleReaction(teamId, memoId, emoji);
        const updateMemos = (memos: TeamMemo[]) => memos.map((m) => m.id === memoId ? { ...m, reaction_counts: result.reaction_counts, user_reactions: result.user_reactions } : m);
        setDrafts(updateMemos);
        setMainMemos(updateMemos);
    };

    const copyCode = () => {
        if (team?.invite_code) { navigator.clipboard.writeText(team.invite_code); setCopied(true); setTimeout(() => setCopied(false), 2000); }
    };

    const fmtTime = (s?: string) => {
        if (!s) return "";
        const ms = Date.now() - new Date(s).getTime();
        const min = Math.floor(ms / 60000);
        if (min < 1) return "vừa xong";
        if (min < 60) return `${min}m`;
        const h = Math.floor(min / 60);
        if (h < 24) return `${h}h`;
        return `${Math.floor(h / 24)}d`;
    };

    const getInitials = (name: string) => name.split(" ").map((w) => w[0]).join("").toUpperCase().slice(0, 2) || "?";

    const memos = tab === "draft" ? drafts : mainMemos;
    const filteredMemos = useMemo(() => {
        if (!searchQuery.trim()) return memos;
        const q = searchQuery.toLowerCase();
        return memos.filter((m) => m.content.toLowerCase().includes(q) || m.tags.some((t) => t.toLowerCase().includes(q)) || m.creator_name.toLowerCase().includes(q));
    }, [memos, searchQuery]);

    const groups = useMemo(() => {
        const pinned = filteredMemos.filter((m) => m.pinned);
        const rest = filteredMemos.filter((m) => !m.pinned);
        const byTag: Record<string, TeamMemo[]> = {};
        const noTag: TeamMemo[] = [];
        rest.forEach((m) => {
            if (m.tags.length > 0) { (byTag[m.tags[0]] ||= []).push(m); } else { noTag.push(m); }
        });
        return { pinned, byTag, noTag };
    }, [filteredMemos]);

    if (loading) {
        return (
            <div className="flex items-center justify-center h-64">
                <div className="animate-spin w-6 h-6 border-2 border-primary border-t-transparent rounded-full" />
            </div>
        );
    }

    // ========================= SUB COMPONENTS =========================

    const Avatar = ({ src, name, size = 24 }: { src?: string; name: string; size?: number }) => {
        if (src) return <img src={src} alt={name} className="member-avatar" style={{ width: size, height: size }} />;
        return <div className="member-avatar-fallback" style={{ width: size, height: size, fontSize: Math.max(8, size * 0.38) }}>{getInitials(name)}</div>;
    };

    const StatusBadge = ({ status }: { status: string }) => {
        const cfg = STATUS_MAP[status] || STATUS_MAP.draft;
        return <span className={cn("status-badge", cfg.css)}>{cfg.icon} {cfg.label}</span>;
    };

    const renderMemo = (memo: TeamMemo) => {
        const isEditing = editingId === memo.id;

        return (
            <article
                key={memo.id}
                className={cn(
                    "team-memo-card",
                    memo.pinned && "pinned",
                    memo.status === "pending_review" && "pending",
                    memo.status === "approved" && "approved",
                )}
            >
                {/* Header */}
                <div className="memo-card-header">
                    <div className="memo-card-author">
                        <Avatar src={memo.creator_avatar} name={memo.creator_name} size={22} />
                        <span className="memo-card-author-name">{memo.creator_name}</span>
                        <span className="memo-card-time">{fmtTime(memo.created_at)}</span>
                        {memo.status !== "draft" && <StatusBadge status={memo.status} />}
                    </div>
                    <div className="memo-card-actions">
                        {/* Pin */}
                        <button className={cn("memo-action-btn", memo.pinned && "!opacity-100")} onClick={() => onPin(memo.id)} title={memo.pinned ? "Bỏ ghim" : "Ghim"}>
                            <BookmarkIcon className={cn("w-3.5 h-3.5", memo.pinned && "fill-current text-primary")} />
                        </button>

                        {/* Edit (drafts only) */}
                        {tab === "draft" && (
                            <button className="memo-action-btn" onClick={() => startEdit(memo)} title="Sửa">
                                <PencilIcon className="w-3.5 h-3.5" />
                            </button>
                        )}

                        {/* Request review */}
                        {tab === "draft" && memo.status === "draft" && (
                            <button className="memo-action-btn info" onClick={() => onRequestReview(memo.id)} title="Gửi duyệt">
                                <SendHorizonal className="w-3.5 h-3.5" />
                            </button>
                        )}

                        {/* Approve/Reject (owner, pending) */}
                        {isOwner && memo.status === "pending_review" && (
                            <>
                                <button className="memo-action-btn success" style={{ opacity: 1 }} onClick={() => onSubmitReview(memo.id, "approve")} title="Duyệt">
                                    <ShieldCheckIcon className="w-3.5 h-3.5" />
                                </button>
                                <button className="memo-action-btn danger" style={{ opacity: 1 }} onClick={() => setReviewMemoId(memo.id)} title="Từ chối">
                                    <XIcon className="w-3.5 h-3.5" />
                                </button>
                            </>
                        )}

                        {/* Merge (owner) */}
                        {tab === "draft" && isOwner && (memo.status === "approved" || memo.status === "draft") && (
                            <button className="memo-action-btn success" onClick={() => onMerge(memo.id)} title="Merge → Chính">
                                <CheckCircle2Icon className="w-3.5 h-3.5" />
                            </button>
                        )}

                        {/* Unmerge (owner, main) */}
                        {tab === "main" && isOwner && (
                            <button className="memo-action-btn" onClick={() => onUnmerge(memo.id)} title="Đưa về Nháp">
                                <UndoIcon className="w-3.5 h-3.5" />
                            </button>
                        )}

                        {/* Delete */}
                        <button className="memo-action-btn danger" onClick={() => onDelete(memo.id)} title="Xóa">
                            <TrashIcon className="w-3.5 h-3.5" />
                        </button>
                    </div>
                </div>

                {/* Content */}
                {isEditing ? (
                    <div>
                        <textarea className="edit-textarea" value={editContent} onChange={(e) => setEditContent(e.target.value)} autoFocus />
                        <div className="edit-actions">
                            <button className="edit-btn cancel" onClick={cancelEdit}>Hủy</button>
                            <button className="edit-btn save" onClick={saveEdit}>Lưu</button>
                        </div>
                    </div>
                ) : (
                    <div className="memo-card-content" onDoubleClick={() => tab === "draft" && startEdit(memo)}>
                        {memo.content}
                    </div>
                )}

                {/* Tags */}
                {memo.tags.length > 0 && (
                    <div className="memo-card-tags">
                        {memo.tags.map((tag) => <span key={tag} className="memo-tag">#{tag}</span>)}
                    </div>
                )}

                {/* Merged info */}
                {memo.merged_by_name && (
                    <div className="memo-card-time" style={{ marginTop: 2 }}>
                        Merged by <strong>{memo.merged_by_name}</strong> · {fmtTime(memo.merged_at)}
                    </div>
                )}

                {/* Review reason */}
                {memo.review_reason && memo.status === "draft" && (
                    <div style={{ fontSize: 11, color: "hsl(40 80% 55%)", background: "hsl(40 80% 55% / 0.08)", borderRadius: 6, padding: "4px 8px", marginTop: 4 }}>
                        💬 Lý do từ chối: {memo.review_reason}
                    </div>
                )}

                {/* Reactions */}
                <div className="reaction-bar">
                    {Object.entries(memo.reaction_counts || {}).map(([emoji, count]) => (
                        <button
                            key={emoji}
                            className={cn("reaction-pill", memo.user_reactions?.includes(emoji) && "active")}
                            onClick={(e) => { e.stopPropagation(); onToggleReaction(memo.id, emoji); }}
                        >
                            <span>{emoji}</span>
                            <span style={{ fontVariantNumeric: "tabular-nums" }}>{count}</span>
                        </button>
                    ))}
                    <div className="reaction-add" style={{ position: "relative" }}>
                        <button className="reaction-pill" style={{ borderStyle: "dashed" }}>+</button>
                        <div className="reaction-picker">
                            {REACTION_EMOJIS.map((emoji) => (
                                <button key={emoji} className="reaction-pick-btn" onClick={(e) => { e.stopPropagation(); onToggleReaction(memo.id, emoji); }}>
                                    {emoji}
                                </button>
                            ))}
                        </div>
                    </div>
                </div>

                {/* Comment toggle */}
                <button
                    onClick={() => toggleComments(memo.id)}
                    style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 11, color: "hsl(var(--muted-foreground))", background: "none", border: "none", cursor: "pointer", marginTop: 4, padding: 0, transition: "color 0.15s" }}
                >
                    <MessageCircleIcon className="w-3.5 h-3.5" />
                    {memo.comment_count > 0 ? `${memo.comment_count} comments` : "Comment"}
                </button>

                {/* Comment thread */}
                {openCommentId === memo.id && (
                    <div className="comment-thread">
                        {loadingComments ? (
                            <div className="memo-card-time" style={{ padding: 4 }}>Đang tải...</div>
                        ) : comments.length === 0 ? (
                            <div className="memo-card-time" style={{ padding: 4 }}>Chưa có comment nào</div>
                        ) : (
                            comments.map((c) => (
                                <div key={c.id} className="comment-item">
                                    <Avatar src={c.user_avatar} name={c.user_name} size={18} />
                                    <div style={{ flex: 1, minWidth: 0 }}>
                                        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                                            <span style={{ fontSize: 11, fontWeight: 600 }}>{c.user_name}</span>
                                            <span className="memo-card-time">{fmtTime(c.created_at)}</span>
                                        </div>
                                        <p style={{ fontSize: 12, color: "hsl(var(--muted-foreground))", lineHeight: 1.5, margin: 0 }}>{c.content}</p>
                                    </div>
                                    <button className="comment-delete memo-action-btn danger" onClick={() => onDeleteComment(c.id)} style={{ width: 20, height: 20 }}>
                                        <XIcon className="w-2.5 h-2.5" />
                                    </button>
                                </div>
                            ))
                        )}
                        <div className="comment-input-row">
                            <input
                                value={commentText}
                                onChange={(e) => setCommentText(e.target.value)}
                                onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); onSendComment(); } }}
                                placeholder="Viết comment..."
                            />
                            <button className="memo-action-btn info" onClick={onSendComment} style={{ opacity: commentText.trim() ? 1 : 0.3 }}>
                                <SendIcon className="w-3.5 h-3.5" />
                            </button>
                        </div>
                    </div>
                )}

                {/* Review reject dialog */}
                {reviewMemoId === memo.id && (
                    <div className="review-dialog">
                        <div style={{ fontSize: 11, fontWeight: 600, color: "hsl(0 60% 60%)" }}>Từ chối note này?</div>
                        <input
                            value={reviewReason}
                            onChange={(e) => setReviewReason(e.target.value)}
                            placeholder="Lý do (tuỳ chọn)..."
                            autoFocus
                        />
                        <div className="edit-actions">
                            <button className="edit-btn cancel" onClick={() => setReviewMemoId(null)}>Huỷ</button>
                            <button className="edit-btn save" style={{ background: "hsl(0 60% 55%)" }} onClick={() => onSubmitReview(memo.id, "reject")}>Từ chối</button>
                        </div>
                    </div>
                )}
            </article>
        );
    };

    return (
        <div className="w-full max-w-3xl mx-auto px-4 py-4">
            {/* Team header */}
            <div className="team-header">
                <button onClick={() => navigate("/app/teams")} style={{ background: "none", border: "none", cursor: "pointer", padding: 4 }}>
                    <ArrowLeftIcon className="w-4 h-4 text-muted-foreground" />
                </button>
                <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="team-header-title">{team?.name}</div>
                    {team?.description && <div className="team-header-desc">{team.description}</div>}
                </div>
                <button
                    onClick={() => setShowMembers(!showMembers)}
                    style={{ display: "flex", alignItems: "center", gap: 4, background: "none", border: "none", cursor: "pointer", fontSize: 12, color: "hsl(var(--muted-foreground))" }}
                >
                    <UsersIcon className="w-4 h-4" />
                    <span>{team?.member_count}</span>
                </button>
            </div>

            {/* Members panel */}
            {showMembers && team && (
                <div className="members-panel">
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                        <span style={{ fontSize: 11, fontWeight: 700, color: "hsl(var(--muted-foreground))", textTransform: "uppercase", letterSpacing: "0.05em" }}>Members</span>
                        <button onClick={copyCode} style={{ display: "flex", alignItems: "center", gap: 4, background: "none", border: "none", cursor: "pointer", color: "hsl(var(--muted-foreground))" }}>
                            <CopyIcon className="w-3 h-3" />
                            <span className="invite-code">{copied ? "Copied!" : team.invite_code}</span>
                        </button>
                    </div>
                    {team.members?.map((m) => (
                        <div key={m.user_id} className="member-row">
                            <Avatar src={m.avatar_url} name={m.display_name || m.user_id} />
                            <span style={{ flex: 1, fontSize: 12, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                                {m.display_name || m.user_id}
                            </span>
                            <Badge variant="secondary" className="text-[9px] h-4 px-1.5">{m.role}</Badge>
                        </div>
                    ))}
                </div>
            )}

            {/* Editor */}
            <div className="team-editor">
                <textarea
                    ref={editorRef}
                    value={content}
                    onChange={(e) => setContent(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="Ghi nháp nhanh vào team... (Enter để lưu)"
                    rows={2}
                />
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 6 }}>
                    <span className="memo-card-time" style={{ fontVariantNumeric: "tabular-nums" }}>
                        {content.trim() ? `${content.trim().split(/\s+/).length}w · ${content.length}c` : ""}
                    </span>
                    <Button onClick={handleSave} disabled={!content.trim()} size="sm" className="h-7 text-xs px-4">
                        Save
                    </Button>
                </div>
            </div>

            {/* Search */}
            <div className="team-search">
                <SearchIcon className="search-icon" />
                <input
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Tìm kiếm trong team..."
                />
            </div>

            {/* Tabs */}
            <div className="team-tabs">
                <button className={cn("team-tab", tab === "draft" && "active")} onClick={() => setTab("draft")}>
                    Nháp ({drafts.length})
                </button>
                <button className={cn("team-tab", tab === "main" && "active")} onClick={() => setTab("main")}>
                    Chính ({mainMemos.length})
                </button>
            </div>

            {/* Memo list */}
            {filteredMemos.length === 0 ? (
                <div className="team-empty">
                    {searchQuery ? "Không tìm thấy kết quả" : tab === "draft" ? "Chưa có nháp nào — viết gì đó ở trên đi!" : "Chưa có gì được merge"}
                </div>
            ) : (
                <>
                    {groups.pinned.length > 0 && (
                        <>
                            <div className="section-label">📌 Ghim</div>
                            {groups.pinned.map(renderMemo)}
                        </>
                    )}
                    {Object.entries(groups.byTag).map(([tag, items]) => (
                        <div key={tag}>
                            <div className="section-label">#{tag}</div>
                            {items.map(renderMemo)}
                        </div>
                    ))}
                    {groups.noTag.length > 0 && (
                        <>
                            {(groups.pinned.length > 0 || Object.keys(groups.byTag).length > 0) && <div className="section-label">Khác</div>}
                            {groups.noTag.map(renderMemo)}
                        </>
                    )}
                </>
            )}
        </div>
    );
};

export default TeamWorkspace;
