<?php

namespace App\Livewire;

use App\Models\Items;
use App\Models\TypeItems;
use App\Models\Bundles;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Storage;

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 $bundle_ids = [];

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

    public $allTypeItems;
    public $allBundles;

    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',
        'bundle_ids' => 'nullable|array',
        'bundle_ids.*' => 'exists:bundles,id',
        'new_image' => 'nullable|image|max:1024',
    ];

    public function mount()
    {
        $this->allTypeItems = TypeItems::all();
        $this->allBundles = Bundles::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->bundle_ids = $item->bundles->pluck('id')->toArray();
        $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,
        ];

        if ($this->new_image) {
            if ($this->itemId && $this->image_url) {
                Storage::disk('public')->delete($this->image_url);
            }
            $itemData['image_url'] = $this->new_image->store('items', 'public');
        }

        $item = null;
        if ($this->itemId) {
            $item = Items::find($this->itemId);
            $item->update($itemData);
            session()->flash('message', 'Item berhasil diperbarui!');
        } else {
            $item = Items::create($itemData);
            session()->flash('message', 'Item berhasil ditambahkan!');
        }

        if ($item) {
            $item->bundles()->sync($this->bundle_ids);
        }

        $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) {
                    Storage::disk('public')->delete($item->image_url);
                }
                $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 = '';
        $this->bundle_ids = [];
    }

    public function setTypeItem($id = null)
    {
        $this->typeItemId = $id;
        $this->resetPage();
    }

    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', 'bundles'])
            ->paginate(10);

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