/**
 * Folder tree sidebar for DMS file browser.
 * Renders a hierarchical tree of folders with expand/collapse and selection.
 */

import React, { useState } from 'react';
import clsx from 'clsx';
import { useTranslation } from 'react-i18next';
import type { DmsFolder } from '@/api/dms';
import { ChevronDown, Folder, Menu } from 'lucide-react';

interface FolderTreeItemProps {
  folder: DmsFolder;
  level: number;
  selectedFolderId: string | null;
  onSelect: (folderId: string | null) => void;
}

function FolderTreeItem({ folder, level, selectedFolderId, onSelect }: FolderTreeItemProps) {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState(true);
  const hasChildren = folder.children && folder.children.length > 0;
  const isSelected = selectedFolderId === folder.id;

  return (
    <li role="treeitem" aria-expanded={hasChildren ? expanded : undefined} aria-selected={isSelected}>
      <div
        className={clsx(
          'flex items-center gap-1 px-2 py-0.5 rounded-md text-sm cursor-pointer',
          'hover:bg-secondary-100 motion-safe:transition-colors',
          'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500',
          isSelected && 'bg-primary-50 text-primary-700 font-medium'
        )}
        style={{ paddingLeft: `${level * 12 + 8}px` }}
        onClick={() => onSelect(folder.id)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            onSelect(folder.id);
          }
        }}
        tabIndex={0}
        role="button"
        aria-label={folder.name}
      >
        {hasChildren && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              setExpanded((prev) => !prev);
            }}
            className="flex-shrink-0 w-4 h-4 flex items-center justify-center text-secondary-400 hover:text-secondary-600"
            aria-label={expanded ? t('dms.folders') : t('dms.folders')}
          >
            <ChevronDown className="w-3 h-3 transition-transform" aria-hidden="true" strokeWidth={2} />
          </button>
        )}
        {!hasChildren && <span className="w-4 flex-shrink-0" aria-hidden="true" />}
        <Folder className="w-4 h-4 text-warning-500 flex-shrink-0" aria-hidden="true" strokeWidth={2} />
        <span className="truncate">{folder.name}</span>
        {typeof folder.file_count === 'number' && folder.file_count > 0 && (
          <span className="ml-auto text-xs text-secondary-400">{folder.file_count}</span>
        )}
      </div>
      {hasChildren && expanded && (
        <ul role="group" className="space-y-0">
          {folder.children!.map((child) => (
            <FolderTreeItem
              key={child.id}
              folder={child}
              level={level + 1}
              selectedFolderId={selectedFolderId}
              onSelect={onSelect}
            />
          ))}
        </ul>
      )}
    </li>
  );
}

export interface FolderTreeProps {
  folders: DmsFolder[];
  selectedFolderId: string | null;
  onSelect: (folderId: string | null) => void;
  loading?: boolean;
}

export function FolderTree({ folders, selectedFolderId, onSelect, loading = false }: FolderTreeProps) {
  const { t } = useTranslation();

  if (loading) {
    return (
      <div className="space-y-2 p-2" data-testid="folder-tree-loading">
        {[1, 2, 3].map((i) => (
          <div key={i} className="h-8 bg-secondary-100 rounded animate-pulse" />
        ))}
      </div>
    );
  }

  return (
    <nav aria-label={t('dms.folders')} data-testid="folder-tree">
      <ul role="tree" className="space-y-0">
        <li role="treeitem" aria-selected={selectedFolderId === null}>
          <div
            className={clsx(
              'flex items-center gap-2 px-2 py-0.5 rounded-md text-sm cursor-pointer',
              'hover:bg-secondary-100 motion-safe:transition-colors',
              'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500',
              selectedFolderId === null && 'bg-primary-50 text-primary-700 font-medium'
            )}
            onClick={() => onSelect(null)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                onSelect(null);
              }
            }}
            tabIndex={0}
            role="button"
            aria-label={t('dms.allFiles')}
          >
            <Menu className="w-4 h-4 text-secondary-400" aria-hidden="true" strokeWidth={2} />
            <span>{t('dms.allFiles')}</span>
          </div>
        </li>
        {folders.map((folder) => (
          <FolderTreeItem
            key={folder.id}
            folder={folder}
            level={0}
            selectedFolderId={selectedFolderId}
            onSelect={onSelect}
          />
        ))}
      </ul>
    </nav>
  );
}
