import type { PermTreeNode } from '@common/services/authApi';
import type { PermState, OperCode } from '../PermissionsPanel';
import { OPER_CODES, OPER_FULL_LABELS, makeKey } from '../PermissionsPanel';
import { PermCell } from './PermCell';

interface TreeRowProps {
  node: PermTreeNode;
  stateMap: Map<string, PermState>;
  expanded: Set<string>;
  onToggleExpand: (code: string) => void;
  onTogglePerm: (code: string, oper: OperCode, currentState: PermState) => void;
  readOnly?: boolean;
}

export function TreeRow({
  node,
  stateMap,
  expanded,
  onToggleExpand,
  onTogglePerm,
  readOnly = false,
}: TreeRowProps) {
  const hasChildren = node.children.length > 0;
  const isExpanded = expanded.has(node.code);
  const indent = node.level * 16;

  // 이 노드의 READ 상태 (CUD 비활성 판단용)
  const readState = stateMap.get(makeKey(node.code, 'READ')) ?? 'forced-denied';
  const readDenied = readState === 'explicit-denied' || readState === 'forced-denied';

  return (
    <>
      <tr className="border-b border-stroke hover:bg-[rgba(6,182,212,0.04)] transition-colors">
        <td className="px-3 py-1">
          <div className="flex items-center" style={{ paddingLeft: indent }}>
            {hasChildren ? (
              <button
                onClick={() => onToggleExpand(node.code)}
                className="w-4 h-4 flex items-center justify-center text-fg-disabled hover:text-fg transition-colors mr-1 flex-shrink-0"
              >
                <svg
                  width="10"
                  height="10"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2.5"
                  className={`transition-transform ${isExpanded ? 'rotate-90' : ''}`}
                >
                  <polyline points="9 18 15 12 9 6" />
                </svg>
              </button>
            ) : (
              <span className="w-4 mr-1 flex-shrink-0 text-center text-fg-disabled text-caption">
                {node.level > 0 ? '├' : ''}
              </span>
            )}
            {node.icon && <span className="mr-1 flex-shrink-0 text-label-2">{node.icon}</span>}
            <div className="min-w-0">
              <div
                className={`text-label-2 font-korean truncate ${node.level === 0 ? 'font-bold text-fg' : 'font-medium text-fg-sub'}`}
              >
                {node.name}
              </div>
            </div>
          </div>
        </td>
        {OPER_CODES.map((oper) => {
          const key = makeKey(node.code, oper);
          const state = stateMap.get(key) ?? 'forced-denied';
          // READ 거부 시 CUD도 강제 거부
          const effectiveState =
            oper !== 'READ' && readDenied ? ('forced-denied' as PermState) : state;
          return (
            <td key={oper} className="px-1 py-1 text-center">
              <div className="flex justify-center">
                <PermCell
                  state={effectiveState}
                  label={OPER_FULL_LABELS[oper]}
                  onToggle={() => onTogglePerm(node.code, oper, effectiveState)}
                  readOnly={readOnly}
                />
              </div>
            </td>
          );
        })}
      </tr>
      {hasChildren &&
        isExpanded &&
        node.children.map((child: PermTreeNode) => (
          <TreeRow
            key={child.code}
            node={child}
            stateMap={stateMap}
            expanded={expanded}
            onToggleExpand={onToggleExpand}
            onTogglePerm={onTogglePerm}
            readOnly={readOnly}
          />
        ))}
    </>
  );
}
