<?php
// app/Livewire/FileView.php
namespace App\Livewire;

use App\Models\File;
use App\Models\FileAttachment;
use App\Models\FileStage;
use App\Models\Stage;
use App\Models\AttachmentType;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class FileView extends Component
{
    use WithFileUploads;

    public $file;
    public $fileId;
    
    // Attachment properties
    public $attachments;
    public $doc_name = '';
    public $upload;
    public $attachment_type_id;
    public $attachmentTypes;
    
    // Stage properties
    public $stages;
    public $stage_id;
    public $stage_comment = '';
    public $stageHistory;
    public $currentStage;
    
    // UI state
    public $activeTab = 'details';
    public $showAttachmentModal = false;
    public $showStageModal = false;
    public $editAttachmentMode = false;
    public $attachmentId;

    protected function rules()
    {
        return [
            'doc_name' => ['required', 'string', 'max:255'],
            'upload' => ['required', 'file', 'max:10240'],
            'attachment_type_id' => ['nullable', 'exists:attachment_types,id'],
        ];
    }

    protected function messages()
    {
        return [
            'doc_name.required' => 'Document name is required.',
            'upload.required' => 'Please select a file to upload.',
            'upload.max' => 'File size cannot exceed 10MB.',
        ];
    }

    public function mount($id)
    {
        $this->fileId = $id;
        $this->loadFile();
        $this->loadAttachments();
        $this->loadStages();
        $this->loadStageHistory();
        $this->loadAttachmentTypes();
    }

    public function loadFile()
    {
        $this->file = File::with(['category', 'user_created', 'user_updated'])->findOrFail($this->fileId);
    }

    public function loadAttachments()
    {
        $this->attachments = FileAttachment::with(['attachmentType', 'createdBy'])
            ->where('file_id', $this->fileId)
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function loadStages()
    {
        $this->stages = Stage::where('active', true)->orderBy('name')->get();
    }

    public function loadStageHistory()
    {
        $this->stageHistory = FileStage::with(['stage', 'createdBy'])
            ->where('file_id', $this->fileId)
            ->orderBy('created_at', 'desc')
            ->get();
        
        $this->currentStage = $this->stageHistory->where('active', true)->first();
    }

    public function loadAttachmentTypes()
    {
        $this->attachmentTypes = AttachmentType::where('active', true)->orderBy('name')->get();
    }

    public function addAttachment()
    {
        $this->validate();

        $filePath = $this->upload->store('attachments/files/' . date('Y/m'), 'public');

        $attachment = new FileAttachment();
        $attachment->file_id = $this->fileId;
        $attachment->doc_name = $this->doc_name;
        $attachment->file_name = $filePath;
        $attachment->doc_type = $this->upload->getMimeType();
        $attachment->doc_size = $this->upload->getSize();
        $attachment->attachment_type_id = $this->attachment_type_id;
        $attachment->active = true;
        $attachment->created_by = Auth::id();
        $attachment->updated_by = Auth::id();
        $attachment->save();

        $this->reset(['doc_name', 'upload', 'attachment_type_id']);
        $this->loadAttachments();
        
        $this->dispatch('close-modal');
        $this->dispatch('show-success', 'Attachment added successfully!');
    }

    public function deleteAttachment($id)
    {
        $attachment = FileAttachment::findOrFail($id);
        
        if ($attachment->file_name) {
            Storage::disk('public')->delete($attachment->file_name);
        }
        
        $attachment->delete();
        $this->loadAttachments();
        
        $this->dispatch('show-success', 'Attachment deleted successfully!');
    }

    public function downloadAttachment($id)
    {
        $attachment = FileAttachment::findOrFail($id);
        
        if (!$attachment->file_name || !Storage::disk('public')->exists($attachment->file_name)) {
            $this->dispatch('show-error', 'File not found!');
            return;
        }
        
        return response()->download(
            storage_path('app/public/' . $attachment->file_name),
            $attachment->doc_name . '.' . pathinfo($attachment->file_name, PATHINFO_EXTENSION)
        );
    }

    public function addStage()
    {
        $this->validate([
            'stage_id' => ['required', 'exists:stages,id'],
            'stage_comment' => ['nullable', 'string', 'max:500'],
        ]);

        // Deactivate current stage if exists
        if ($this->currentStage) {
            $this->currentStage->update(['active' => false]);
        }

        // Create new stage assignment
        $stageAssignment = new FileStage();
        $stageAssignment->file_id = $this->fileId;
        $stageAssignment->stage_id = $this->stage_id;
        $stageAssignment->comment = $this->stage_comment;
        $stageAssignment->active = true;
        $stageAssignment->created_by = Auth::id();
        $stageAssignment->updated_by = Auth::id();
        $stageAssignment->save();

        $this->reset(['stage_id', 'stage_comment']);
        $this->loadStageHistory();
        
        $this->dispatch('close-modal');
        $this->dispatch('show-success', 'Stage updated successfully!');
    }

    public function getStageColor($stageName)
    {
        $colors = [
            'Draft' => 'secondary',
            'Under Review' => 'warning',
            'Approved' => 'success',
            'Published' => 'info',
            'Archived' => 'dark',
        ];
        
        return $colors[$stageName] ?? 'primary';
    }

    public function render()
    {
        return view('livewire.file-view');
    }
}