import type { ReactNode } from 'react';
import { ChevronDown, ChevronRight, FolderClosed, FolderOpen, Search } from 'lucide-react';

type KeywordSectionNode = {
  directoryKey: string;
  keyword: string;
  merchant_count: number;
};

type TaskSectionNode = {
  directoryKey: string;
  task_label: string;
  merchant_count: number;
  keywordSections: KeywordSectionNode[];
};

type BatchSectionNode = {
  directoryKey: string;
  batch_id: string;
  merchant_count: number;
  taskSections: TaskSectionNode[];
};

interface SearchResultsDirectoryTreeProps {
  loading?: boolean;
  sections: BatchSectionNode[];
  openKeys: Set<string>;
  selectedKeywordKey: string | null;
  onToggleDirectory: (directoryKey: string) => void;
  onSelectKeyword: (directoryKey: string) => void;
}

function CountBadge({ children }: { children: ReactNode }) {
  return (
    <span className="shrink-0 whitespace-nowrap rounded-full bg-background px-1.5 py-0.5 text-[10px] text-muted-foreground">
      {children}
    </span>
  );
}

function MerchantCount({ count, selected = false }: { count: number; selected?: boolean }) {
  return (
    <span className={`shrink-0 whitespace-nowrap text-[11px] ${selected ? 'text-primary/80' : 'text-muted-foreground'}`}>
      {count} 个商家
    </span>
  );
}

export function SearchResultsDirectoryTree({
  loading = false,
  sections,
  openKeys,
  selectedKeywordKey,
  onToggleDirectory,
  onSelectKeyword,
}: SearchResultsDirectoryTreeProps) {
  if (loading && sections.length === 0) {
    return (
      <div className="space-y-2 p-2">
        {Array.from({ length: 4 }).map((_, index) => (
          <div key={index} className="h-14 animate-pulse rounded-lg bg-muted/60" />
        ))}
      </div>
    );
  }

  if (sections.length === 0) {
    return (
      <div className="p-4 text-sm text-muted-foreground">
        暂无可浏览的搜索结果目录
      </div>
    );
  }

  return (
    <div className="space-y-2 py-2 pl-0.5 pr-1">
      {sections.map((batchSection) => {
        const batchOpen = openKeys.has(batchSection.directoryKey);

        return (
          <div key={batchSection.directoryKey} className="rounded-lg border border-border/70 bg-background/80">
            <button
              type="button"
              onClick={() => onToggleDirectory(batchSection.directoryKey)}
              className="flex w-full items-start gap-1.5 rounded-lg py-2.5 pl-1.5 pr-1 text-left transition-colors hover:bg-muted/50"
            >
              {batchOpen ? (
                <ChevronDown className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
              ) : (
                <ChevronRight className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
              )}
              {batchOpen ? (
                <FolderOpen className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />
              ) : (
                <FolderClosed className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />
              )}
              <div className="min-w-0 flex-1">
                <div className="flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap">
                  <span className="min-w-0 truncate text-xs font-medium text-foreground">{batchSection.batch_id}</span>
                  <CountBadge>{batchSection.taskSections.length} 个任务</CountBadge>
                  <MerchantCount count={batchSection.merchant_count} />
                </div>
              </div>
            </button>

            {batchOpen && (
              <div className="space-y-1.5 py-0.5 pl-1 pr-0.5 pb-2">
                {batchSection.taskSections.map((taskSection) => {
                  const taskOpen = openKeys.has(taskSection.directoryKey);

                  return (
                    <div key={taskSection.directoryKey} className="rounded-md border border-border/60 bg-muted/20">
                      <button
                        type="button"
                        onClick={() => onToggleDirectory(taskSection.directoryKey)}
                        className="flex w-full items-start gap-1.5 rounded-md py-2 pl-1.5 pr-1 text-left transition-colors hover:bg-muted/60"
                      >
                        {taskOpen ? (
                          <ChevronDown className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                        ) : (
                          <ChevronRight className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                        )}
                        <div className="min-w-0 flex-1">
                          <div className="flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap">
                            <span className="min-w-0 truncate text-xs font-medium text-foreground">{taskSection.task_label}</span>
                            <MerchantCount count={taskSection.merchant_count} />
                          </div>
                        </div>
                      </button>

                      {taskOpen && (
                        <div className="space-y-1 py-1 pl-1 pr-0.5 pb-1.5">
                          {taskSection.keywordSections.map((keywordSection) => {
                            const selected = selectedKeywordKey === keywordSection.directoryKey;

                            return (
                              <button
                                key={keywordSection.directoryKey}
                                type="button"
                                onClick={() => onSelectKeyword(keywordSection.directoryKey)}
                                className={`flex w-full items-start gap-1.5 rounded-md border py-2 pl-1.5 pr-1 text-left transition-colors ${selected
                                  ? 'border-primary/40 bg-primary/10 text-primary'
                                  : 'border-transparent bg-background/80 hover:border-border hover:bg-background'}`}
                              >
                                <Search className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${selected ? 'text-primary' : 'text-muted-foreground'}`} />
                                <div className="min-w-0 flex-1">
                                  <div className="flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap">
                                    <span className="min-w-0 truncate text-xs font-medium">{keywordSection.keyword || '-'}</span>
                                    <MerchantCount count={keywordSection.merchant_count} selected={selected} />
                                  </div>
                                </div>
                              </button>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}
