<?php

namespace App\Livewire\Forms\Tables;

use App\Models\TextAd;
use App\Enums\TextAdColors;
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 TextAdsTable extends PowerGridComponent
{
    use WithExport, WireUiActions;
    public string $tableName = 'text-ads-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('text-ad-create') ?? false;
        $this->canEdit = Auth::user()?->can('text-ad-edit') ?? false;
        $this->canDownload=Auth::user()?->can('text-ad-delete') ?? false;
        $this->canDelect = Auth::user()?->can('text-ad-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();
        if($this->canCreate){
            $header->includeViewOnTop('livewire.header.text-ad');
        }
        $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 TextAd::query();
    }

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

    public function fields(): PowerGridFields
    {
        return PowerGrid::fields()
            ->add('id')
            ->add('content')
            ->add(
                'content_short',
                fn (TextAd $model) =>
                    '<span title="' . e($model->content) . '">' . e(Str::limit($model->content, 50)) . '</span>'
            )
            ->add('color')
            ->add('color_str', function  (TextAd $model) {
                if ($this->canEdit) {
                    return Blade::render(
                        '<x-select-category 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('duration')
            ->add('is_active')
            ->add('created_at');
    }

    public function columns(): array
    {
        $column=[];
        $column[] = Column::make(__('text_ads.id'), 'id');
        $column[] = Column::make(__('text_ads.content'), 'content_short', 'text_ads.content')->sortable()->searchable();
        $column[] = Column::make(__('text_ads.color'),'color_str', 'text-ads.color')->searchable();
        $column[] = Column::make(__('text_ads.duration'), 'duration')->sortable()->searchable();
        $column[] = Column::make(__('text_ads.is_active'), 'is_active')->toggleable(hasPermission: $this->canEdit, trueLabel: 'yes', falseLabel: 'no');
        $column[] = Column::make(__('text_ads.created_at'), 'created_at')->sortable()->searchable();
        $column[] = Column::action(__('text_ads.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) {
                $textAd = TextAd::find($id);
                if ($textAd) {
                    $textAd->delete();
                }
            }
            $this->js('window.pgBulkActions.clearAll()'); // clear the count on the interface.
        }
    }
    #[On('categoryChanged')]
    public function categoryChanged($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){
        $textAd = TextAd::find($id);
        if ($textAd) {
            $textAd->{$field} = $value;
            $textAd->save(); // 明確觸發 saving
        }
        $this->notification()->send([
            'icon' => 'success',
            'title' => $id.'.'.__('text_ads.'.$field).':'.$value,
            'description' => '已經寫入',
        ]);
    }
    

    public function actions(TextAd $row): array
    {
        $actions = [];
        

        if ($this->canEdit) {
            $actions[]=Button::add('edit')
                ->slot(__('text_ads.edit'))
                ->icon('solid-pencil-square')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.text-ads-form', 'openModal', ['id' => $row->id]);
        }
        if($this->canDelect){
            $actions[]=Button::add('delete')
                ->slot(__('text_ads.delete'))
                ->icon('solid-trash')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.text-ads-form', 'deleteTextAd', ['id' => $row->id]);
        }

        return $actions;
    }
}
