"use client";

import { ChevronRight, FileText, Folder, Paperclip, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import type { FileTreeRow } from "@/lib/file-tree/types";
import { getFileTreeRowLabel } from "@/lib/file-tree/types";
import { isRealFileAsset } from "@/lib/file-tree/asset";
import { isTextInputTarget } from "@/lib/file-tree/clipboard";

interface FileTreeProps {
  rows: FileTreeRow[];
  activeId: string;
  selectedRowIds: Set<string>;
  onRowClick: (row: FileTreeRow, event: React.MouseEvent) => void;
  onRowDoubleClick: (row: FileTreeRow, event: React.MouseEvent) => void;
  onRowContextMenu: (row: FileTreeRow, event: React.MouseEvent) => void;
  onRowDragStart?: (row: FileTreeRow, event: React.DragEvent) => void;
  onToggleExpand: (docId: string) => void;
  onCreateChild: (parentId: string | null) => void;
  onBlankMouseDown?: (event: React.MouseEvent) => void;
  onDropFiles?: (docId: string, files: FileList) => void;
  onInternalDrop?: (args: { targetRow: FileTreeRow; rowIds: string[]; copy: boolean }) => void;
}

const INDENT = 16;

export function FileTree({
  rows,
  activeId,
  selectedRowIds,
  onRowClick,
  onRowDoubleClick,
  onRowContextMenu,
  onRowDragStart,
  onToggleExpand,
  onCreateChild,
  onBlankMouseDown,
  onDropFiles,
  onInternalDrop,
}: FileTreeProps) {
  if (rows.length === 0) {
    return <div className="px-4 py-6 text-sm text-gray-400">暂无页面，点击下方按钮创建</div>;
  }

  return (
    <div
      className="w-full min-w-0 max-w-full space-y-0.5 overflow-x-hidden"
      onDragOver={(event) => {
        if (!onDropFiles) return;
        event.preventDefault();
        if (event.dataTransfer.files?.length) {
          event.dataTransfer.dropEffect = "copy";
        }
      }}
      onDrop={(event) => {
        if (onDropFiles && event.dataTransfer.files?.length) {
          event.preventDefault();
          const files = event.dataTransfer.files;
          const activeDocRow = rows.find(
            (row) => row.kind === "doc" && row.docId === activeId,
          );
          const firstDocRow = rows.find((row) => row.kind === "doc");
          const targetDocId = activeDocRow?.docId ?? firstDocRow?.docId ?? "";
          onDropFiles(targetDocId, files);
        }
      }}
      onMouseDown={(event) => {
        if (event.target === event.currentTarget) {
          onBlankMouseDown?.(event);
        }
      }}
    >
      {rows.map((row) => {
        const label = getFileTreeRowLabel(row);
        const selected = selectedRowIds.has(row.rowId);
        const active = row.kind !== "asset" && row.docId === activeId;    
        const draggable =
          row.kind === "doc" || (row.kind === "asset" && isRealFileAsset(row.asset));
        const baseClass =
          "flex w-full min-w-0 max-w-full select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm text-gray-700 hover:bg-[#f5f7fb]";
        const activeClass =
          row.kind === "index"
            ? "text-[#2563eb] font-medium"
            : row.kind === "doc"
              ? "text-[#2563eb]"
              : "";
        const paddingLeft =
          row.kind === "doc" ? row.depth * INDENT + 8 : row.depth * INDENT + 32;

        return (
          <div
            key={row.rowId}
            className={cn(baseClass, active && activeClass, selected && "bg-[#e8f2ff] text-[#2563eb]")}
            style={{ paddingLeft }}
            onClick={(event) => onRowClick(row, event)}
            onDoubleClick={(event) => onRowDoubleClick(row, event)}
            onContextMenu={(event) => onRowContextMenu(row, event)}
            onMouseDown={(event) => {
              // 避免 Shift 多选时触发浏览器默认的文本范围选择（VS Code 资源管理器不会出现该行为）
              if (event.button !== 0) return;
              if (!event.shiftKey) return;
              if (isTextInputTarget(event.target)) return;
              event.preventDefault();
            }}
            draggable={draggable}
            onDragStart={(event) => {
              if (!draggable) return;
              if (!selectedRowIds.has(row.rowId)) {
                onRowDragStart?.(row, event);
              }
              const rowIds = selectedRowIds.has(row.rowId) ? Array.from(selectedRowIds) : [row.rowId];
              const payload = JSON.stringify({ type: "mnote-file-tree-dnd", version: 1, rowIds });
              try {
                event.dataTransfer.setData("application/x-mnote-file-tree", payload);
              } catch {
                // ignore
              }
              event.dataTransfer.setData("text/plain", payload);
              event.dataTransfer.effectAllowed = event.altKey ? "copyMove" : "move";
            }}
            onDragOver={(event) => {
              const types = Array.from(event.dataTransfer.types ?? []);
              const hasInternal = types.includes("application/x-mnote-file-tree");
              if (hasInternal && onInternalDrop) {
                event.preventDefault();
                event.dataTransfer.dropEffect = event.altKey ? "copy" : "move";
                return;
              }
              if (!onDropFiles) return;
              event.preventDefault();
              if (event.dataTransfer.files?.length) {
                event.dataTransfer.dropEffect = "copy";
              }
            }}
            onDrop={(event) => {
              const types = Array.from(event.dataTransfer.types ?? []);
              const isInternal = types.includes("application/x-mnote-file-tree");
              if (isInternal && onInternalDrop) {
                const raw =
                  event.dataTransfer.getData("application/x-mnote-file-tree") || "";
                try {
                  const parsed = JSON.parse(raw) as { type?: string; version?: number; rowIds?: unknown };
                  if (parsed?.type === "mnote-file-tree-dnd" && parsed.version === 1 && Array.isArray(parsed.rowIds)) {
                    event.preventDefault();
                    onInternalDrop({
                      targetRow: row,
                      rowIds: parsed.rowIds.filter((id) => typeof id === "string") as string[],
                      copy: event.altKey,
                    });
                    return;
                  }
                } catch {
                  // ignore
                }
              }

              if (onDropFiles && event.dataTransfer.files?.length) {
                event.preventDefault();
                event.stopPropagation();
                onDropFiles(row.docId, event.dataTransfer.files);
              }
            }}
            role="button"
            tabIndex={0}
          >
            {row.kind === "doc" ? (
              <>
                {row.hasChildren ? (
                  <button
                    type="button"
                    aria-label="展开或折叠"
                    onClick={(event) => {
                      event.stopPropagation();
                      onToggleExpand(row.docId);
                    }}
                    className="flex h-5 w-5 items-center justify-center rounded-md hover:bg-gray-100"
                  >
                    <ChevronRight
                      className={cn(
                        "h-3.5 w-3.5 transition-transform",
                        row.isExpanded && "rotate-90",
                      )}
                    />
                  </button>
                ) : (
                  <span className="h-5 w-5" />
                )}
                <Folder className="h-4 w-4 text-[#2563eb]" />
                <span className="min-w-0 flex-1 truncate text-left">{label}</span>
                <button
                  type="button"
                  aria-label="新建子页面"
                  onClick={(event) => {
                    event.stopPropagation();
                    onCreateChild(row.docId);
                  }}
                  className="rounded-md p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-700"
                >
                  <Plus className="h-3.5 w-3.5" />
                </button>
              </>
            ) : row.kind === "index" ? (
              <>
                <span className="h-4 w-4" />
                <FileText className="h-4 w-4 text-gray-500" />
                <span className="min-w-0 flex-1 truncate text-left">{label}</span>
              </>
            ) : (
              <>
                <span className="h-4 w-4" />
                <Paperclip className="h-4 w-4 text-gray-500" />
                <span className="min-w-0 flex-1 truncate text-left">{label}</span>
              </>
            )}
          </div>
        );
      })}
    </div>
  );
}
