import { Box, Text, Tree, Group, ActionIcon, Modal, TextInput, Button } from '@mantine/core';
import { IconFolder, IconFile, IconPlus, IconTrash, IconEdit } from '@tabler/icons-react';
import { useState } from 'react';
import { useDisclosure } from '@mantine/hooks';

interface FileNode {
  value: string;
  label: string;
  children?: FileNode[];
  type: 'file' | 'folder';
}

interface FileExplorerDockProps {
  onFileSelect?: (file: FileNode) => void;
}

export function FileExplorerDock({ onFileSelect }: FileExplorerDockProps) {
  const [opened, { open, close }] = useDisclosure(false);
  const [newItemName, setNewItemName] = useState('');
  const [newItemType, setNewItemType] = useState<'file' | 'folder'>('file');
  const [selectedNode, setSelectedNode] = useState<string>('');

  const [treeData, setTreeData] = useState<FileNode[]>([
    {
      value: 'src',
      label: 'src',
      type: 'folder',
      children: [
        {
          value: 'src/components',
          label: 'components',
          type: 'folder',
          children: [
            { value: 'src/components/App.tsx', label: 'App.tsx', type: 'file' },
            { value: 'src/components/Header.tsx', label: 'Header.tsx', type: 'file' },
          ]
        },
        {
          value: 'src/pages',
          label: 'pages',
          type: 'folder',
          children: [
            { value: 'src/pages/Home.tsx', label: 'Home.tsx', type: 'file' },
            { value: 'src/pages/About.tsx', label: 'About.tsx', type: 'file' },
          ]
        },
        { value: 'src/index.tsx', label: 'index.tsx', type: 'file' },
      ]
    },
    {
      value: 'public',
      label: 'public',
      type: 'folder',
      children: [
        { value: 'public/index.html', label: 'index.html', type: 'file' },
        { value: 'public/favicon.ico', label: 'favicon.ico', type: 'file' },
      ]
    },
    { value: 'package.json', label: 'package.json', type: 'file' },
    { value: 'README.md', label: 'README.md', type: 'file' },
  ]);

  const renderTreeLabel = (node: FileNode) => (
    <Group gap="xs">
      {node.type === 'folder' ? <IconFolder size={16} /> : <IconFile size={16} />}
      <Text size="sm">{node.label}</Text>
    </Group>
  );

  const handleNodeSelect = (value: string) => {
    setSelectedNode(value);
    const findNode = (nodes: FileNode[], value: string): FileNode | null => {
      for (const node of nodes) {
        if (node.value === value) {return node;}
        if (node.children) {
          const found = findNode(node.children, value);
          if (found) {return found;}
        }
      }
      return null;
    };

    const node = findNode(treeData, value);
    if (node) {
      onFileSelect?.(node);
    }
  };

  const addNewItem = () => {
    if (!newItemName.trim()) {return;}

    const newItem: FileNode = {
      value: `new-${Date.now()}`,
      label: newItemName,
      type: newItemType,
      children: newItemType === 'folder' ? [] : undefined,
    };

    setTreeData(prev => [...prev, newItem]);
    setNewItemName('');
    close();
  };

  const deleteSelectedItem = () => {
    if (!selectedNode) {return;}

    const removeNode = (nodes: FileNode[]): FileNode[] => {
      return nodes.filter(node => {
        if (node.value === selectedNode) {return false;}
        if (node.children) {
          node.children = removeNode(node.children);
        }
        return true;
      });
    };

    setTreeData(removeNode(treeData));
    setSelectedNode('');
  };

  return (
    <Box p="md" h="100%">
      <Group justify="space-between" mb="md">
        <Text size="lg" fw={600}>Explorador de Archivos</Text>
        <Group gap="xs">
          <ActionIcon
            onClick={() => { setNewItemType('file'); open(); }}
            variant="light"
            size="sm"
          >
            <IconPlus size={14} />
          </ActionIcon>
          <ActionIcon
            onClick={() => { setNewItemType('folder'); open(); }}
            variant="light"
            size="sm"
          >
            <IconFolder size={14} />
          </ActionIcon>
          <ActionIcon
            onClick={deleteSelectedItem}
            variant="light"
            color="red"
            size="sm"
            disabled={!selectedNode}
          >
            <IconTrash size={14} />
          </ActionIcon>
        </Group>
      </Group>

      <Box h="calc(100% - 60px)" style={{ overflow: 'auto' }}>
        <Tree
          data={treeData}
          renderNode={({ node, expanded, hasChildren, elementProps }) => (
            <Box {...elementProps} onClick={() => handleNodeSelect(node.value)}>
              {renderTreeLabel(node as FileNode)}
            </Box>
          )}
        />
      </Box>

      <Modal opened={opened} onClose={close} title={`Crear ${newItemType === 'file' ? 'archivo' : 'carpeta'}`}>
        <TextInput
          label={`Nombre del ${newItemType === 'file' ? 'archivo' : 'carpeta'}`}
          value={newItemName}
          onChange={(e) => setNewItemName(e.target.value)}
          placeholder={`Ingresa el nombre del ${newItemType === 'file' ? 'archivo' : 'carpeta'}`}
        />
        <Group justify="flex-end" mt="md">
          <Button variant="outline" onClick={close}>Cancelar</Button>
          <Button onClick={addNewItem}>Crear</Button>
        </Group>
      </Modal>
    </Box>
  );
}