<?php

namespace App\Livewire\Forms\Tables;

use App\Models\Room;
use App\Enums\RoomType;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Blade;
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 PowerComponents\LivewirePowerGrid\Traits\WithExport; 
use PowerComponents\LivewirePowerGrid\Components\SetUp\Exportable; 
use Livewire\Attributes\On;
use WireUi\Traits\WireUiActions;

final class RoomTable extends PowerGridComponent
{
    use WithExport, WireUiActions;
    public string $tableName = 'room-table';
    public bool $canCreate;
    public bool $canEdit;
    public bool $canDownload;
    public bool $canDelect;

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

    public function setUp(): array
    {
        if($this->canDownload || $this->canDelect){
            $this->showCheckBox();
        }
        $actions = [];
        if($this->canDownload){
            $actions[]=PowerGrid::exportable(fileName: $this->tableName.'-file') 
                ->type(Exportable::TYPE_XLS, Exportable::TYPE_CSV);
        }
        $header = PowerGrid::header()
            ->withoutLoading()
            ->showToggleColumns();
        if($this->canCreate){
            $header->includeViewOnTop('livewire.header.admin.room');
        }  
        $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
    {
        return Room::query();
    }

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

    public function fields(): PowerGridFields
    {
        return PowerGrid::fields()
            ->add('id')
            ->add('floor')
            ->add('type_str',function(Room $model){
                if ($this->canEdit) {
                    return Blade::render(
                        '<x-select-category type="occurrence" :options=$options  :modelId=$modelId :fieldName=$fieldName :selected=$selected/>', 
                        [
                            'options' => RoomType::options(), 
                            'modelId' => intval($model->id),
                            'fieldName'=>'type', 
                            'selected' => $model->type->value
                        ]
                    );
                }
                return $model->type->labelPowergridFilter();
            })
            ->add('name')
            ->add('internal_ip')
            ->add('port')
            ->add('is_online', fn ($model) => $model->is_online===true ? '在線' : '斷線')
            ->add('status_str',function (Room $model){
                return $model->status->labelPowergridFilter();
            })
            ->add('str_started_at', fn (Room $model) => $model->str_started_at())
            ->add('str_ended_at', fn (Room $model) => $model->str_ended_at())
            ->add('created_at');
    }

    public function columns(): array
    {
        $column=[];
        $column[]=Column::make(__('rooms.id'), 'id');
        $column[]=Column::make(__('rooms.floor'), 'floor')->sortable()->searchable()->editOnClick(
                hasPermission: $this->canEdit,
                dataField: 'floor',
                fallback: 'N/A',
                saveOnMouseOut: true
            );
        $column[]=Column::make(__('rooms.type'), 'type_str','room.type')->sortable()->searchable();
        $column[]=Column::make(__('rooms.name'), 'name')->sortable()->searchable()
            ->editOnClick(
                hasPermission: $this->canEdit,
                dataField: 'name',
                fallback: 'N/A',
                saveOnMouseOut: true
            );
        $column[]=Column::make(__('rooms.internal_ip'), 'internal_ip')->sortable()->searchable()->hidden(true, false);
        $column[]=Column::make(__('rooms.port'), 'port')->sortable()->searchable()->hidden(true, false);
        $column[]=Column::make(__('rooms.isOnline'), 'is_online')->hidden(true, false);
        $column[]=Column::make(__('rooms.status'), 'status_str','room.status')->sortable()->searchable()->hidden(true, false);
        $column[]=Column::make(__('rooms.started_at'), 'str_started_at', 'started_at')->sortable()->hidden(true, false);
        $column[]=Column::make(__('rooms.ended_at'), 'str_ended_at', 'ended_at')->sortable()->hidden(true, false);
        $column[]=Column::make(__('rooms.created_at'), 'created_at')->sortable()->searchable();
        $column[]=Column::action('Action');

        return $column;
    }

    public function filters(): array
    {
        return [
            Filter::datetimepicker('started_at'),
            Filter::datetimepicker('ended_at'),
            Filter::boolean('is_online')
                ->label('在線', '斷線'),
        ];
    }

    #[On('bulkDelete.{tableName}')]
    public function bulkDelete(): void
    {
        if ($this->canDelect) {
            $this->js('alert(window.pgBulkActions.get(\'' . $this->tableName . '\'))');
            if($this->checkboxValues){
                Branch::destroy($this->checkboxValues);
                $this->js('window.pgBulkActions.clearAll()'); // clear the count on the interface.
            }
        }
    } 
    #[On('categoryChanged')]
    public function categoryChanged($value,$fieldName, $modelId): void
    {
        if ($fieldName == 'type' && $this->canEdit) {
            $this->noUpdated($modelId,$fieldName,$value);
        }
    }
    #[On('onUpdatedEditable')]
    public function onUpdatedEditable($id, $field, $value): void
    {
        if($field === 'floor' && $this->canEdit){
            if (!is_numeric($value)) {
                $this->notification()->send([
                    'icon' => 'error',
                    'title' => '無效輸入',
                    'description' => '樓層必須是數字',
                ]);
                return;
            }
            $this->noUpdated($id,$field,$value);
        }else if ($field === 'name' && $this->canEdit) {
            $this->noUpdated($id,$field,$value);
        }
    }
    
    private function noUpdated($id,$field,$value){
        //dd($id,$field,$value);
        $room = Room::find($id);
        if ($room) {
            $room->{$field} = $value;
            $room->save(); // 明確觸發 saving
        }
        $this->notification()->send([
            'icon' => 'success',
            'title' => $id.'.'.__('room.'.$field).':'.$value,
            'description' => '已經寫入',
        ]);
    }

    public function actions(Room $row): array
    {
        $actions = [];
        
        if ($this->canEdit) {
            $actions[] =Button::add('edit')
                ->slot(__('rooms.edit'))
                ->icon('solid-pencil-square')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.room-form', 'openModal', ['id' => $row->id]);
        }
        if($this->canDelect){
            $actions[] =Button::add('delete')
                ->slot(__('rooms.delete'))
                ->icon('solid-trash')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.room-form', 'deleteRoom', ['id' => $row->id]);
        }
        if ($row->type->value === 'pc') {
            $actions[] = Button::add('room-settings')
                ->slot('包廂設定')
                ->icon('solid-cog')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.modals.room-detail-modal', 'openModal', ['roomId' => $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(),
        ];
    }
    */
}
