<?php

namespace App\Filament\Resources;

use App\Filament\Resources\HouseUserResource\Pages;
use App\Filament\Resources\HouseUserResource\RelationManagers;
use App\Models\HouseUser;
use App\Models\House;
use App\Models\Room;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ActionsColumn;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Model;




class HouseUserResource extends Resource
{
    protected static ?string $model = HouseUser::class;

    // protected static ?string $navigationLabel = 'Hogar cliente';
    protected static ?string $navigationGroup = 'Gestionar Hogar';
    protected static ?int $navigationSort = 5;

    protected static ?string $navigationIcon = 'heroicon-o-home';

    public static function form(Form $form): Form
    {
        return $form
             ->schema([
              Forms\Components\Select::make('user_id')
                ->label('Cliente')
                ->options(
                    User::role('cliente')
                        ->get()
                        ->mapWithKeys(function ($user) {
                            return [
                                $user->id => $user->ci . ' - ' . $user->name
                            ];
                        })
                )
                ->reactive()
                ->required()
                ->searchable(),

               Forms\Components\Select::make('house_id')
                    ->label('Casa')
                    ->required()
                    ->searchable()
                    ->options(function (callable $get) {
                        $userId = $get('user_id');
                        $currentHouseId = $get('house_id');

                        if (! $userId) {
                            return House::all()->mapWithKeys(function ($house) {
                                return [$house->id => $house->code . ' - ' . $house->name];
                            });
                        }
                        $houseIdsAlreadyAssigned = \DB::table('house_user')
                            ->where('user_id', $userId)
                            ->pluck('house_id')
                            ->toArray();

                        if ($currentHouseId) {
                            $houseIdsAlreadyAssigned = array_diff($houseIdsAlreadyAssigned, [$currentHouseId]);
                        }
                        return House::whereNotIn('id', $houseIdsAlreadyAssigned)
                            ->get()
                            ->mapWithKeys(function ($house) {
                                return [$house->id => $house->code . ' - ' . $house->name];
                            });
                    }),


                Forms\Components\Select::make('role')
                    ->options([
                        'owner' => 'Propietario',
                        // 'guest' => 'Invitado',
                    ])
                    ->required()
                    ->default('guest'),
                Forms\Components\Hidden::make('created_by')
                ->default(auth()->id()),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([

                TextColumn::make('user.name')
                ->label('Cliente'),

                TextColumn::make('house.name')
                ->label('Casa')
                ->searchable()
                ->sortable(),

                TextColumn::make('role')
                ->label('Rol')
                ->badge()
                ->color(fn (string $state): string => match ($state) {
                    'owner' => 'success',
                    'guest' => 'gray',
                    default => 'warning',
                }),

                TextColumn::make('creator.name')
                ->label('Creado por')
                ->searchable(),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListHouseUsers::route('/'),
            'create' => Pages\CreateHouseUser::route('/create'),
            'edit' => Pages\EditHouseUser::route('/{record}/edit'),
        ];
    }



    public static function getPluralModelLabel(): string
    {
        return 'Hogar Cliente';
    }



    /////// para restriguir con los roles y permiso de spaty

    public static function canViewAny(): bool
    {
        return auth()->user()?->can('hogar_usuario.user.view');
    }

    public static function canCreate(): bool
    {
        return auth()->user()?->can('hogar_usuario.user.create');
    }

    public static function canEdit(Model $record): bool
    {
        return auth()->user()?->can('hogar_usuario.user.update');
    }

    public static function canDelete(Model $record): bool
    {
        return auth()->user()?->can('hogar_usuario.user.delete');
    }

    //////




    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->where('status', 1)->with(['user','house','creator']);
    }

}
