<?php

namespace App\Livewire\Tables;

use App\Models\Branch;
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 Livewire\Attributes\Url;
use WireUi\Traits\WireUiActions;

final class RoomTable extends PowerGridComponent
{
    use WithExport, WireUiActions;
    public string $tableName = 'room-table';
    public bool $canDownload;
    public bool $canDelect;
    #[Url]
    public ?int $selectedBranchId = null;
    public ?string $external_ip= "";

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

    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();
        $header->includeViewOnTop('livewire.headers.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
    {
        $query = Room::query()->orderBy('name');

        if ($this->selectedBranchId) {
            $query->where('branch_id', $this->selectedBranchId);
        }

        return $query;
    }

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

    public function fields(): PowerGridFields
    {
        return PowerGrid::fields()
            ->add('id')
            ->add('floor')
            ->add('type_str',function(Room $model){
                return $model->type->labelPowergridFilter();
            })
            ->add('name')
            ->add('is_online_img', fn ($model) => [
                    $model->is_online ? 'check-circle' : 'x-circle' => [
                        'text-color' => $model->is_online ? 'text-green-600' : 'text-red-600',
                    ],
                ]
            )
            ->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();
        $column[]=Column::make(__('rooms.type'), 'type_str','room.type')->sortable()->searchable();
        $column[]=Column::make(__('rooms.name'), 'name')->sortable()->searchable();
        $column[]=Column::make(__('rooms.isOnline'), 'is_online_img')->template();
        $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 rowTemplates(): array
    {
        return [
            'check-circle' => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6 {{ text-color }}">
                <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                </svg>',
            'x-circle' => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6 {{ text-color }}">
                <path stroke-linecap="round" stroke-linejoin="round" d="m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                </svg>',
        ];
    }

    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('selectChanged')]
    public function selectChanged($value,$fieldName, $modelId): void
    {
        
        if($fieldName == 'selectedBranchId'){
            $this->selectedBranchId=$value;
            $branch = Branch::find($this->selectedBranchId);
            $this->external_ip=$branch->external_ip;
            $this->resetPage(); // 重設分頁
        }
    }
    #[On('deleteRoom')]
    public function deleteRoom($rowId)
    {
        if ($this->canDelect) {
            Room::findOrFail($rowId)->delete();
            $this->notification()->send([
                'icon' => 'success',
                'title' => '成功',
                'description' => '包廂已刪除',
            ]);
            
            $this->dispatch('pg:eventRefresh-room-table');
        }
    }

    public function actions(Room $row): array
    {
        $actions = [];
        
        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 ')
                ->dispatch('deleteRoom', ['rowId' => $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('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(),
        ];
    }
    */
}
