<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource\RelationManagers;
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 Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;

class UserResource extends Resource
{
    protected static ?string $model = User::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationGroup = 'Pengaturan';
    protected static ?string $navigationLabel = 'Akun';
    protected static ?int $navigationSort = 1;


    public static function shouldRegisterNavigation(): bool
    {
        if (Auth::user()->role !== 'kepala_desa' && Auth::user()->role !== 'admin_dusun') {
            return true;
        } else {
            return false;
        }
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->placeholder('Masukan nama user')
                    ->required()
                    ->maxLength(255),
                Forms\Components\TextInput::make('email')
                    ->email()
                    ->required()
                    ->maxLength(255),
                Forms\Components\Select::make('dusun_id')
                // ->relationship(
                //     name: 'dusun',
                //     titleAttribute: 'nama',
                //     modifyQueryUsing: function ($query) {
                //         $usedDusunIds = \App\Models\User::whereNotNull('dusun_id')
                //             ->pluck('dusun_id')
                //             ->toArray();
            
                //         $query->whereNotIn('id', $usedDusunIds);
                //     }
                // )
                ->relationship('dusun', 'nama')
                ->label('Dusun')
                ->required(),
                Forms\Components\Select::make('role')
                    ->options([
                        'admin_dusun' => 'Admin Dusun',
                        'admin_desa' => 'Admin desa',
                        'kepala_desa' => 'Kepala desa',
                        ])
                        ->required(),
                Forms\Components\Toggle::make('is_approved')
                    ->label('Disetujui?')
                    ->default(true)
                    ->helperText('Centang untuk menyetujui akun ini.')
                    ->required(),
                Forms\Components\TextInput::make('password')
                    ->placeholder('Masukan password user')
                    ->password()
                    ->revealable()
                    ->required()
                    ->maxLength(255),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->searchable(),
                Tables\Columns\TextColumn::make('email')
                    ->searchable(),
                Tables\Columns\TextColumn::make('dusun.nama')
                    ->default('-')
                    ->label('Dusun')
                    ->sortable(),
                Tables\Columns\TextColumn::make('role')
                    ->sortable(),
                Tables\Columns\IconColumn::make('is_approved')
                    ->label('Disetujui?')
                    ->boolean(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make()->visible(fn (): bool => Auth::user()->role !== 'kepala_desa' && Auth::user()->role !== 'admin_dusun'),
                Tables\Actions\Action::make('approve_single')
                    ->label('Setujui')
                    ->icon('heroicon-o-check')
                    ->color('success')
                    ->hidden(fn (User $record): bool => $record->is_approved || Auth::user()->role === 'warga') // Sembunyikan jika sudah disetujui atau role adalah warga
                    ->requiresConfirmation()
                    ->action(fn (User $record) => $record->update(['is_approved' => true])),
                // Tambahkan aksi individual untuk pembatalan persetujuan
                Tables\Actions\Action::make('disapprove_single')
                    ->label('Batalkan Setuju')
                    ->icon('heroicon-o-x-mark')
                    ->color('warning')
                    ->hidden(fn (User $record): bool => !$record->is_approved || Auth::user()->role === 'warga') // Sembunyikan jika belum disetujui atau role adalah warga
                    ->requiresConfirmation()
                    ->action(fn (User $record) => $record->update(['is_approved' => false])),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()->visible(fn (): bool => Auth::user()->role === 'kepala_desa'),
                    Tables\Actions\BulkAction::make('approve')
                        ->label('Setujui Akun')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->action(function (Collection $records) {
                            $records->each(fn (User $user) => $user->update(['is_approved' => true]));
                        })
                        ->visible(fn (): bool => Auth::user()->role !== 'warga'),
                    Tables\Actions\BulkAction::make('disapprove')
                        ->label('Batalkan Persetujuan')
                        ->icon('heroicon-o-x-circle')
                        ->color('warning')
                        ->requiresConfirmation()
                        ->action(function (Collection $records) {
                            $records->each(fn (User $user) => $user->update(['is_approved' => false]));
                        })
                        ->visible(fn (): bool => Auth::user()->role !== 'warga'),
                ]),
            ]);
    }

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

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

    public static function canAccess(): bool
    {
        return Auth::user()->role !== 'warga';
    }
}
