<?php

namespace App\Livewire\Tables;

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Builder;
use PowerComponents\LivewirePowerGrid\Button;
use PowerComponents\LivewirePowerGrid\Column;
use PowerComponents\LivewirePowerGrid\Facades\Filter;
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridFields;
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use Livewire\Attributes\On;
use WireUi\Traits\WireUiActions;

final class RoleTable extends PowerGridComponent
{
    use WireUiActions;

    public string $tableName = 'role-table';
    public bool $canCreate;
    public bool $canEdit;
    public bool $canDelect;

    public function boot(): void
    {
        config(['livewire-powergrid.filter' => 'outside']);
        //權限設定
        $this->canCreate = Auth::user()?->can('role-edit') ?? false;
        $this->canEdit = Auth::user()?->can('role-edit') ?? false;
        $this->canDelect = Auth::user()?->can('role-delete') ?? false;
    }

    public function setUp(): array
    {
        if($this->canDelect){
            $this->showCheckBox();
        }
        $actions = [];
        $header =PowerGrid::header();
        $header->includeViewOnTop('livewire.headers.role');
        $actions[]=$header;
        $actions[]=PowerGrid::footer()
            ->showPerPage()
            ->showRecordCount();    
        return $actions;
    }
    public function header(): array
    {
        $actions = [];
        if ($this->canDelect) {
            $actions[]=Button::add('bulk-delete')
                ->slot('Bulk delete (<span x-text="window.pgBulkActions.count(\'' . $this->tableName . '\')"></span>)')
                ->icon('solid-trash',['id' => 'my-custom-icon-id', 'class' => 'font-bold'])
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatch('bulkDelete.' . $this->tableName, []);
        }
        return $actions;
    } 

    public function datasource(): Builder
    {
       //dd(Role::with('permissions'));
        return Role::with('permissions');
    }

    public function relationSearch(): array
    {
        return [];
    }

    public function fields(): PowerGridFields
    {
        $allPermissions = Permission::pluck('name')->sort()->values();
        return PowerGrid::fields()
            ->add('id')
            ->add('name')
            ->add('permissions_list', function (Role $model) use ($allPermissions) {
                $rolePermissions = $model->permissions->pluck('name')->sort()->values();
            
                if ($rolePermissions->count() === $allPermissions->count() && $rolePermissions->values()->all() === $allPermissions->values()->all()) {
                    return 'all';
                }
            
                return $rolePermissions->implode(', ');
            })
            ->add('created_at_formatted', fn (Role $model) => Carbon::parse($model->created_at)->format('Y-m-d H:i:s'));
    }

    public function columns(): array
    {
        $column=[];
        $column[]=Column::make(__('roles.no'), 'id')->sortable()->searchable();
        $column[]=Column::make(__('roles.name'), 'name')->sortable()->searchable()
            ->editOnClick(
                hasPermission: $this->canEdit,
                dataField: 'name',
                fallback: 'N/A',
                saveOnMouseOut: true
            );
        $column[]=Column::make(__('roles.permissions'), 'permissions_list');
        $column[]=Column::make('Created at', 'created_at_formatted', 'created_at')->sortable();
        $column[]=Column::action('Action');
        return $column;
    }
    #[On('bulkDelete.{tableName}')]
    public function bulkDelete(): void
    {
        if ($this->canDelect) {
            $this->js('alert(window.pgBulkActions.get(\'' . $this->tableName . '\'))');
            if($this->checkboxValues){
                Role::destroy($this->checkboxValues);
                $this->js('window.pgBulkActions.clearAll()'); // clear the count on the interface.
            }
        }
    } 
    #[On('onUpdatedEditable')]
    public function onUpdatedEditable($id, $field, $value): void
    {
        if ($field === 'name' && $this->canEdit) {
            $this->noUpdated($id,$field,$value);
        }
    }
    private function noUpdated($id,$field,$value){
        $role = Role::find($id);
        if ($role) {
            $role->{$field} = $value;
            $role->save(); // 明確觸發 saving
        }
        $this->notification()->send([
            'icon' => 'success',
            'title' => $id.'.'.__('roles.'.$field).':'.$value,
            'description' => '已經寫入',
        ]);
    }
    public function filters(): array
    {
        return [
            Filter::inputText('name')->placeholder(__('roles.name')),
            Filter::datetimepicker('created_at'),
        ];
    }


    public function actions(Role $row): array
    {
        $actions = [];
        if ($this->canEdit) {
            $actions[] =Button::add('edit')
                ->slot(__('roles.edit'))
                ->icon('solid-pencil-square')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.role-form', 'openEditRoleModal', ['id' => $row->id]);
        }
        if($this->canDelect){
            $actions[] =Button::add('delete')
                ->slot(__('roles.delete'))
                ->icon('solid-trash')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.role-form', 'deleteRole', ['id' => $row->id]);
        }
        return $actions;
    }

    /*
    public function actionRules($row): array
    {
       return [
            // Hide button edit for ID 1
            Rule::button('edit')
                ->when(fn($row) => $row->id === 1)
                ->hide(),
        ];
    }
    */
}
