"use client";

import { useEffect, useState } from "react";
import clsx from "clsx";
import { ChevronRight, Folder as FolderIcon } from "lucide-react";
import {
  type DriveFolderNode,
} from "@/lib/addons/google-drive-tree";

type DriveFolderTreeProps = {
  nodes: DriveFolderNode[];
  selectedId: string;
  onSelect: (folderId: string, folderName: string) => void;
  query: string;
  level?: number;
  displayName?: (node: DriveFolderNode) => string;
  variant?: "default" | "native-zimbra";
  sectionLabel?: string;
  emptyLabel?: string;
  expandLabel?: string;
  collapseLabel?: string;
  selectedLabel?: string;
};

export function DriveFolderTree({
  nodes,
  selectedId,
  onSelect,
  query,
  level = 0,
  displayName,
  variant = "default",
  sectionLabel,
  emptyLabel = "No folders found.",
  expandLabel = "Expand folder",
  collapseLabel = "Collapse folder",
  selectedLabel = "Selected",
}: DriveFolderTreeProps) {
  const visibleNodes = nodes.filter((node) => driveFolderTreeMatches(node, query));

  if (!visibleNodes.length) {
    return <p className="p-3 text-sm font-semibold text-slate-500">{emptyLabel}</p>;
  }

  if (variant === "native-zimbra" && level === 0) {
    return (
      <div className="grid gap-1.5">
        {sectionLabel ? <p className="px-2 text-[11px] font-bold uppercase tracking-[0.08em] text-slate-500">{sectionLabel}</p> : null}
        <div className="grid gap-1">
          {visibleNodes.map((node) => (
            <DriveFolderTreeNode
              key={node.id}
              node={node}
              selectedId={selectedId}
              onSelect={onSelect}
              query={query}
              level={level}
              displayName={displayName}
              variant={variant}
              emptyLabel={emptyLabel}
              expandLabel={expandLabel}
              collapseLabel={collapseLabel}
              selectedLabel={selectedLabel}
            />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="grid gap-1">
      {visibleNodes.map((node) => (
        <DriveFolderTreeNode
          key={node.id}
          node={node}
          selectedId={selectedId}
          onSelect={onSelect}
          query={query}
          level={level}
          displayName={displayName}
          variant={variant}
          emptyLabel={emptyLabel}
          expandLabel={expandLabel}
          collapseLabel={collapseLabel}
          selectedLabel={selectedLabel}
        />
      ))}
    </div>
  );
}

function DriveFolderTreeNode({
  node,
  selectedId,
  onSelect,
  query,
  level,
  displayName,
  variant = "default",
  emptyLabel,
  expandLabel,
  collapseLabel,
  selectedLabel,
}: {
  node: DriveFolderNode;
  selectedId: string;
  onSelect: (folderId: string, folderName: string) => void;
  query: string;
  level: number;
  displayName?: (node: DriveFolderNode) => string;
  variant?: DriveFolderTreeProps["variant"];
  emptyLabel: string;
  expandLabel: string;
  collapseLabel: string;
  selectedLabel: string;
}) {
  const [expanded, setExpanded] = useState<boolean>(level === 0 || Boolean(query));
  useEffect(() => {
    if (query) setExpanded(true);
  }, [query]);
  const active = node.id === selectedId;
  const childMatches = node.children.filter((child) => driveFolderTreeMatches(child, query));
  const hasChildren = childMatches.length > 0;
  const label = displayName?.(node) ?? node.name;
  const isNativeZimbra = variant === "native-zimbra";
  return (
    <div className="grid gap-1">
      <div
        className={clsx(
          "flex items-center gap-2 text-left transition",
          isNativeZimbra
            ? active
              ? "rounded-sm bg-sky-100 text-slate-950"
              : "rounded-sm text-slate-700 hover:bg-slate-50"
            : active
              ? "rounded-md bg-[color-mix(in_srgb,var(--accent)_10%,white)] text-[var(--accent)]"
              : "rounded-md text-slate-700 hover:bg-slate-50",
          isNativeZimbra ? "px-2 py-1 text-[13px] font-medium" : "px-3 py-2 text-sm font-semibold"
        )}
        style={{ paddingLeft: `${isNativeZimbra ? 8 + level * 18 : 12 + level * 16}px` }}
      >
        <button
          type="button"
          onClick={(event) => {
            event.stopPropagation();
            if (hasChildren) setExpanded((current) => !current);
          }}
          className={clsx(
            "grid shrink-0 place-items-center rounded-sm transition",
            isNativeZimbra ? "h-4 w-4 text-slate-500" : "h-5 w-5 text-slate-400",
            hasChildren ? "hover:bg-slate-100 hover:text-slate-700" : isNativeZimbra ? "opacity-0" : "opacity-30"
          )}
          aria-label={expanded ? collapseLabel : expandLabel}
        >
          <ChevronRight size={isNativeZimbra ? 12 : 14} className={clsx("transition", expanded && "rotate-90")} />
        </button>
        <button type="button" onClick={() => onSelect(node.id, label)} className="flex min-w-0 flex-1 items-center gap-2 text-left">
          <FolderIcon size={isNativeZimbra ? 15 : 16} className={clsx("shrink-0", isNativeZimbra ? "text-slate-500" : active ? "text-[var(--accent)]" : "text-slate-400")} />
          <span className="min-w-0 flex-1 truncate">{label}</span>
          {!isNativeZimbra && active ? <span className="rounded-full bg-white px-2 py-0.5 text-[10px] font-black uppercase tracking-[0.12em]">{selectedLabel}</span> : null}
        </button>
      </div>
      {expanded && hasChildren ? (
        <DriveFolderTree
          nodes={childMatches}
          selectedId={selectedId}
          onSelect={onSelect}
          query={query}
          level={level + 1}
          displayName={displayName}
          variant={variant}
          emptyLabel={emptyLabel}
          expandLabel={expandLabel}
          collapseLabel={collapseLabel}
          selectedLabel={selectedLabel}
        />
      ) : null}
    </div>
  );
}

function driveFolderTreeMatches(node: DriveFolderNode, query: string): boolean {
  if (!query) return true;
  if (node.name.toLowerCase().includes(query)) return true;
  return node.children.some((child) => driveFolderTreeMatches(child, query));
}
