<?php

namespace App\Livewire\Admin;

use App\Models\Resource;
use App\Services\FlashMessageService;
use Livewire\Component;
use Livewire\WithPagination;

class ResourceManagement extends Component
{
    use WithPagination;

    public $search = '';
    public $statusFilter = '';
    public $sortBy = 'created_at';
    public $sortDirection = 'desc';

    protected $queryString = [
        'search' => ['except' => ''],
        'statusFilter' => ['except' => ''],
        'sortBy' => ['except' => 'created_at'],
        'sortDirection' => ['except' => 'desc'],
    ];

    public function mount()
    {
        // Check permissions
        if (!auth()->user()->can('resources.view')) {
            abort(403, 'Unauthorized access to resources.');
        }
    }

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingStatusFilter()
    {
        $this->resetPage();
    }

    public function sortBy($field)
    {
        if ($this->sortBy === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $field;
            $this->sortDirection = 'asc';
        }
    }

    public function deleteResource($resourceId)
    {
        // Check permissions
        if (!auth()->user()->can('resources.delete')) {
            FlashMessageService::insufficientPermissions();
            $this->dispatch('flashMessage', 'error', 'You do not have permission to delete resources.', 'Insufficient Permissions', 8000);
            return;
        }

        try {
            $resource = Resource::findOrFail($resourceId);
            
            // Delete the file from storage
            if ($resource->file_path && \Storage::disk('public')->exists($resource->file_path)) {
                \Storage::disk('public')->delete($resource->file_path);
            }
            
            $resource->delete();
            
            FlashMessageService::success('Resource deleted successfully!', 'Resource Deleted');
            $this->dispatch('flashMessage', 'success', 'Resource deleted successfully!', 'Resource Deleted', 5000);
            
        } catch (\Exception $e) {
            FlashMessageService::error('Failed to delete resource. Please try again.', 'Delete Failed');
            $this->dispatch('flashMessage', 'error', 'Failed to delete resource. Please try again.', 'Delete Failed', 8000);
            
            \Log::error('Resource deletion error: ' . $e->getMessage());
        }
    }

    public function toggleStatus($resourceId)
    {
        // Check permissions
        if (!auth()->user()->can('resources.edit')) {
            FlashMessageService::insufficientPermissions();
            $this->dispatch('flashMessage', 'error', 'You do not have permission to edit resources.', 'Insufficient Permissions', 8000);
            return;
        }

        try {
            $resource = Resource::findOrFail($resourceId);
            $resource->update(['is_active' => !$resource->is_active]);
            
            $status = $resource->is_active ? 'activated' : 'deactivated';
            FlashMessageService::success("Resource {$status} successfully!", 'Status Updated');
            $this->dispatch('flashMessage', 'success', "Resource {$status} successfully!", 'Status Updated', 5000);
            
        } catch (\Exception $e) {
            FlashMessageService::error('Failed to update resource status. Please try again.', 'Update Failed');
            $this->dispatch('flashMessage', 'error', 'Failed to update resource status. Please try again.', 'Update Failed', 8000);
            
            \Log::error('Resource status update error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        $query = Resource::with('creator')
            ->when($this->search, function ($query) {
                $query->where('title', 'like', '%' . $this->search . '%')
                      ->orWhere('description', 'like', '%' . $this->search . '%');
            })
            ->when($this->statusFilter, function ($query) {
                if ($this->statusFilter === 'active') {
                    $query->where('is_active', true);
                } elseif ($this->statusFilter === 'inactive') {
                    $query->where('is_active', false);
                }
            })
            ->orderBy($this->sortBy, $this->sortDirection);

        $resources = $query->paginate(10);

        return view('livewire.admin.resource-management', [
            'resources' => $resources,
        ]);
    }
}