<?php

namespace App\Livewire\Admin;

use App\Models\AppBuilder;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;

class DeleteBuilderModal extends Component
{
    public $showModal = false;

    #[Locked]
    public $builderId = null;

    public $builderName = '';

    public $isDefault = false;

    #[On('delete-builder')]
    public function confirmDelete($id)
    {
        $builder = AppBuilder::findOrFail($id);

        $this->builderId = $builder->id;
        $this->builderName = $builder->name;
        $this->isDefault = $builder->is_default;
        $this->showModal = true;
    }

    public function delete()
    {
        if (config('app.demo')) {
            $this->dispatch('show-toast',
                type: 'error',
                message: __('common.demo_mode_deletion_disabled')
            );
            $this->closeModal();

            return;
        }

        $builder = AppBuilder::findOrFail($this->builderId);

        // Prevent deletion of default builder
        if ($builder->is_default) {
            $this->dispatch('show-toast',
                type: 'error',
                message: __('common.cannot_delete_default_builder')
            );
            $this->closeModal();

            return;
        }

        // Check if builder has active builds
        if ($builder->current_builds_count > 0) {
            $this->dispatch('show-toast',
                type: 'error',
                message: __('common.cannot_delete_builder_active')
            );
            $this->closeModal();

            return;
        }

        $builder->delete();

        $this->dispatch('show-toast',
            type: 'success',
            message: __('common.item_deleted', ['item' => 'Builder'])
        );

        $this->dispatch('builderDeleted');
        $this->closeModal();
    }

    public function closeModal()
    {
        $this->showModal = false;
        $this->isDefault = false;
        $this->reset(['builderId', 'builderName']);
    }

    public function render()
    {
        return view('livewire.admin.delete-builder-modal');
    }
}
