/**
 * Folder tree view — the "Folder Content" pane of a dataset (Option B).
 *
 * Renders the real folder hierarchy persisted via folder_path (migration 026): expandable folders,
 * image files, and segmentation masks nested under the scan they segment (parentFileId). Built from
 * the flat file list by the pure buildFolderTree adapter.
 */
import { useMemo, useState } from 'react';
import { ChevronDown, ChevronRight, Folder, FolderOpen, Layers, Library, ScanLine } from 'lucide-react';

import { Card, CardContent, cn } from '@ump/shared';
import type { ImagehubFile } from '@ump/shared';

import { formatBytes } from '../domain/workspaceModel';
import { buildFolderTree, type TreeFile, type TreeFolder } from '../domain/folderTree';

function FileRow({ file, depth }: { file: TreeFile; depth: number }) {
  const isMask = file.fileKind === 'segmentation';
  return (
    <>
      <div className="flex items-center gap-2 py-1.5 pr-2" style={{ paddingLeft: depth * 18 + 26 }}>
        {isMask ? (
          <Layers className="h-4 w-4 shrink-0 text-accent" />
        ) : (
          <ScanLine className="h-4 w-4 shrink-0 text-muted-foreground" />
        )}
        <span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">{file.name}</span>
        <span className="shrink-0 text-[11px] text-muted-foreground">
          {isMask ? file.organLabel || 'nhãn' : 'ảnh'} · {formatBytes(file.size)}
        </span>
      </div>
      {file.masks.map((m) => (
        <FileRow key={m.id} file={m} depth={depth + 1} />
      ))}
    </>
  );
}

function FolderRow({ folder, depth }: { folder: TreeFolder; depth: number }) {
  const [open, setOpen] = useState(depth === 0);
  return (
    <>
      <button
        onClick={() => setOpen((o) => !o)}
        className="flex w-full items-center gap-2 py-1.5 pr-2 text-left hover:bg-muted/50"
        style={{ paddingLeft: depth * 18 + 6 }}
        aria-expanded={open}
      >
        {open ? (
          <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" />
        ) : (
          <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
        )}
        {open ? (
          <FolderOpen className="h-4 w-4 shrink-0 text-accent" />
        ) : (
          <Folder className="h-4 w-4 shrink-0 text-accent" />
        )}
        <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">{folder.name}</span>
        <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{folder.fileCount} tệp</span>
      </button>
      {open && (
        <>
          {folder.folders.map((sub) => (
            <FolderRow key={sub.path} folder={sub} depth={depth + 1} />
          ))}
          {folder.files.map((file) => (
            <FileRow key={file.id} file={file} depth={depth} />
          ))}
        </>
      )}
    </>
  );
}

export function FolderTreeView({ files }: { files: ImagehubFile[] }) {
  const root = useMemo(() => buildFolderTree(files), [files]);
  const isEmpty = root.folders.length === 0 && root.files.length === 0;

  return (
    <Card>
      <CardContent className={cn('p-2', isEmpty && 'p-0')}>
        {isEmpty ? (
          <div className="flex flex-col items-center gap-2 py-12 text-center text-sm text-muted-foreground">
            <Library className="h-6 w-6" />
            Bộ dữ liệu này chưa có tệp nào.
          </div>
        ) : (
          <div>
            {root.folders.map((folder) => (
              <FolderRow key={folder.path} folder={folder} depth={0} />
            ))}
            {root.files.map((file) => (
              <FileRow key={file.id} file={file} depth={0} />
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
