import React, { useState, useCallback } from 'react';
import { cn } from "@/lib/utils";
import EditableInput from '../shared/EditableInput';

const LayoutTreeGrid = ({ root, options = [], onUpdate }) => {
  const [expandedNodes, setExpandedNodes] = useState(new Set());

  // Helper function to get node path
  const getNodePath = useCallback((node, targetId, path = '') => {
    if (node.id === targetId) {
      return path;
    }

    if (node.children) {
      for (let i = 0; i < node.children.length; i++) {
        const currentPath = path ? `${path}.children[${i}]` : `children[${i}]`;
        const resultPath = getNodePath(node.children[i], targetId, currentPath);
        if (resultPath) {
          return resultPath;
        }
      }
    }
    return null;
  }, []);

  // Get indentation for tree structure
  const getIndent = useCallback((depth) => {
    return Array(depth + 1).join('  ');
  }, []);

  // Handle expand/collapse
  const handleExpanderClick = useCallback((nodeId) => {
    setExpandedNodes(prev => {
      const newSet = new Set(prev);
      if (newSet.has(nodeId)) {
        newSet.delete(nodeId);
      } else {
        newSet.add(nodeId);
      }
      return newSet;
    });
  }, []);

  // Render cell content
  const renderCell = useCallback((node, field, depth) => {
    const nodePath = getNodePath(root, node.id) + '.value';

    if (node.loutItemType === 'Field' && field.type === 'textfield') {
      return (
          <EditableInput
              name={field.name}
              value={node[field.name]}
              path={nodePath}
              onChange={(value) => {
                node[field.name] = value;
                onUpdate?.(root);
              }}
          />
      );
    }

    if (field.isFirst) {
      const hasChildren = node.children?.length > 0;
      return (
          <div className="flex items-center">
            <span className="inline-block" style={{ width: `${depth * 20}px` }} />
            {hasChildren && (
                <button
                    onClick={() => handleExpanderClick(node.id)}
                    className="w-4 h-4 flex items-center justify-center mr-1"
                >
                  {expandedNodes.has(node.id) ? '−' : '+'}
                </button>
            )}
            <span>{node[field.name]}</span>
          </div>
      );
    }

    return node[field.name];
  }, [root, expandedNodes, handleExpanderClick, getNodePath, onUpdate]);

  // Recursive function to render tree rows
  const renderTreeRows = useCallback((node, depth = 0, parentId = null) => {
    const rows = [];

    const isVisible = depth === 0 || !parentId || expandedNodes.has(parentId);

    if (!isVisible) {
      return rows;
    }

    const row = (
        <tr
            key={node.id}
            className={cn(
                "layout-grid-row",
                depth === 0 && "hidden",
                parentId && `treegrid-parent-${parentId}`
            )}
            data-node-id={node.id}
        >
          {options.map((field, fieldIndex) => (
              <td
                  key={fieldIndex}
                  className={cn(
                      "border p-2",
                      field.align && `text-${field.align}`,
                      "whitespace-nowrap"
                  )}
                  style={{ width: field.width }}
              >
                {renderCell(node, field, depth)}
              </td>
          ))}
        </tr>
    );

    rows.push(row);

    if (node.children?.length > 0) {
      node.children.forEach(child => {
        rows.push(...renderTreeRows(child, depth + 1, node.id));
      });
    }

    return rows;
  }, [options, expandedNodes, renderCell]);

  return (
      <div className="overflow-auto">
        <table className="w-full border-collapse border">
          <thead>
          <tr>
            {options.map((field, index) => (
                <th
                    key={index}
                    className={cn(
                        "border p-2",
                        field.align && `text-${field.align}`,
                        "whitespace-nowrap"
                    )}
                    style={{ width: field.width }}
                >
                  {field.label}
                </th>
            ))}
          </tr>
          </thead>
          <tbody>
          {renderTreeRows(root)}
          </tbody>
        </table>
      </div>
  );
};

export default LayoutTreeGrid;
