<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\Attributes\Title;
use Livewire\WithFileUploads;
use App\Models\Project;
use App\Models\Folder;
use App\Models\Document;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;

class ProjectShow extends Component
{

    use WithFileUploads;

    protected $middleware = ['auth']; // Añade esto

    public Project $project;
    public ?Folder $currentFolder = null;
    public $expandedFolders = [];
    public $files = [];
    public $folderName = '';

    public $selectedFolderId = null;
    public $showFolderModal = false;
    public $showUploadModal = false;
    public $tempFiles = [];
    public $selectedFiles = []; // Archivos temporales en el modal
    public $uploadProgress = [];

    
    public function mount(Project $project)
    {
        $this->project = $project->load('rootFolders');
        $this->currentFolder = $this->project->rootFolders->first() ?? null;
    }

    public function selectFolder($folderId)
    {
        $this->selectedFolderId = $folderId;
        $this->currentFolder = Folder::with('children')->find($folderId);
    }

    public function toggleFolder($folderId): void
    {
        if (in_array($folderId, $this->expandedFolders)) {
            $this->expandedFolders = array_diff($this->expandedFolders, [$folderId]);
        } else {
            $this->expandedFolders[] = $folderId;
        }
    }

    public function createFolder(): void
    {
        $this->validate([
            'folderName' => [
                'required',
                'max:255',
                Rule::unique('folders', 'name')->where(function ($query) {
                    return $query->where('project_id', $this->project->id)
                        ->where('parent_id', $this->currentFolder?->id);
                })
            ]
        ]);
        Folder::create([
            'name' => $this->folderName,
            'project_id' => $this->project->id,
            'parent_id' => $this->currentFolder?->id,
        ]);

        $this->hideCreateFolderModal();
        $this->reset('folderName');
        $this->project->load('rootFolders');        // Recargar carpetas raíz
        if ($this->currentFolder) {
            $this->currentFolder->load('children'); // Recargar hijos si está en una subcarpeta
        }
        $this->project->refresh();
    }

    /*public function uploadFiles(): void
    {
        $this->validate([
            'files.*' => 'file|max:10240|mimes:pdf,docx,xlsx,jpg,png'
        ]);
        dd($this->files);
        foreach ($this->files as $file) {
            Document::create([
                'name' => $file->getClientOriginalName(),
                'file_path' => $file->store("projects/{$this->project->id}/documents"),
                'project_id' => $this->project->id,
                'folder_id' => $this->currentFolder?->id
            ]);
        }

        $this->reset('files');
        if ($this->currentFolder) {
            $this->currentFolder->refresh(); // Recargar documentos
        }
        $this->reset('files');
    }*/

    public function getDocumentsProperty()
    {
        return $this->currentFolder
            ? $this->currentFolder->documents()->with('versions')->get()
            : Document::whereNull('folder_id')->where('project_id', $this->project->id)->with('versions')->get();
    }

    public function getBreadcrumbsProperty()
    {
        if (!$this->currentFolder) return collect();

        $breadcrumbs = collect();
        $folder = $this->currentFolder;

        while ($folder) {
            $breadcrumbs->prepend($folder);
            $folder = $folder->parent;
        }

        return $breadcrumbs;
    }

    public function showCreateFolderModal()
    {
        $this->folderName = '';
        $this->showFolderModal = true;
    }

    public function hideCreateFolderModal()
    {
        $this->showFolderModal = false;
    }

    // Método para abrir el modal
    public function openUploadModal(): void
    {
        $this->showUploadModal = true;
    }

    // Método para manejar archivos seleccionados
    public function selectFiles($files): void
    {
        $this->validate([
            'selectedFiles.*' => 'file|max:10240|mimes:pdf,docx,xlsx,jpg,png'
        ]);
        
        $this->selectedFiles = array_merge($this->selectedFiles, $files);
    }

    // Método para eliminar un archivo de la lista
    public function removeFile($index): void
    {
        unset($this->selectedFiles[$index]);
        $this->selectedFiles = array_values($this->selectedFiles); // Reindexar array
    }

    // Método para confirmar y guardar
    public function uploadFiles(): void
    {
        foreach ($this->selectedFiles as $file) {
            Document::create([
                'name' => $file->getClientOriginalName(),
                'file_path' => $file->store("projects/{$this->project->id}/documents"),
                'project_id' => $this->project->id, // Asegurar que se envía
                'folder_id' => $this->currentFolder?->id,
                //'user_id' => Auth::id(),
                //'status' => 'active' // Añadir si tu modelo lo requiere
            ]);
        }
    
        $this->resetUpload();
        $this->project->refresh();
    }

    // Método para procesar los archivos
    protected function processFiles(): void
    {
        foreach ($this->files as $file) {
            Document::create([
                'name' => $file->getClientOriginalName(),
                'file_path' => $file->store("projects/{$this->project->id}/documents"),
                'project_id' => $this->project->id, // Asegurar que se envía
                'folder_id' => $this->currentFolder?->id,
                //'user_id' => Auth::id(),
                //'status' => 'active' // Añadir si tu modelo lo requiere
            ]);
        }
    }

    // Método para resetear
    public function resetUpload(): void
    {
        $this->reset(['selectedFiles', 'showUploadModal', 'uploadProgress']);
    }

    #[On('upload-progress')]
    public function updateProgress($name, $progress)
    {
        $this->uploadProgress[$name] = $progress;
    }

    public function addFiles($files)
    {
        $this->validate([
            'selectedFiles.*' => 'file|max:10240|mimes:pdf,docx,xlsx,jpg,png'
        ]);
        
        $this->selectedFiles = array_merge($this->selectedFiles, $files);
    }

    public function startUpload()
    {
        foreach ($this->selectedFiles as $file) {
            try {
                $path = $file->store(
                    "projects/{$this->project->id}/".($this->currentFolder ? "folders/{$this->currentFolder->id}" : ""),
                    'public'
                );
                
                Document::create([
                    'name' => $file->getClientOriginalName(),
                    'file_path' => $path,
                    'project_id' => $this->project->id,
                    'folder_id' => $this->currentFolder?->id,
                    'user_id' => Auth::id()
                ]);
                
            } catch (\Exception $e) {
                $this->addError('upload', "Error subiendo {$file->getClientOriginalName()}: {$e->getMessage()}");
            }
        }
        
        $this->resetUpload();
        $this->project->refresh();
    }

    public function render()
    {
        return view('livewire.project.show');
    }
}
