<?php

namespace App\Livewire;

use App\Models\Items;
use App\Models\TypeItems;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\File;
use Intervention\Image\Laravel\Facades\Image;
// use Intervention\Image\ImageManager;

class ItemTable extends Component
{
    use WithPagination;
    use WithFileUploads;

    public $search = '';
    public $sortBy = 'name';
    public $sortDirection = 'asc';
    public $typeItemId = null;

    public $itemId;
    public $name;
    public $description;
    public $price;
    public $image_url;
    public $new_image;
    public $is_available = true;
    public $type_item_id;

    public $isModalOpen = false;
    public $isDeleteModalOpen = false;
    public $itemToDeleteId;

    public $allTypeItems;

    protected $queryString = [
        'search' => ['except' => ''],
        'sortBy' => ['except' => 'name'],
        'sortDirection' => ['except' => 'asc'],
        'typeItemId' => ['except' => null],
    ];

    protected $rules = [
        'name' => 'required|string|max:255',
        'description' => 'nullable|string',
        'price' => 'required|numeric|min:0',
        'is_available' => 'boolean',
        'type_item_id' => 'required|exists:type_items,id',
        'new_image' => 'nullable|image|max:1024',
    ];

    public function mount()
    {
        $this->allTypeItems = TypeItems::all();
        $this->typeItemId = request()->query('type_item_id');
    }

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

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

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

    public function create()
    {
        $this->resetInputFields();
        $this->is_available = true;
        $this->isModalOpen = true;
    }

    public function edit($id)
    {
        $item = Items::findOrFail($id);
        $this->itemId = $item->id;
        $this->name = $item->name;
        $this->description = $item->description;
        $this->price = $item->price;
        $this->image_url = $item->image_url;
        $this->is_available = $item->is_available;
        $this->type_item_id = $item->type_item_id;
        $this->new_image = null;
        $this->isModalOpen = true;
    }

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

        $itemData = [
            'name' => $this->name,
            'description' => $this->description,
            'price' => $this->price,
            'is_available' => $this->is_available,
            'type_item_id' => $this->type_item_id,
        ];

        $targetPath = 'img/items/';
        if (!File::isDirectory(public_path($targetPath))) {
            File::makeDirectory(public_path($targetPath), 0755, true);
        }

        if ($this->new_image) {
            if ($this->image_url && File::exists(public_path($this->image_url))) {
                File::delete(public_path($this->image_url));
            }

            $webpName = uniqid('item_') . '.webp';
            $image = Image::read($this->new_image->getRealPath())->toWebp(80);
            $image->save(public_path($targetPath . $webpName));

            $itemData['image_url'] = $targetPath . $webpName;
        } elseif ($this->itemId && !$this->image_url) {
            $item = Items::find($this->itemId);
            if ($item && $item->image_url && File::exists(public_path($item->image_url))) {
                File::delete(public_path($item->image_url));
            }
            $itemData['image_url'] = null;
        }

        $item = Items::updateOrCreate(
            ['id' => $this->itemId],
            $itemData
        );

        session()->flash('message', $this->itemId ? 'Item berhasil diperbarui!' : 'Item berhasil ditambahkan!');
        $this->closeModal();
        $this->resetInputFields();
    }

    public function confirmDelete($id)
    {
        $this->itemToDeleteId = $id;
        $this->isDeleteModalOpen = true;
    }

    public function delete()
    {
        if ($this->itemToDeleteId) {
            $item = Items::find($this->itemToDeleteId);
            if ($item) {
                if ($item->image_url) {
                    $imagePath = public_path($item->image_url);
                    if (File::exists($imagePath)) {
                        File::delete($imagePath);
                    }
                }
                $item->delete();
                session()->flash('message', 'Item berhasil dihapus!');
            }
        }
        $this->closeDeleteModal();
    }

    public function closeModal()
    {
        $this->isModalOpen = false;
        $this->resetValidation();
    }

    public function closeDeleteModal()
    {
        $this->isDeleteModalOpen = false;
        $this->itemToDeleteId = null;
    }

    private function resetInputFields()
    {
        $this->itemId = null;
        $this->name = '';
        $this->description = '';
        $this->price = '';
        $this->image_url = null;
        $this->new_image = null;
        $this->is_available = true;
        $this->type_item_id = '';
    }

    public function render()
    {
        $items = Items::query()
            ->when($this->search, fn ($query) =>
                $query->where('name', 'like', '%' . $this->search . '%')
                    ->orWhere('description', 'like', '%' . $this->search . '%')
            )
            ->when($this->typeItemId, fn ($query) =>
                $query->where('type_item_id', $this->typeItemId)
            )
            ->orderBy($this->sortBy, $this->sortDirection)
            ->with(['typeItem'])
            ->paginate(10);

        return view('livewire.item-table', [
            'items' => $items,
            'allTypeItems' => $this->allTypeItems,
        ]);
    }
}
