<?php

namespace App\Livewire\Tables;

use App\Enums\TextAdColors;
use App\Models\BroadcastTemplate;
use Illuminate\Support\Str;
use Illuminate\Support\Carbon;
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 PowerComponents\LivewirePowerGrid\Facades\Rule;
use Livewire\Attributes\On;
use WireUi\Traits\WireUiActions;

final class BroadcastTemplateTable extends PowerGridComponent
{
    public string $tableName = 'broadcast-table';

    public bool $canCreate;
    public bool $canEdit;
    public bool $canDownload;
    public bool $canDelect;

    public function boot(): void
    {
        config(['livewire-powergrid.filter' => 'outside']);
        $this->canCreate = Auth::user()?->can('broadcast-create') ?? false;
        $this->canEdit = Auth::user()?->can('broadcast-edit') ?? false;
        $this->canDownload=Auth::user()?->can('broadcast-delete') ?? false;
        $this->canDelect = Auth::user()?->can('broadcast-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()->showSoftDeletes()->showToggleColumns();
        $header->includeViewOnTop('livewire.headers.broadcast-template');
        $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 BroadcastTemplate::query();
    }

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

    public function fields(): PowerGridFields
    {
        return PowerGrid::fields()
            ->add('id')
            ->add('content')
            ->add(
                'content_short',
                fn (BroadcastTemplate $model) =>
                    '<span title="' . e($model->content) . '">' . e(Str::limit($model->content, 50)) . '</span>'
            )
            ->add('color')
            ->add('color_str', function  (BroadcastTemplate $model) {
                if ($this->canEdit) {
                    return Blade::render(
                        '<x-select-dropdown type="occurrence" :options=$options  :modelId=$modelId :fieldName=$fieldName :selected=$selected/>', 
                        [
                            'options' => TextAdColors::options(), 
                            'modelId' => intval($model->id),
                            'fieldName'=>'color', 
                            'selected' => $model->color->value
                        ]
                    );
                }
                // 沒有權限就顯示對應的文字
                
                return $model->color->labelPowergridFilter(); // 假設 label() 會回傳顯示文字
            } )
            ->add('is_active')
            ->add('created_at');
    }

    public function columns(): array
    {
        $column=[];
        $column[] = Column::make(__('broadcast-templates.id'), 'id');
        $column[] = Column::make(__('broadcast-templates.content'), 'content_short', 'broadcast-templates.content')->sortable()->searchable();
        $column[] = Column::make(__('broadcast-templates.color'),'color_str', 'text-ads.color')->searchable();
        $column[] = Column::make(__('broadcast-templates.is_active'), 'is_active')->toggleable(hasPermission: $this->canEdit, trueLabel: 'yes', falseLabel: 'no');
        $column[] = Column::make(__('broadcast-templates.created_at'), 'created_at')->sortable()->searchable();
        $column[] = Column::action(__('broadcast-templates.actions'));
        return $column;
    }

    public function filters(): array
    {
        return [
        ];
    }
    #[On('bulkDelete.{tableName}')]
    public function bulkDelete(): void
    {
        $this->js('alert(window.pgBulkActions.get(\'' . $this->tableName . '\'))');
        if($this->checkboxValues){
            foreach ($this->checkboxValues as $id) {
                $template = BroadcastTemplate::find($id);
                if ($template) {
                    $template->delete();
                }
            }
            $this->js('window.pgBulkActions.clearAll()'); // clear the count on the interface.
        }
    }
    #[On('selectChanged')]
    public function selectChanged($value,$fieldName, $modelId): void
    {
        //dd($value,$fieldName, $modelId);
        if (in_array($fieldName, ['color'])) {
            $this->noUpdated($modelId,$fieldName,$value);
        }
    }
    #[On('onUpdatedEditable')]
    public function onUpdatedEditable($id, $field, $value): void
    {
        if (in_array($field,[
                ''
            ]) && $this->canEdit) {
            $this->noUpdated($id,$field,$value);
        }
    }
    #[On('onUpdatedToggleable')]
    public function onUpdatedToggleable($id, $field, $value): void
    {
        if (in_array($field,['is_active']) && $this->canEdit) {
            $this->noUpdated($id,$field,$value);
        }
    }
    private function noUpdated($id,$field,$value){
        $template = BroadcastTemplate::find($id);
        if ($template) {
            $template->{$field} = $value;
            $template->save(); // 明確觸發 saving
        }
        $this->notification()->send([
            'icon' => 'success',
            'title' => $id.'.'.__('broadcast.'.$field).':'.$value,
            'description' => '已經寫入',
        ]);
    }

    public function actions(BroadcastTemplate $row): array
    {
        $actions = [];
        if ($this->canEdit) {
            $actions[]=Button::add('edit')
                ->slot(__('broadcast-templates.edit'))
                ->icon('solid-pencil-square')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.broadcast-template-form', 'openModal', ['id' => $row->id]);
        }
        if($this->canDelect){
            $actions[]=Button::add('delete')
                ->slot(__('broadcast-templates.delete'))
                ->icon('solid-trash')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.broadcast-template-form', 'deleteBroadcast', ['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(),
        ];
    }
    */
}
