<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserDeviceResource\Pages;
use App\Models\UserDevice;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Infolists;
use Filament\Infolists\Infolist;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class UserDeviceResource extends Resource
{
    protected static ?string $model = UserDevice::class;

    protected static ?string $navigationIcon = 'heroicon-o-device-phone-mobile';

    protected static ?string $navigationGroup = 'Approval';

    protected static ?string $navigationLabel = 'Perangkat User';

    protected static ?int $navigationSort = 2;

    protected static ?string $modelLabel = 'Perangkat';

    protected static ?string $pluralModelLabel = 'Perangkat User';

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('status', 'pending')->count() ?: null;
    }

    public static function getNavigationBadgeColor(): ?string
    {
        return 'warning';
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Device')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->label('User')
                            ->relationship('user', 'name')
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(),
                        Forms\Components\TextInput::make('device_id')
                            ->label('Device ID')
                            ->disabled(),
                        Forms\Components\TextInput::make('device_brand')
                            ->label('Merek')
                            ->disabled(),
                        Forms\Components\TextInput::make('device_model')
                            ->label('Model')
                            ->disabled(),
                        Forms\Components\TextInput::make('os_version')
                            ->label('Versi OS')
                            ->disabled(),
                        Forms\Components\TextInput::make('app_version')
                            ->label('Versi Aplikasi')
                            ->disabled(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Status Approval')
                    ->schema([
                        Forms\Components\ToggleButtons::make('status')
                            ->label('Status')
                            ->options([
                                'pending' => 'Menunggu',
                                'approved' => 'Disetujui',
                                'rejected' => 'Ditolak',
                            ])
                            ->icons([
                                'pending' => 'heroicon-o-clock',
                                'approved' => 'heroicon-o-check-circle',
                                'rejected' => 'heroicon-o-x-circle',
                            ])
                            ->colors([
                                'pending' => 'warning',
                                'approved' => 'success',
                                'rejected' => 'danger',
                            ])
                            ->inline()
                            ->disabled(),
                        Forms\Components\Textarea::make('rejection_reason')
                            ->label('Alasan Penolakan')
                            ->visible(fn ($get) => $get('status') === 'rejected'),
                        Forms\Components\Toggle::make('is_primary')
                            ->label('Perangkat Utama')
                            ->helperText('Tandai sebagai perangkat utama user'),
                    ])
                    ->columns(1),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('user.name')
                    ->label('Nama User')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.employee_id')
                    ->label('NIP/ID')
                    ->searchable()
                    ->toggleable(),
                Tables\Columns\TextColumn::make('user.company.name')
                    ->label('Perusahaan')
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('formatted_name')
                    ->label('Perangkat')
                    ->description(fn (UserDevice $record): string => $record->os_version ?? ''),
                Tables\Columns\TextColumn::make('device_id')
                    ->label('Device ID')
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->copyable()
                    ->limit(20),
                Tables\Columns\TextColumn::make('app_version')
                    ->label('Versi App')
                    ->toggleable(),
                Tables\Columns\BadgeColumn::make('status')
                    ->label('Status')
                    ->colors([
                        'warning' => 'pending',
                        'success' => 'approved',
                        'danger' => 'rejected',
                    ])
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'pending' => 'Menunggu',
                        'approved' => 'Disetujui',
                        'rejected' => 'Ditolak',
                        default => $state,
                    }),
                Tables\Columns\IconColumn::make('is_primary')
                    ->label('Utama')
                    ->boolean()
                    ->trueIcon('heroicon-o-star')
                    ->falseIcon('heroicon-o-minus')
                    ->trueColor('warning'),
                Tables\Columns\TextColumn::make('last_used_at')
                    ->label('Terakhir Digunakan')
                    ->dateTime('d M Y H:i')
                    ->sortable()
                    ->toggleable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Terdaftar')
                    ->dateTime('d M Y H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('created_at', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('Status')
                    ->options([
                        'pending' => 'Menunggu Approval',
                        'approved' => 'Disetujui',
                        'rejected' => 'Ditolak',
                    ]),
                Tables\Filters\TernaryFilter::make('is_primary')
                    ->label('Perangkat Utama'),
                Tables\Filters\SelectFilter::make('company')
                    ->label('Perusahaan')
                    ->relationship('user.company', 'name'),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\Action::make('approve')
                        ->label('Setujui')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->visible(fn (UserDevice $record): bool => $record->status === 'pending')
                        ->requiresConfirmation()
                        ->modalHeading('Setujui Perangkat')
                        ->modalDescription(fn (UserDevice $record): string =>
                            "Apakah Anda yakin ingin menyetujui perangkat {$record->formatted_name} milik {$record->user->name}?")
                        ->action(function (UserDevice $record) {
                            $record->approve(auth()->id());

                            Notification::make()
                                ->success()
                                ->title('Perangkat Disetujui')
                                ->body("Perangkat {$record->formatted_name} berhasil disetujui")
                                ->send();
                        }),
                    Tables\Actions\Action::make('reject')
                        ->label('Tolak')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->visible(fn (UserDevice $record): bool => $record->status === 'pending')
                        ->form([
                            Forms\Components\Textarea::make('reason')
                                ->label('Alasan Penolakan')
                                ->placeholder('Masukkan alasan penolakan...')
                                ->required(),
                        ])
                        ->action(function (UserDevice $record, array $data) {
                            $record->reject(auth()->id(), $data['reason']);

                            Notification::make()
                                ->warning()
                                ->title('Perangkat Ditolak')
                                ->body("Perangkat {$record->formatted_name} berhasil ditolak")
                                ->send();
                        }),
                    Tables\Actions\Action::make('setPrimary')
                        ->label('Jadikan Utama')
                        ->icon('heroicon-o-star')
                        ->color('warning')
                        ->visible(fn (UserDevice $record): bool =>
                            $record->status === 'approved' && !$record->is_primary)
                        ->requiresConfirmation()
                        ->action(function (UserDevice $record) {
                            $record->setAsPrimary();

                            Notification::make()
                                ->success()
                                ->title('Perangkat Utama Diubah')
                                ->body("Perangkat {$record->formatted_name} dijadikan perangkat utama")
                                ->send();
                        }),
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\DeleteAction::make()
                        ->visible(fn (UserDevice $record): bool => $record->status !== 'approved'),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\BulkAction::make('approveSelected')
                        ->label('Setujui Terpilih')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->action(function ($records) {
                            $count = 0;
                            foreach ($records as $record) {
                                if ($record->status === 'pending') {
                                    $record->approve(auth()->id());
                                    $count++;
                                }
                            }

                            Notification::make()
                                ->success()
                                ->title('Bulk Approval Berhasil')
                                ->body("{$count} perangkat berhasil disetujui")
                                ->send();
                        }),
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Section::make('Informasi User')
                    ->schema([
                        Infolists\Components\TextEntry::make('user.name')
                            ->label('Nama'),
                        Infolists\Components\TextEntry::make('user.employee_id')
                            ->label('NIP/ID'),
                        Infolists\Components\TextEntry::make('user.company.name')
                            ->label('Perusahaan'),
                        Infolists\Components\TextEntry::make('user.department')
                            ->label('Departemen'),
                    ])
                    ->columns(2),

                Infolists\Components\Section::make('Informasi Perangkat')
                    ->schema([
                        Infolists\Components\TextEntry::make('device_id')
                            ->label('Device ID')
                            ->copyable(),
                        Infolists\Components\TextEntry::make('formatted_name')
                            ->label('Nama Perangkat'),
                        Infolists\Components\TextEntry::make('device_brand')
                            ->label('Merek'),
                        Infolists\Components\TextEntry::make('device_model')
                            ->label('Model'),
                        Infolists\Components\TextEntry::make('os_version')
                            ->label('Versi OS'),
                        Infolists\Components\TextEntry::make('app_version')
                            ->label('Versi Aplikasi'),
                    ])
                    ->columns(2),

                Infolists\Components\Section::make('Status & Approval')
                    ->schema([
                        Infolists\Components\TextEntry::make('status')
                            ->label('Status')
                            ->badge()
                            ->color(fn (string $state): string => match ($state) {
                                'pending' => 'warning',
                                'approved' => 'success',
                                'rejected' => 'danger',
                                default => 'gray',
                            })
                            ->formatStateUsing(fn (string $state): string => match ($state) {
                                'pending' => 'Menunggu',
                                'approved' => 'Disetujui',
                                'rejected' => 'Ditolak',
                                default => $state,
                            }),
                        Infolists\Components\IconEntry::make('is_primary')
                            ->label('Perangkat Utama')
                            ->boolean()
                            ->trueIcon('heroicon-o-star')
                            ->falseIcon('heroicon-o-minus')
                            ->trueColor('warning'),
                        Infolists\Components\TextEntry::make('approver.name')
                            ->label('Diproses Oleh'),
                        Infolists\Components\TextEntry::make('approved_at')
                            ->label('Tanggal Proses')
                            ->dateTime('d M Y H:i'),
                        Infolists\Components\TextEntry::make('rejection_reason')
                            ->label('Alasan Penolakan')
                            ->visible(fn ($record) => $record->status === 'rejected')
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                Infolists\Components\Section::make('Aktivitas')
                    ->schema([
                        Infolists\Components\TextEntry::make('last_used_at')
                            ->label('Terakhir Digunakan')
                            ->dateTime('d M Y H:i'),
                        Infolists\Components\TextEntry::make('created_at')
                            ->label('Terdaftar')
                            ->dateTime('d M Y H:i'),
                    ])
                    ->columns(2),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListUserDevices::route('/'),
            'view' => Pages\ViewUserDevice::route('/{record}'),
        ];
    }

    public static function getEloquentQuery(): \Illuminate\Database\Eloquent\Builder
    {
        $query = parent::getEloquentQuery();

        // Selalu hide super_admin (using Spatie roles)
        $query->whereHas('user', function ($q) {
            $q->whereDoesntHave('roles', function ($r) {
                $r->where('name', 'super_admin');
            });
        });

        // Admin biasa hanya lihat company mereka
        $user = auth()->user();
        if ($user && !$user->hasRole('super_admin')) {
            $query->whereHas('user', function ($q) use ($user) {
                $q->where('company_id', $user->company_id);
            });
        }

        return $query;
    }
}
