'use client';

import { Group, Text, Box } from '@tidbcloud/uikit';
import { WorkspaceFile } from '@/lib/workspace';

interface FileTreeProps {
  files: WorkspaceFile[];
  selectedPath: string | null;
  onFileClick: (path: string) => void;
  /** Directory paths that are expanded (controlled). */
  expandedDirPaths: Set<string>;
  onToggleDir: (path: string) => void;
  level?: number;
}

function getFileIcon(file: WorkspaceFile): string {
  if (file.type === 'directory') return '';
  const ext = file.name.split('.').pop()?.toLowerCase();
  switch (ext) {
    case 'json': return '📄';
    case 'png':
    case 'jpg':
    case 'svg': return '🖼️';
    case 'md': return '📝';
    case 'yaml':
    case 'yml': return '⚙️';
    case 'lock': return '🔒';
    default: return '📄';
  }
}

function FileTreeItem({
  file,
  selectedPath,
  onFileClick,
  expandedDirPaths,
  onToggleDir,
  level = 0,
}: {
  file: WorkspaceFile;
  selectedPath: string | null;
  onFileClick: (path: string) => void;
  expandedDirPaths: Set<string>;
  onToggleDir: (path: string) => void;
  level: number;
}) {
  const expanded = file.type === 'directory' && expandedDirPaths.has(file.path);
  const isDir = file.type === 'directory';
  const isSelected = !isDir && selectedPath === file.path;

  return (
    <>
      <Box
        py={3}
        onClick={() => {
          if (isDir) {
            onToggleDir(file.path);
          } else {
            onFileClick(file.path);
          }
        }}
        style={{
          paddingInlineStart: `${8 + level * 12}px`,
          paddingInlineEnd: '8px',
          cursor: 'pointer',
          borderRadius: '4px',
          backgroundColor: isSelected ? '#e8f0fe' : 'transparent',
          userSelect: 'none',
        }}
        onMouseEnter={(e: React.MouseEvent<HTMLDivElement>) => {
          if (!isSelected) (e.currentTarget as HTMLDivElement).style.backgroundColor = '#f3f4f6';
        }}
        onMouseLeave={(e: React.MouseEvent<HTMLDivElement>) => {
          if (!isSelected) (e.currentTarget as HTMLDivElement).style.backgroundColor = 'transparent';
        }}
      >
        <Group gap={5} align="center" wrap="nowrap">
          {isDir ? (
            <span
              style={{
                fontSize: '10px',
                width: '14px',
                textAlign: 'center',
                flexShrink: 0,
                color: '#6b7280',
                transition: 'transform 0.12s ease',
                display: 'inline-block',
                transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)',
              }}
            >
              ▶
            </span>
          ) : (
            <span style={{ fontSize: '12px', width: '14px', textAlign: 'center', flexShrink: 0 }}>
              {getFileIcon(file)}
            </span>
          )}
          {isDir && (
            <span style={{ fontSize: '12px', flexShrink: 0 }}>
              {expanded ? '📂' : '📁'}
            </span>
          )}
          <Text
            size="sm"
            fw={isDir ? 500 : 400}
            style={{
              fontFamily: 'monospace',
              fontSize: '12px',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              minWidth: 0,
              flex: 1,
              color: isSelected ? '#1d4ed8' : isDir ? '#374151' : '#4b5563',
            }}
          >
            {file.name}
          </Text>
          {!isDir && file.size && (
            <Text size="xs" c="carbon.5" style={{ flexShrink: 0, fontSize: '10px' }}>
              {file.size}
            </Text>
          )}
        </Group>
      </Box>
      {isDir && expanded && file.children && (
        <div>
          {file.children.map(child => (
            <FileTreeItem
              key={child.path}
              file={child}
              selectedPath={selectedPath}
              onFileClick={onFileClick}
              expandedDirPaths={expandedDirPaths}
              onToggleDir={onToggleDir}
              level={level + 1}
            />
          ))}
        </div>
      )}
    </>
  );
}

export default function FileTree({
  files,
  selectedPath,
  onFileClick,
  expandedDirPaths,
  onToggleDir,
  level = 0,
}: FileTreeProps) {
  return (
    <div>
      {files.map(file => (
        <FileTreeItem
          key={file.path}
          file={file}
          selectedPath={selectedPath}
          onFileClick={onFileClick}
          expandedDirPaths={expandedDirPaths}
          onToggleDir={onToggleDir}
          level={level}
        />
      ))}
    </div>
  );
}

/** Collect all directory paths present in the tree (for pruning stale expansion state). */
export function collectDirectoryPaths(files: WorkspaceFile[]): Set<string> {
  const out = new Set<string>();
  const walk = (nodes: WorkspaceFile[]) => {
    for (const n of nodes) {
      if (n.type === 'directory') {
        out.add(n.path);
        if (n.children?.length) walk(n.children);
      }
    }
  };
  walk(files);
  return out;
}
