"use client";

import { useEffect, useMemo, useState } from "react";
import { useConvexAuth, useMutation, useQuery } from "convex/react";
import { MessageSquare, CornerDownRight, CheckCircle2, Circle, ExternalLink } from "lucide-react";
import { api } from "@/lib/convex/api";
import { useCommentsUiStore } from "@/store/comments-ui";
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";

const makeId = (): string => {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  return `${Date.now()}_${Math.random().toString(16).slice(2)}`;
};

const jumpToBlock = (blockId: string) => {
  if (!blockId) return;
  const target = document.querySelector<HTMLElement>(`[data-id="${blockId}"]`);
  if (target) {
    target.scrollIntoView({ behavior: "smooth", block: "center" });
  } else {
    window.alert("未找到对应块（可能已被删除或未渲染）");
  }
};

export function DocumentCommentsDrawer() {
  const { isAuthenticated } = useConvexAuth();
  const open = useCommentsUiStore((s) => s.open);
  const target = useCommentsUiStore((s) => s.target);
  const close = useCommentsUiStore((s) => s.close);

  const documentId = target?.documentId ?? "";
  const workspaceId = target?.workspaceId ?? "";
  const focusBlockId = target?.blockId ?? null;

  const [includeResolved, setIncludeResolved] = useState(false);
  const threads = useQuery(
    api.comments.listThreadsByDocument,
    open && isAuthenticated && documentId ? { documentId, includeResolved } : "skip",
  );
  const currentUser = useQuery(api.users.currentUser, open && isAuthenticated ? {} : "skip");

  const createThread = useMutation(api.comments.createThread);
  const reply = useMutation(api.comments.reply);
  const setResolved = useMutation(api.comments.setResolved);
  const editMessage = useMutation(api.comments.editMessage);
  const deleteMessage = useMutation(api.comments.deleteMessage);

  // 说明：messages 需要 threadId；在选择线程后再订阅。
  const [activeThreadId, setActiveThreadId] = useState<string | null>(null);
  const activeMessages = useQuery(
    api.comments.listMessagesByThread,
    open && isAuthenticated && activeThreadId ? { threadId: activeThreadId } : "skip",
  );

  const [activeTab, setActiveTab] = useState<"page" | "block">("page");
  useEffect(() => {
    if (!open) return;
    setActiveTab(focusBlockId ? "block" : "page");
    setActiveThreadId(null);
    setEditingMessageId(null);
    setEditingDraft("");
  }, [focusBlockId, open]);

  const { pageThreads, blockThreads } = useMemo(() => {
    const list = Array.isArray(threads) ? threads : [];
    const pageThreads = list.filter((t: any) => !t.blockId);
    const blockThreads = list.filter((t: any) => Boolean(t.blockId));
    return { pageThreads, blockThreads };
  }, [threads]);

  const blockThreadsForFocus = useMemo(() => {
    if (!focusBlockId) return blockThreads;
    return blockThreads.filter((t: any) => String(t.blockId) === String(focusBlockId));
  }, [blockThreads, focusBlockId]);

  const activeThread = useMemo(() => {
    const list = Array.isArray(threads) ? threads : [];
    return list.find((t: any) => String(t.id) === String(activeThreadId)) ?? null;
  }, [activeThreadId, threads]);

  const [draft, setDraft] = useState("");
  const [replyDraft, setReplyDraft] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [editingMessageId, setEditingMessageId] = useState<string | null>(null);
  const [editingDraft, setEditingDraft] = useState("");

  const submitNewThread = async (blockId: string | null) => {
    if (!documentId || !workspaceId) return;
    const body = draft.trim();
    if (!body) {
      window.alert("请输入评论内容");
      return;
    }
    setSubmitting(true);
    try {
      const threadId = makeId();
      const messageId = makeId();
      await createThread({
        id: threadId,
        documentId,
        workspaceId,
        blockId,
        messageId,
        body,
      });
      setDraft("");
      setActiveThreadId(threadId);
    } catch (e) {
      window.alert(e instanceof Error ? e.message : "创建评论失败");
    } finally {
      setSubmitting(false);
    }
  };

  const submitReply = async () => {
    if (!activeThreadId) return;
    const body = replyDraft.trim();
    if (!body) {
      window.alert("请输入回复内容");
      return;
    }
    setSubmitting(true);
    try {
      await reply({ threadId: activeThreadId, messageId: makeId(), body });
      setReplyDraft("");
    } catch (e) {
      window.alert(e instanceof Error ? e.message : "回复失败");
    } finally {
      setSubmitting(false);
    }
  };

  const submitEdit = async () => {
    if (!editingMessageId) return;
    const body = editingDraft.trim();
    if (!body) {
      window.alert("请输入评论内容");
      return;
    }
    setSubmitting(true);
    try {
      await editMessage({ messageId: editingMessageId, body });
      setEditingMessageId(null);
      setEditingDraft("");
    } catch (e) {
      window.alert(e instanceof Error ? e.message : "编辑失败");
    } finally {
      setSubmitting(false);
    }
  };

  const submitDelete = async (messageId: string) => {
    const ok = window.confirm("确定删除这条评论吗？");
    if (!ok) return;
    setSubmitting(true);
    try {
      await deleteMessage({ messageId });
      if (editingMessageId === messageId) {
        setEditingMessageId(null);
        setEditingDraft("");
      }
    } catch (e) {
      window.alert(e instanceof Error ? e.message : "删除失败");
    } finally {
      setSubmitting(false);
    }
  };

  const toggleResolved = async () => {
    if (!activeThreadId || !activeThread) return;
    const next = !activeThread.resolvedAt;
    setSubmitting(true);
    try {
      await setResolved({ threadId: activeThreadId, resolved: next });
    } catch (e) {
      window.alert(e instanceof Error ? e.message : "更新状态失败");
    } finally {
      setSubmitting(false);
    }
  };

  const ThreadList = ({ list }: { list: any[] }) => {
    if (!list.length) {
      return (
        <div className="rounded-lg border border-dashed border-[#e2e8f0] px-4 py-10 text-center text-sm text-gray-500">
          暂无评论
        </div>
      );
    }
    return (
      <div className="space-y-2">
        {list.map((t) => {
          const isActive = String(t.id) === String(activeThreadId);
          const resolved = Boolean(t.resolvedAt);
          return (
            <button
              key={t.id}
              type="button"
              className={cn(
                "w-full rounded-lg border px-4 py-3 text-left text-sm transition-colors",
                isActive ? "border-[#c7d2fe] bg-[#eef2ff]" : "border-[#e2e8f0] bg-white hover:bg-gray-50",
              )}
              onClick={() => setActiveThreadId(t.id)}
            >
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 text-xs text-gray-500">
                    {resolved ? (
                      <span className="inline-flex items-center gap-1 text-green-700">
                        <CheckCircle2 className="h-4 w-4" />
                        已解决
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-gray-500">
                        <Circle className="h-4 w-4" />
                        进行中
                      </span>
                    )}
                    <span>·</span>
                    <span>{t.commentCount} 条</span>
                    {t.blockId ? (
                      <>
                        <span>·</span>
                        <span className="inline-flex items-center gap-1">
                          块评论
                          <ExternalLink
                            className="h-3.5 w-3.5"
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              jumpToBlock(String(t.blockId));
                            }}
                          />
                        </span>
                      </>
                    ) : null}
                  </div>
                  <div className="mt-1 truncate font-medium text-gray-900">
                    {t.lastCommentPreview || "（无预览）"}
                  </div>
                  <div className="mt-1 text-xs text-gray-500">
                    {t.lastCommentBy?.name || "匿名"} · {new Date(t.lastActivityAt).toLocaleString()}
                  </div>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    );
  };

  const ThreadDetail = () => {
    if (!activeThreadId || !activeThread) {
      return (
        <div className="rounded-lg border border-dashed border-[#e2e8f0] px-4 py-10 text-center text-sm text-gray-500">
          选择一条评论后查看详情
        </div>
      );
    }

    const list = Array.isArray(activeMessages) ? activeMessages : [];
    return (
      <div className="space-y-3">
        <div className="flex items-center justify-between rounded-lg border border-[#e2e8f0] bg-white px-4 py-3">
          <div className="text-sm font-medium text-gray-800">
            {activeThread.blockId ? "块评论" : "页面评论"}
          </div>
          <div className="flex items-center gap-2">
            {activeThread.blockId ? (
              <Button
                type="button"
                size="sm"
                variant="outline"
                onClick={() => jumpToBlock(String(activeThread.blockId))}
              >
                定位到块
              </Button>
            ) : null}
            <Button type="button" size="sm" variant="outline" onClick={toggleResolved} disabled={submitting}>
              {activeThread.resolvedAt ? "取消解决" : "标记解决"}
            </Button>
          </div>
        </div>

        <div className="max-h-[38vh] space-y-2 overflow-y-auto rounded-lg border border-[#eef2ff] bg-[#fbfbff] p-3">
          {list.length === 0 ? (
            <div className="py-6 text-center text-sm text-gray-500">加载中...</div>
          ) : (
            list.map((m: any) => (
              <div key={m.id} className="rounded-md border border-[#e2e8f0] bg-white p-3 text-sm">
                <div className="flex items-center justify-between text-xs text-gray-500">
                  <span>{m.createdBy?.name || "匿名"}</span>
                  <span>{new Date(m.createdAt).toLocaleString()}</span>
                </div>
                <div className={cn("mt-2 whitespace-pre-wrap text-gray-800", m.deletedAt && "text-gray-400")}>
                  {m.deletedAt ? (
                    "该评论已删除"
                  ) : editingMessageId === String(m.id) ? (
                    <div className="space-y-2">
                      <Textarea
                        value={editingDraft}
                        onChange={(e) => setEditingDraft(e.target.value)}
                        className="min-h-[90px]"
                        disabled={submitting}
                      />
                      <div className="flex gap-2">
                        <Button type="button" size="sm" onClick={submitEdit} disabled={submitting}>
                          保存
                        </Button>
                        <Button
                          type="button"
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setEditingMessageId(null);
                            setEditingDraft("");
                          }}
                          disabled={submitting}
                        >
                          取消
                        </Button>
                      </div>
                    </div>
                  ) : (
                    m.body
                  )}
                </div>

                {!m.deletedAt && editingMessageId !== String(m.id) ? (
                  <div className="mt-2 flex gap-2 text-xs">
                    {currentUser && String((currentUser as any)?._id ?? "") === String(m.createdBy?.id ?? "") ? (
                      <>
                        <Button
                          type="button"
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setEditingMessageId(String(m.id));
                            setEditingDraft(String(m.body ?? ""));
                          }}
                          disabled={submitting}
                        >
                          编辑
                        </Button>
                        <Button
                          type="button"
                          size="sm"
                          variant="outline"
                          onClick={() => submitDelete(String(m.id))}
                          disabled={submitting}
                        >
                          删除
                        </Button>
                      </>
                    ) : null}
                  </div>
                ) : null}
              </div>
            ))
          )}
        </div>

        <div className="rounded-lg border border-[#e2e8f0] bg-white p-3">
          <div className="flex items-center gap-2 text-xs text-gray-500">
            <CornerDownRight className="h-4 w-4" />
            回复
          </div>
          <Textarea
            value={replyDraft}
            onChange={(e) => setReplyDraft(e.target.value)}
            placeholder="输入回复内容..."
            className="mt-2 min-h-20"
          />
          <div className="mt-2 flex justify-end">
            <Button type="button" onClick={submitReply} disabled={submitting}>
              发送
            </Button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <Drawer
      open={open}
      onOpenChange={(next) => {
        if (!next) close();
      }}
    >
      <DrawerContent className="max-h-[92vh]">
        <DrawerHeader className="text-left">
          <DrawerTitle className="flex items-center gap-2">
            <MessageSquare className="h-5 w-5" />
            评论
          </DrawerTitle>
          <DrawerDescription>支持页面评论与块评论（先实现核心闭环）。</DrawerDescription>
        </DrawerHeader>

        {!isAuthenticated ? (
          <div className="px-4 pb-6 text-sm text-gray-500">未登录，无法查看评论。</div>
        ) : !documentId ? (
          <div className="px-4 pb-6 text-sm text-gray-500">缺少 documentId。</div>
        ) : (
          <div className="grid gap-4 px-4 pb-6 lg:grid-cols-2">
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <div className="text-sm font-semibold text-gray-800">线程列表</div>
                <div className="flex items-center gap-2">
                  <Button
                    type="button"
                    size="sm"
                    variant="ghost"
                    onClick={() => setIncludeResolved((prev) => !prev)}
                  >
                    {includeResolved ? "隐藏已解决" : "显示已解决"}
                  </Button>
                </div>
              </div>

              <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as any)}>
                <TabsList className="w-full">
                  <TabsTrigger value="page" className="flex-1">
                    页面评论（{pageThreads.length}）
                  </TabsTrigger>
                  <TabsTrigger value="block" className="flex-1">
                    块评论（{blockThreads.length}）
                  </TabsTrigger>
                </TabsList>

                <TabsContent value="page" className="mt-3 space-y-3">
                  <div className="rounded-lg border border-[#e2e8f0] bg-white p-3">
                    <div className="text-xs font-medium text-gray-600">新建页面评论</div>
                    <Textarea
                      value={draft}
                      onChange={(e) => setDraft(e.target.value)}
                      placeholder="输入评论内容..."
                      className="mt-2 min-h-20"
                    />
                    <div className="mt-2 flex justify-end">
                      <Button type="button" onClick={() => submitNewThread(null)} disabled={submitting}>
                        发送
                      </Button>
                    </div>
                  </div>
                  <ThreadList list={pageThreads} />
                </TabsContent>

                <TabsContent value="block" className="mt-3 space-y-3">
                  <div className="rounded-lg border border-[#e2e8f0] bg-white p-3">
                    <div className="text-xs font-medium text-gray-600">新建块评论</div>
                    <div className="mt-2 flex items-center gap-2">
                      <Input
                        value={focusBlockId ?? ""}
                        readOnly
                        placeholder="从块菜单进入后会自动带上 blockId"
                        className="h-9 text-xs"
                      />
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        disabled={!focusBlockId}
                        onClick={() => (focusBlockId ? jumpToBlock(focusBlockId) : null)}
                      >
                        定位
                      </Button>
                    </div>
                    <Textarea
                      value={draft}
                      onChange={(e) => setDraft(e.target.value)}
                      placeholder={focusBlockId ? "对该块发表评论..." : "请从块菜单进入以指定 blockId"}
                      className="mt-2 min-h-20"
                      disabled={!focusBlockId}
                    />
                    <div className="mt-2 flex justify-end">
                      <Button
                        type="button"
                        onClick={() => submitNewThread(focusBlockId)}
                        disabled={submitting || !focusBlockId}
                      >
                        发送
                      </Button>
                    </div>
                  </div>
                  <ThreadList list={blockThreadsForFocus} />
                </TabsContent>
              </Tabs>
            </div>

            <div className="space-y-3">
              <div className="text-sm font-semibold text-gray-800">线程详情</div>
              <ThreadDetail />
            </div>
          </div>
        )}
      </DrawerContent>
    </Drawer>
  );
}
