<?php

namespace App\Http\Livewire;

use Closure;
use Livewire\Component;
use App\Models\User;
use Laravel\Scout\Searchable;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\CheckboxColumn;
use Filament\Tables\Actions\Action;
use Filament\Tables\Actions\EditAction;
use Filament\Tables\Actions\DeleteAction;
use Filament\Tables\Actions\DeleteBulkAction;
use Filament\Tables\Actions;
use Filament\Notifications\Notification;
use Filament\Forms;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Filament\Tables\Filters\SelectFilter;

//https://filamentphp.com/docs/2.x/tables/columns/getting-started
class Usertable extends Component implements Tables\Contracts\HasTable
{
    use Tables\Concerns\InteractsWithTable;

    protected function getTableQuery(): Builder
    {
        if (Auth::user()->hasRole('super-admin')) {
            $query = User::with('roles');
        } else {
            $query = User::with('roles')
            ->where(function ($q) {
                $q->orWhereDoesntHave('roles')
                    ->orWhereHas('roles', function ($subquery) {
                        $subquery->where('name', '!=', 'super-admin');
                    });
            });
        }

        return $query;
    }

    protected function getTableColumns(): array
    {
        return [
            TextColumn::make('name')->sortable(),
            TextColumn::make('email')->sortable(),
            TextColumn::make('roles.name')->sortable()
            ->view('tables.columns.custom-rolecolumn'),
            TextColumn::make('department')->sortable()
            ->view('tables.columns.custom-department-column'),
            TextColumn::make('phone')
            ->view('tables.columns.custom-phone-column'),
        ];
    }

    protected function getTableFilters(): array
    {
        $query = Role::all();
        // dd($query);
        $rolesArray = $query->pluck('name')->unique()->toArray();
        $rolesIDArray = $query->pluck('id')->unique()->toArray();

        return [
            SelectFilter::make('Roles')
                ->options(array_combine($rolesIDArray, $rolesArray))
                ->attribute('roles.id')
        ];
    }

    protected function getTableActions(): array
    {
        $data_id = (fn (User $record)=> $record->id);
        $data_name =(fn (User $record)=> $record->name);
        return [
            Tables\Actions\ActionGroup::make([
                EditAction::make()
                ->url(fn (User $record): string => route('admin.users.edit', $record->id))
                ->visible(fn (User $record) => auth()->user()->can('user-edit', $record))
                ->size("md"),

                Action::make('Delete')
                ->extraAttributes(fn (User $record) => [
                    'class' => 'delete btn btn-danger-light-danger btn-active-danger',
                    'data-id' => $data_id($record),
                    'data-name' => $data_name($record),
                ])
                ->icon('heroicon-s-trash')
                ->color('danger')
                ->visible(fn (User $record) => auth()->user()->can('user-delete', $record) &&
                $record->id != "1" &&
                auth()->user()->name != $record->name
                )
                ,
            ]),

        ];
    }

    // protected function getTableBulkActions(): array
    // {
    //     $data_id = (fn (User $record)=> $record->id);
    //     $data_name =(fn (User $record)=> $record->name);
    //     return [
    //         Tables\Actions\BulkAction::make('Delete')
    //         ->extraAttributes(fn (User $record) => [
    //             'class' => 'delete btn btn-danger-light-danger btn-active-danger text-danger',
    //             'data-id' => $data_id($record),
    //             'data-name' => $data_name($record),
    //         ])
    //         ->icon('heroicon-s-trash')
    //         ->color('danger')
    //         ->visible(fn (User $record) => auth()->user()->can('user-delete', $record) &&
    //         $record->id != "1" &&
    //         auth()->user()->name != "$record->name"
    //         )
    //     ];
    // }

    protected function isTablePaginationEnabled(): bool
    {
        return true;
    }

    protected function getTableRecordsPerPageSelectOptions(): array
    {
        return [5, 10, 25, 50];
    }

    public function isTableSearchable(): bool
    {
        return true;
    }

    protected function applySearchToTableQuery(Builder $query): Builder
    {
        if (filled($searchQuery = $this->getTableSearchQuery())) {
            $query->whereIn('id', User::search($searchQuery)->keys());
        }

        return $query;
    }

    protected function getTableRecordUrlUsing(): ?Closure
    {
        return fn (User $record): string => route('admin.users.show', $record->id);
    }

    public function render()
    {
        // dd(fn (User $record) => auth()->user()->name != "$record->name");
        return view('livewire.usertable');
    }
}
