<?php

namespace App\Livewire\Tables;

use App\Models\Branch;
use App\Jobs\ExportSqliteBranchJob;
use App\Jobs\ExportSqliteUserJob;
use App\Jobs\ExportSqliteSongJob;
use App\Jobs\ExportSqliteFavoriteJob;
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 BranchTable extends PowerGridComponent
{
    use WithExport, WireUiActions;
    public string $tableName = 'branch-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('room-edit') ?? false;
        $this->canEdit = Auth::user()?->can('room-edit') ?? false;
        $this->canDownload=Auth::user()?->can('room-delete') ?? false;
        $this->canDelect = Auth::user()?->can('room-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()
        $header->includeViewOnTop('livewire.headers.branch') ;
        $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 Branch::query();
    }

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

    public function fields(): PowerGridFields
    {
        return PowerGrid::fields()
            ->add('id')
            ->add('name')
            ->add('external_ip')
            ->add('enable')
            ->add('created_at_formatted', fn (Branch $model) => Carbon::parse($model->created_at)->format('d/m/Y H:i:s'));
    }

    public function columns(): array
    {
        $column=[];
        $column[]=Column::make(__('branches.no'), 'id');
        $column[]=Column::make(__('branches.name'), 'name')->sortable()->searchable()
                    ->editOnClick(
                        hasPermission: $this->canEdit,
                        dataField: 'name',
                        fallback: 'N/A',
                        saveOnMouseOut: true
                    );
        $column[]=Column::make(__('branches.external_ip'), 'external_ip')->sortable()->searchable()
                    ->editOnClick(
                        hasPermission: $this->canEdit,
                        dataField: 'external_ip',
                        fallback: 'N/A',
                        saveOnMouseOut: true
                    );
        $column[]=Column::make(__('branches.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(__('branches.actions'));
        return $column;
    }
    #[On('synchronous.{tableName}')]
    public function synchronous($branch_id): void
    {
       ExportSqliteBranchJob::dispatch($branch_id);
       ExportSqliteSongJob::dispatch($branch_id);
       ExportSqliteFavoriteJob::dispatch($branch_id);
       ExportSqliteUserJob::dispatch(true,$branch_id);

       $this->notification()->send([
            'icon' => 'success',
            'title' => '分店：'.$branch_id,
            'description' => '已經加入排程',
        ]);
    } 
    #[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
    {
       // 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){
        $branch = Branch::find($id);
        if ($branch) {
            $branch->{$field} = $value;
            $branch->save(); // 明確觸發 saving
        }
        $this->notification()->send([
            'icon' => 'success',
            'title' => $id.'.'.__('branches.'.$field).':'.$value,
            'description' => '已經寫入',
        ]);
    }
    public function filters(): array
    {
        return [
            Filter::inputText('name')->placeholder(__('branches.name')),
            Filter::inputText('external_ip')->placeholder(__('branches.external_ip')),
            Filter::boolean('enable')->label('✅', '❌'),
            Filter::datetimepicker('created_at'),
        ];
    }

    public function actions(Branch $row): array
    {
        $actions = [];
        $actions[] = Button::add('room-synchronous')
            ->slot('分店中控同步')
            ->icon('solid-cog')
            ->class('inline-flex items-center gap-1 px-3 py-1 rounded bg-amber-200 text-black')
            ->dispatchTo('modals.branch-sync-modal','openModal', ['branch_id' => $row->id]);
        if ($this->canEdit) {
            $actions[] =Button::add('edit')
                ->slot(__('branches.edit'))
                ->icon('solid-pencil-square')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.branch-form', 'openModal', ['id' => $row->id]);
        }
        if($this->canDelect){
            $actions[] =Button::add('delete')
                ->slot(__('branches.delete'))
                ->icon('solid-trash')
                ->class('inline-flex items-center gap-1 px-3 py-1 rounded ')
                ->dispatchTo('forms.branch-form', 'deleteBranch', ['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(),
        ];
    }
    */
}
