// src/App.tsx
import React, { useState, ChangeEvent } from "react";
import { FolderTree, Download, AlertCircle, CheckCircle } from "lucide-react";
import FolderTreeView from "./FolderTreeView";
import { TreeNode } from "./types";

function App() {
  const [folderStructure, setFolderStructure] = useState<string>("");
  const [treeData, setTreeData] = useState<TreeNode[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>("");

  const handleFolderSelect = async (event: ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    console.log(`Número de archivos seleccionados: ${files?.length}`); // Depuración

    if (files && files.length > 0) {
      // Opcional: Listar los archivos seleccionados en consola
      for (let i = 0; i < files.length; i++) {
        console.log(`Archivo ${i + 1}: ${files[i].webkitRelativePath}`);
      }

      setIsLoading(true);
      setError("");
      try {
        const { tree, structure, treeNodes } = await listFolderContents(files);
        setFolderStructure(structure);
        setTreeData(treeNodes);
        downloadTextFile(structure, "folder_structure.txt");
      } catch (err) {
        console.error(err); // Depuración adicional
        setError("Ocurrió un error al procesar los archivos.");
      } finally {
        setIsLoading(false);
      }
    }
  };

  const listFolderContents = async (
    fileList: FileList
  ): Promise<{ tree: string; structure: string; treeNodes: TreeNode[] }> => {
    let treeStructure = "Folder Structure:\n\n";
    const files = Array.from(fileList);
    const folderMap = new Map<string, string[]>();
    const fileContentMap = new Map<string, string>(); // Mapa para contenido de archivos

    // Construir el mapa de carpetas y leer contenido de archivos
    for (const file of files) {
      const relativePath = file.webkitRelativePath || file.name;
      const parts = relativePath.split("/");

      // Si solo hay un archivo en la raíz
      if (parts.length === 1) {
        const folderPath = "";
        const fileName = parts[0];
        if (!folderMap.has(folderPath)) {
          folderMap.set(folderPath, []);
        }
        folderMap.get(folderPath)!.push(fileName);

        // Leer el contenido del archivo
        const content = await readFileContent(file);
        fileContentMap.set(fileName, content);
      } else {
        const folderPath = parts.slice(0, -1).join("/");
        const fileName = parts[parts.length - 1];

        if (!folderMap.has(folderPath)) {
          folderMap.set(folderPath, []);
        }
        folderMap.get(folderPath)!.push(fileName);

        // Leer el contenido del archivo
        const content = await readFileContent(file);
        fileContentMap.set(relativePath, content);
      }
    }

    console.log("Mapa de Carpetas:", Array.from(folderMap.entries())); // Depuración

    // Función recursiva para generar la estructura del árbol como texto
    const generateTreeText = (path: string, depth: number): string => {
      let treeStr = "";
      const prefix = "│  ".repeat(depth);
      const filesInPath = folderMap.get(path) || [];

      for (let i = 0; i < filesInPath.length; i++) {
        const isLast = i === filesInPath.length - 1;
        const connector = isLast ? "└─ " : "├─ ";
        const fileName = filesInPath[i];
        const fullPath = path ? `${path}/${fileName}` : fileName;

        treeStr += `${prefix}${connector}${fileName}\n`;

        if (folderMap.has(fullPath)) {
          treeStr += generateTreeText(fullPath, depth + 1);
        }
      }

      return treeStr;
    };

    // Identificar las carpetas raíz (paths que no tienen un "/")
    const roots: string[] = [];
    for (const path of folderMap.keys()) {
      if (!path.includes("/")) {
        roots.push(path);
      }
    }

    console.log("Carpetas Raíz:", roots); // Depuración

    // Generar la estructura del árbol como texto y como objeto
    let treeNodes: TreeNode[] = [];

    const generateTreeNodes = (path: string): TreeNode => {
      const nodeName = path;
      const childrenNames = folderMap.get(path) || [];
      const children: TreeNode[] = [];

      for (const childName of childrenNames) {
        const fullPath = path ? `${path}/${childName}` : childName;
        if (folderMap.has(fullPath)) {
          children.push(generateTreeNodes(fullPath));
        } else {
          children.push({
            name: childName,
            type: "file",
            content:
              fileContentMap.get(fullPath) || fileContentMap.get(childName),
          });
        }
      }

      return {
        name: nodeName,
        type: "folder",
        children: children,
      };
    };

    // Agregar raíces a treeNodes y generar el texto del árbol
    for (let i = 0; i < roots.length; i++) {
      const root = roots[i];
      treeNodes.push(generateTreeNodes(root));
      treeStructure += generateTreeText(root, 0);
    }

    return { tree: treeStructure, structure: treeStructure, treeNodes };
  };

  const readFileContent = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target) {
          const content = event.target.result as string;
          resolve(content);
        }
      };
      reader.onerror = (error) => reject(error);
      reader.readAsText(file);
    });
  };

  const downloadTextFile = (content: string, fileName: string) => {
    const element = document.createElement("a");
    const file = new Blob([content], { type: "text/plain" });
    element.href = URL.createObjectURL(file);
    element.download = fileName;
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  };

  return (
    <div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center p-4">
      <h1 className="text-3xl font-bold mb-6">
        Estructura de Carpetas y Visualización
      </h1>
      <div className="bg-white p-8 rounded-lg shadow-md w-full max-w-2xl">
        {/* Botón de Selección de Carpeta */}
        <label
          htmlFor="folder-input"
          className="flex items-center justify-center w-full px-4 py-2 bg-blue-500 text-white rounded-lg cursor-pointer hover:bg-blue-600 transition-colors"
        >
          <FolderTree className="mr-2" />
          Seleccionar Carpeta
        </label>
        <input
          id="folder-input"
          type="file"
          webkitdirectory="true"
          directory=""
          className="hidden"
          onChange={handleFolderSelect}
        />

        {/* Indicador de Carga */}
        {isLoading && (
          <div className="flex items-center mt-6">
            <svg
              className="animate-spin -ml-1 mr-3 h-5 w-5 text-blue-500"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              ></circle>
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8v8H4z"
              ></path>
            </svg>
            <span className="text-gray-700">Procesando...</span>
          </div>
        )}

        {/* Mensaje de Error */}
        {error && (
          <div className="flex items-center mt-6 text-red-600">
            <AlertCircle className="mr-2 w-5 h-5" />
            <span>{error}</span>
          </div>
        )}

        {/* Resultados */}
        {folderStructure && !isLoading && !error && (
          <div className="mt-6">
            {/* Estructura de Carpeta como Texto */}
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-2xl font-semibold text-gray-800">
                Estructura de la Carpeta
              </h2>
              <button
                onClick={() =>
                  downloadTextFile(folderStructure, "folder_structure.txt")
                }
                className="flex items-center px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
              >
                <Download className="mr-2 w-5 h-5" />
                Descargar
              </button>
            </div>
            <div className="bg-gray-50 p-4 rounded-md shadow-inner overflow-x-auto mb-6">
              <pre className="whitespace-pre-wrap font-mono text-sm text-gray-800">
                {folderStructure}
              </pre>
            </div>

            {/* Visualización Gráfica del Árbol */}
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-2xl font-semibold text-gray-800">
                Visualización de la Carpeta
              </h2>
            </div>
            <div className="bg-gray-50 p-4 rounded-md shadow-inner overflow-x-auto">
              {treeData.map((node, index) => (
                <FolderTreeView key={index} node={node} />
              ))}
            </div>

            <div className="flex items-center mt-4 text-green-600">
              <CheckCircle className="mr-2 w-5 h-5" />
              <span>¡Estructura generada y descargada exitosamente!</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default App;


tengo eso, pero necesito que en mi txt se vea reflejado tambien los archivos que están en la carpeta