<?php

namespace App\Livewire\Forms\Tables;

use App\Models\Artist;
use App\Enums\ArtistCategory;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
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 ArtistTable extends PowerGridComponent
{
    use WithExport, WireUiActions;

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

    //public bool $deferLoading = true;
    //public string $loadingComponent = 'components.power-grid-loading';

    public bool $showFilters = false;

    public function boot(): void
    {
        config(['livewire-powergrid.filter' => 'outside']);
        //權限設定
        $this->canCreate = Auth::user()?->can('song-edit') ?? false;
        $this->canEdit = Auth::user()?->can('song-edit') ?? false;
        $this->canDownload=Auth::user()?->can('song-delete') ?? false;
        $this->canDelect = Auth::user()?->can('song-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();
            //->showSoftDeletes()
            //->showSearchInput()
        if($this->canCreate){
            $header->includeViewOnTop('livewire.header.artist') ;
        }
        $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 Artist::query();
    }

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

    public function fields(): PowerGridFields
    {
        return PowerGrid::fields()
            ->add('id')
            ->add('category_str', function  (Artist $model) {
                if ($this->canEdit) {
                    return Blade::render(
                        '<x-select-category type="occurrence" :options=$options  :modelId=$modelId :fieldName=$fieldName :selected=$selected/>', 
                        [
                            'options' => ArtistCategory::options(), 
                            'modelId' => intval($model->id),
                            'fieldName'=>'category', 
                            'selected' => $model->category->value
                        ]
                    );
                }
                // 沒有權限就顯示對應的文字
                
                return $model->category->labelPowergridFilter(); // 假設 label() 會回傳顯示文字
            } )
            ->add('name')
            ->add('simplified')
            ->add('phonetic_abbr')
            ->add('pinyin_abbr')
            ->add('strokes_abbr')
            ->add('enable')
            ->add('created_at_formatted', fn (Artist $model) => Carbon::parse($model->created_at)->format('Y-m-d H:i:s'));
    }

    public function columns(): array
    {
        $column=[];
        $column[]=Column::make(__('artists.no'), 'id');
        $column[]=Column::make(__('artists.category'),'category_str', 'artists.category')->searchable();
        $column[]=Column::make(__('artists.name'), 'name')->sortable()->searchable()
                    ->editOnClick(
                        hasPermission: $this->canEdit,
                        dataField: 'name',
                        fallback: 'N/A',
                        saveOnMouseOut: true
                    );
        $column[]=Column::make(__('artists.name.simplified'), 'simplified')->sortable()->searchable()->hidden(true, false);
        $column[]=Column::make(__('artists.name.phinetic'), 'phonetic_abbr')->sortable()->searchable();
        $column[]=Column::make(__('artists.name.pinyin'), 'pinyin_abbr')->sortable()->searchable();
        $column[]=Column::make(__('artists.name.strokes'), 'strokes_abbr')->sortable()->searchable();
        $column[]=Column::make(__('artists.enable'), 'enable')->toggleable(hasPermission: $this->canEdit, trueLabel: 'yes', falseLabel: 'no');
        $column[]=Column::make('Created at', 'created_at_formatted', 'created_at')->sortable()->hidden(true, false);
        $column[]=Column::action(__('artists.actions'));
        
        return $column;
    }
    #[On('bulkDelete.{tableName}')]
    public function bulkDelete(): void
    {
        if ($this->canDelect) {
            $this->js('alert(window.pgBulkActions.get(\'' . $this->tableName . '\'))');
            if($this->checkboxValues){
                Artist::destroy($this->checkboxValues);
                $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 ($fieldName == 'category' && $this->canEdit) {
            $this->noUpdated($modelId,$fieldName,$value);
        }
    }
    #[On('onUpdatedEditable')]
    public function onUpdatedEditable($id, $field, $value): void
    {
        if ($field === 'name' && $this->canEdit) {
            $this->noUpdated($id,$field,$value);
        }
    }
    #[On('onUpdatedToggleable')]
    public function onUpdatedToggleable($id, $field, $value): void
    {
        if (in_array($field,['enable']) && $this->canEdit) {
            $this->noUpdated($id,$field,$value);
        }
    }
    private function noUpdated($id,$field,$value){
        $artist = Artist::find($id);
        if ($artist) {
            $artist->{$field} = $value;
            $artist->save(); // 明確觸發 saving
        }
        $this->notification()->send([
            'icon' => 'success',
            'title' => $id.'.'.__('artists.'.$field).':'.$value,
            'description' => '已經寫入',
        ]);
    }
    
    public function filters(): array
    {
        return [
            Filter::enumSelect('category_str','artists.category') 
                ->datasource(ArtistCategory::cases())
                ->optionLabel('artists.category'),
            Filter::inputText('name')->placeholder(__('artists.name')),
            Filter::inputText('phonetic_abbr')->placeholder(__('artists.name.phinetic')),
            Filter::inputText('pinyin_abbr')->placeholder(__('artists.name.pinyin')),
            Filter::number('strokes_abbr')->thousands('.')->decimal(','),
            Filter::boolean('enable')->label('✅', '❌'),
            Filter::datetimepicker('created_at'),
        ];
    }
    public function actions(Artist $row): array
    {
        $actions = [];
        if ($this->canEdit) {
            $actions[] =Button::add('edit')
                ->slot(__('artists.edit'))
                ->icon('solid-pencil-square')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.artist-form', 'openModal', ['id' => $row->id]);
        }
        if($this->canDelect){
            $actions[] =Button::add('delete')
                ->slot(__('artists.delete'))
                ->icon('solid-trash')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.artist-form', 'deleteArtist', ['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(),
        ];
    }
    */
}
