<?php

namespace App\Filament\Resources;

use App\Filament\Resources\RoomResource\Pages;
use App\Filament\Resources\RoomResource\RelationManagers;
use App\Models\Room;
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\IconColumn;
use Illuminate\Support\Str;
use Filament\Tables\Actions\Action;
use Illuminate\Database\Eloquent\Model;



class RoomResource extends Resource
{
    protected static ?string $model = Room::class;

    protected static ?string $navigationIcon = 'heroicon-o-building-library';
    // protected static ?string $navigationLabel = 'Ambientes';
    protected static ?string $navigationGroup = 'Gestionar Hogar';
        protected static ?int $navigationSort = 6;


    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\TextInput::make('name')->label('Nombre')->required(),
            Forms\Components\Select::make('type')
                ->label('Tipo')
                ->options([
                    'living_room' => 'Sala',
                    'kitchen' => 'Cocina',
                    'bedroom' => 'Dormitorio',
                    'bathroom' => 'Baño',
                    'dining_room' => 'Comedor',
                    'office' => 'Oficina',
                    'garage' => 'Garaje',
                    'garden' => 'Jardín',
                    'other' => 'Otro',
                ])
                ->required(),
            // Forms\Components\TextInput::make('identifier')->label('Identificador único')->required(),
            Forms\Components\TextInput::make('floor')->label('Piso')->default(0),
            Forms\Components\Textarea::make('description')->label('Descripción')->nullable(),
            Forms\Components\Select::make('house_id')
                ->label('Casa asociada')
                ->relationship('house', 'name') // relación house() en el modelo Room
                ->required(),
            Forms\Components\Toggle::make('status')->label('Estado')->default(true),

        ]);
    }

public static function table(Table $table): Table
{
    return $table
        ->columns([
            Tables\Columns\TextColumn::make('house.name')
                ->label('Hogar')
                ->searchable()
                ->sortable(),

            Tables\Columns\TextColumn::make('name')->label('Ambiente'),
            Tables\Columns\TextColumn::make('type')
                ->label('Tipo')
                ->formatStateUsing(function ($state) {
                    $types = [
                        'living_room' => 'Sala',
                        'kitchen' => 'Cocina',
                        'bedroom' => 'Dormitorio',
                        'bathroom' => 'Baño',
                        'dining_room' => 'Comedor',
                        'office' => 'Oficina',
                        'garage' => 'Garaje',
                        'garden' => 'Jardín',
                        'other' => 'Otro',
                    ];

                    return $types[$state] ?? $state;
                }),
            Tables\Columns\TextColumn::make('floor')->label('Piso'),
            Tables\Columns\IconColumn::make('status')->label('Activo')->boolean(),
        ])
        ->actions([
            // Tables\Actions\EditAction::make(),
            // Tables\Actions\DeleteAction::make(),

            Action::make('crear_dispositivo')
                ->label('Crear dispositivo')
                ->icon('heroicon-o-plus')
                ->form([
                    Forms\Components\Select::make('device_type_id')
                        ->label('Tipo de dispositivo')
                        ->options(\App\Models\DeviceType::where('status', 1)->pluck('name', 'id'))
                        ->required()
                        ->reactive()
                        ->afterStateUpdated(fn (callable $set) => $set('device_family_id', null))
                        ->columnSpan('full'),

                    Forms\Components\Select::make('device_family_id')
                        ->label('Familia')
                        ->options(function (callable $get) {
                            $deviceTypeId = $get('device_type_id');
                            if (!$deviceTypeId) {
                                return [];
                            }
                            return \App\Models\DeviceFamily::where('device_type_id', $deviceTypeId)
                                ->where('status', 1)
                                ->pluck('name', 'id');
                        })
                        ->required()
                        ->reactive()
                        ->afterStateUpdated(fn (callable $set) => $set('device_model_id', null))
                        ->disabled(fn (callable $get) => !$get('device_type_id'))
                        ->columnSpan('full'),

                    Forms\Components\Select::make('device_model_id')
                        ->label('Modelo')
                        ->options(function (callable $get) {
                            $familyId = $get('device_family_id');
                            if (!$familyId) {
                                return [];
                            }
                            return \App\Models\DeviceModel::where('device_family_id', $familyId)
                                ->where('status', 1)
                                ->pluck('name', 'id');
                        })
                        ->required()
                        ->disabled(fn (callable $get) => !$get('device_family_id'))
                        ->columnSpan('full'),

                    Forms\Components\TextInput::make('name')
                        ->label('Nombre del dispositivo')
                        ->required()
                        ->columnSpan('full'),

                    Forms\Components\Toggle::make('status')
                        ->label('Activo')
                        ->default(true)
                        ->columnSpan('full'),

                    // Pasamos room_id automáticamente al crear
                    Forms\Components\Hidden::make('room_id')
                        ->default(fn ($record) => $record->id),

                    // Pasamos house_id automáticamente al crear
                    Forms\Components\Hidden::make('house_id')
                        ->default(fn ($record) => $record->house_id),
                ])
                ->action(function (array $data) {
                    \App\Models\Device::create([
                        'name' => $data['name'],
                        'device_model_id' => $data['device_model_id'],
                        'room_id' => $data['room_id'],
                        'house_id' => $data['house_id'],
                        'status' => $data['status'],
                        'device_id' => \Str::uuid(),
                        'secret_key' => \Str::random(24),
                        'created_by' => auth()->id(),
                    ]);
                })
                ->modalHeading('Crear nuevo dispositivo')
                ->modalSubmitActionLabel('Crear')
                ->color('success'),
        ])
        ->filters([
            //
        ])
        ->bulkActions([
            // Tables\Actions\BulkActionGroup::make([
            //     Tables\Actions\DeleteBulkAction::make(),
            // ]),
        ]);
}




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

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

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

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

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

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->where('status', 1);

    }


}
