<?php

namespace App\Livewire\Forms\Tables;

use App\Models\User;
use App\Enums\UserGender;
use App\Enums\UserStatus;
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 UserTable extends PowerGridComponent
{
    use WithExport, WireUiActions;
 
    public string $tableName = 'user-table';

    public bool $showFilters = false;
    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('user-edit') ?? false;
        $this->canEdit = Auth::user()?->can('user-edit') ?? false;
        $this->canDownload=Auth::user()?->can('user-delete') ?? false;
        $this->canDelect = Auth::user()?->can('user-delete') ?? false;
    }
   

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

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

    public function fields(): PowerGridFields
    {
        
        return PowerGrid::fields()
            ->add('id')
            ->add('name')
            ->add('email')
            ->add('phone')
            ->add('birthday_formatted',fn (User $model) => Carbon::parse($model->birthday)->format('Y-m-d'))
            ->add('gender_str', function  (User $model) {
                if ($this->canEdit) {
                    return Blade::render(
                        '<x-select-category type="occurrence" :options=$options  :modelId=$modelId :fieldName=$fieldName :selected=$selected/>', 
                        [
                            'options' => UserGender::options(), 
                            'modelId' => intval($model->id),
                            'fieldName'=>'gender', 
                            'selected' => $model->gender->value
                        ]
                    );
                }
                // 沒有權限就顯示對應的文字
                
                return $model->gender->labelPowergridFilter(); // 假設 label() 會回傳顯示文字
            } )
            ->add('status_str', function  (User $model) {
                if ($this->canEdit) {
                    return Blade::render(
                        '<x-select-category type="occurrence" :options=$options  :modelId=$modelId :fieldName=$fieldName :selected=$selected/>', 
                        [
                            'options' => UserStatus::options(), 
                            'modelId' => intval($model->id),
                            'fieldName'=>'status', 
                            'selected' => $model->status->value
                        ]
                    );
                }
                // 沒有權限就顯示對應的文字
                
                return $model->status->labelPowergridFilter(); // 假設 label() 會回傳顯示文字
            } )
            ->add('roles' ,fn(User $model)=> $model->roles->pluck('name')->implode(', '))
            ->add('created_at_formatted', fn (User $model) => Carbon::parse($model->created_at)->format('Y-m-d H:i:s'));
    }

    public function columns(): array
    {
        return [
            Column::make('ID', 'id'),
            Column::make(__('users.name'), 'name')
                ->sortable()
                ->searchable()
                ->editOnClick(
                    hasPermission: $this->canEdit,
                    dataField: 'name',
                    fallback: 'N/A',
                    saveOnMouseOut: true
                ),
            Column::make('Email', 'email')
                ->sortable()
                ->searchable()
                ->editOnClick(
                    hasPermission: $this->canEdit,
                    dataField: 'email',
                    fallback: 'N/A',
                    saveOnMouseOut: true
                ),
            Column::make(__('users.phone'), 'phone')
                ->sortable()
                ->searchable()
                ->editOnClick(
                    hasPermission: $this->canEdit, 
                    dataField: 'phone', 
                    fallback: 'N/A', 
                    saveOnMouseOut: true
                ),
    
            Column::make(__('users.gender'), 'gender_str','users.gender'),
            Column::make(__('users.birthday'), 'birthday_formatted')->sortable()->searchable(),
            Column::make(__('users.status'), 'status_str','users.status'),
            Column::make(__('users.role'), 'roles'),
            Column::make('建立時間', 'created_at_formatted', 'created_at')->sortable(),
            Column::action('操作')
        ];
    }
    #[On('bulkDelete.{tableName}')]
    public function bulkDelete(): void
    {
        if ($this->canDelect) {
            $this->js('alert(window.pgBulkActions.get(\'' . $this->tableName . '\'))');
            if($this->checkboxValues){
                User::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 (in_array($fieldName,['gender','status']) && $this->canEdit) {
            $this->noUpdated($modelId,$fieldName,$value);
        }
    }
    #[On('onUpdatedEditable')]
    public function onUpdatedEditable($id, $field, $value): void
    {
        if (in_array($field,['name','email','phone']) && $this->canEdit) {
            $this->noUpdated($id,$field,$value);
        }
    }
    #[On('onUpdatedToggleable')]
    public function onUpdatedToggleable($id, $field, $value): void
    {
        if (in_array($field,[]) && $this->canEdit) {
            $this->noUpdated($id,$field,$value);
        }
    }
    private function noUpdated($id,$field,$value){
        $user = User::find($id);
        if ($user) {
            $user->{$field} = $value;
            $user->save(); // 明確觸發 saving
        }
        $this->notification()->send([
            'icon' => 'success',
            'title' => $id.'.'.__('users.'.$field).':'.$value,
            'description' => '已經寫入',
        ]);
    }
    public function filters(): array
    {
        return [
            Filter::inputText('name')->placeholder(__('users.name')),
            Filter::inputText('email')->placeholder('Email'),
            Filter::inputText('phone')->placeholder(__('users.phone')),
            Filter::enumSelect('gender_str','users.gender') 
                ->datasource(UserGender::cases())
                ->optionLabel('users.gender'),
            Filter::datepicker('birthday'),
            Filter::enumSelect('status_str', 'users.status')  
                ->datasource(UserStatus::cases())
                ->optionLabel('users.status'),
            Filter::datetimepicker('created_at'),
        ];
    }

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