import { useMemo, useState } from 'react';
import { FileJson, FolderTree } from 'lucide-react';
import { cn } from '@ump/shared';
import type { PlannedFile } from '../../domain/nnunet/core';

interface TreeNode {
  name: string;
  children: Map<string, TreeNode>;
  file: boolean;
}

/** Live right-rail: the resolved nnU-Net folder tree + the generated dataset.json. */
export function OutputPane({
  folderName,
  plan,
  datasetJson,
  trainCount,
  testCount,
  channels,
  labels,
  dim,
  rgb,
}: {
  folderName: string;
  plan: PlannedFile[];
  datasetJson: Record<string, unknown>;
  trainCount: number;
  testCount: number;
  channels: number;
  labels: number;
  dim: '2d' | '3d';
  rgb: boolean;
}) {
  const [tab, setTab] = useState<'tree' | 'json'>('tree');
  const jsonText = JSON.stringify(datasetJson, null, 2);

  const tree = useMemo<TreeNode>(() => {
    const root: TreeNode = { name: `${folderName}/`, children: new Map(), file: false };
    const add = (path: string) => {
      const parts = path.split('/').slice(1);
      let node = root;
      parts.forEach((p, i) => {
        const isFile = i === parts.length - 1;
        if (!node.children.has(p)) node.children.set(p, { name: p, children: new Map(), file: isFile });
        node = node.children.get(p)!;
      });
    };
    add(`${folderName}/dataset.json`);
    plan.forEach((p) => add(p.targetPath));
    return root;
  }, [folderName, plan]);

  const tabs: Array<['tree' | 'json', string, typeof FolderTree]> = [
    ['tree', 'Thư mục', FolderTree],
    ['json', 'dataset.json', FileJson],
  ];

  return (
    <aside className="flex h-fit flex-col self-start overflow-hidden rounded-xl border border-border bg-card lg:sticky lg:top-4">
      <div className="flex items-center gap-1 border-b border-border px-2 pt-2">
        {tabs.map(([k, label, Icon]) => (
          <button
            key={k}
            type="button"
            onClick={() => setTab(k)}
            className={cn(
              'flex items-center gap-1.5 rounded-t-lg px-3 py-1.5 text-xs font-medium transition',
              tab === k ? 'bg-muted text-foreground' : 'text-muted-foreground hover:text-foreground',
            )}
          >
            <Icon className="h-3.5 w-3.5" /> {label}
          </button>
        ))}
      </div>
      <div className="flex flex-wrap items-center gap-x-4 gap-y-1 bg-muted/40 px-3 py-1.5 font-mono text-[11px] text-muted-foreground">
        <span className="text-accent">{dim}{rgb ? ' rgb' : ''}</span>
        <span>{channels} kênh</span>
        <span>{labels} nhãn</span>
        <span className="text-primary">{trainCount} Tr</span>
        <span>{testCount} Ts</span>
      </div>
      <div className="max-h-[60vh] overflow-auto p-3 text-[12px] leading-relaxed">
        {tab === 'tree' ? (
          <TreeView node={tree} depth={0} />
        ) : (
          <pre className="whitespace-pre font-mono text-foreground">{jsonText}</pre>
        )}
      </div>
    </aside>
  );
}

function TreeView({ node, depth }: { node: TreeNode; depth: number }) {
  const children = [...node.children.values()].sort(
    (a, b) => Number(a.file) - Number(b.file) || a.name.localeCompare(b.name),
  );
  return (
    <div>
      <div className="whitespace-pre font-mono" style={{ paddingLeft: depth * 12 }}>
        <span className={node.file ? 'text-muted-foreground' : 'text-primary'}>
          {node.file ? '' : '▸ '}
          {node.name}
        </span>
      </div>
      {children.map((c, i) => (
        <TreeView key={i} node={c} depth={depth + 1} />
      ))}
    </div>
  );
}

export default OutputPane;
