<?php

namespace App\Livewire\Studio\Loyalty;

use App\Livewire\Forms\Studio\Loyalty\RewardForm;
use App\Models\Reward as RewardModel;
use App\Models\Tier;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithCloseModal;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Utilities\WithUpdatedData;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Hadiah')]
class Reward extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithSubscribeNotification, WithToast, WithUpdatedData;

    public RewardForm $form;

    public string $method = 'create';

    public string $modalTitle = '';

    public $tiers = [];

    public function mount(): void
    {
        $this->tiers = Tier::orderBy('min_spending')->pluck('name', 'id')->toArray();
    }

    public function create(): void
    {
        $this->canOrAbort('create reward');

        $this->form->store();

        $this->dispatch('refreshDatatable');

        $this->toast('Hadiah berhasil ditambahkan.');

        Flux::modals()->close();
    }

    public function update(): void
    {
        $this->canOrAbort('update reward');

        if ($this->form->reward->redemptions()->exists()) {
            $this->toast('Hadiah tidak dapat diubah karena sudah ada penukaran.', 'error');
            Flux::modals()->close();

            return;
        }

        $this->form->update();

        $this->dispatch('refreshDatatable');

        $this->toast('Hadiah berhasil diperbarui.');

        Flux::modals()->close();
    }

    public function delete(RewardModel $reward): void
    {
        $this->canOrAbort('delete reward');

        $reward->delete();

        $this->dispatch('refreshDatatable');

        $this->toast('Hadiah berhasil dihapus.');

        Flux::modals()->close();
    }

    #[On('modal:open')]
    public function openModal(string $method, string $modalTitle, ?string $id = null): void
    {
        $this->resetValidation();
        $this->resetErrorBag();

        $this->method = $method;
        $this->modalTitle = $modalTitle;

        $id && $this->form->setReward(RewardModel::byHashOrFail($id));
    }

    public function render(): View
    {
        return view('livewire.studio.loyalty.rewards', [
            'pageTitle' => 'Hadiah',
        ]);
    }
}
