<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ActivityAssignmentRuleResource\Pages;
use App\Models\ActivityAssignmentRule;
use App\Models\User;
use App\Services\ActivityAssignmentService;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class ActivityAssignmentRuleResource extends Resource
{
    protected static ?string $model = ActivityAssignmentRule::class;

    protected static ?string $navigationIcon = 'heroicon-o-clipboard-document-check';

    protected static ?string $navigationGroup = 'Pengaturan';

    protected static ?string $navigationLabel = 'Aturan Aktivitas Wajib';

    protected static ?string $modelLabel = 'Aturan Aktivitas';

    protected static ?string $pluralModelLabel = 'Aturan Aktivitas';

    protected static ?int $navigationSort = 10;

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

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Konfigurasi Aturan')
                    ->description('Tentukan karyawan mana yang wajib mengisi aktivitas harian')
                    ->schema([
                        Forms\Components\Select::make('rule_type')
                            ->label('Tipe Aturan')
                            ->options([
                                'all_users' => 'Semua Karyawan',
                                'specific_users' => 'Karyawan Tertentu',
                                'departments' => 'Berdasarkan Departemen',
                                'positions' => 'Berdasarkan Jabatan',
                            ])
                            ->required()
                            ->native(false)
                            ->live()
                            ->afterStateUpdated(fn (Forms\Set $set) => $set('target_values', [])),

                        Forms\Components\Select::make('target_values')
                            ->label('Pilih Karyawan')
                            ->multiple()
                            ->options(function () {
                                $user = Auth::user();
                                return User::where('company_id', $user->company_id)
                                    ->where('is_active', true)
                                    ->pluck('name', 'id');
                            })
                            ->searchable()
                            ->preload()
                            ->visible(fn (Get $get): bool => $get('rule_type') === 'specific_users')
                            ->required(fn (Get $get): bool => $get('rule_type') === 'specific_users'),

                        Forms\Components\TagsInput::make('target_values')
                            ->label('Nama Departemen')
                            ->placeholder('Ketik nama departemen dan tekan Enter')
                            ->suggestions(function () {
                                $user = Auth::user();
                                return User::where('company_id', $user->company_id)
                                    ->whereNotNull('department')
                                    ->where('department', '!=', '')
                                    ->distinct()
                                    ->pluck('department')
                                    ->toArray();
                            })
                            ->visible(fn (Get $get): bool => $get('rule_type') === 'departments')
                            ->required(fn (Get $get): bool => $get('rule_type') === 'departments'),

                        Forms\Components\TagsInput::make('target_values')
                            ->label('Nama Jabatan')
                            ->placeholder('Ketik nama jabatan dan tekan Enter')
                            ->suggestions(function () {
                                $user = Auth::user();
                                return User::where('company_id', $user->company_id)
                                    ->whereNotNull('position')
                                    ->where('position', '!=', '')
                                    ->distinct()
                                    ->pluck('position')
                                    ->toArray();
                            })
                            ->visible(fn (Get $get): bool => $get('rule_type') === 'positions')
                            ->required(fn (Get $get): bool => $get('rule_type') === 'positions'),

                        Forms\Components\Select::make('frequency')
                            ->label('Frekuensi')
                            ->options([
                                'daily' => 'Harian',
                                'weekly' => 'Mingguan',
                            ])
                            ->default('daily')
                            ->native(false),

                        Forms\Components\Toggle::make('is_active')
                            ->label('Aktif')
                            ->default(true)
                            ->inline(false),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('rule_type')
                    ->label('Tipe Aturan')
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'all_users' => 'Semua Karyawan',
                        'specific_users' => 'Karyawan Tertentu',
                        'departments' => 'Departemen',
                        'positions' => 'Jabatan',
                        default => $state,
                    })
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'all_users' => 'primary',
                        'specific_users' => 'info',
                        'departments' => 'warning',
                        'positions' => 'success',
                        default => 'gray',
                    }),

                Tables\Columns\TextColumn::make('description')
                    ->label('Deskripsi')
                    ->wrap(),

                Tables\Columns\TextColumn::make('frequency')
                    ->label('Frekuensi')
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'daily' => 'Harian',
                        'weekly' => 'Mingguan',
                        default => $state,
                    })
                    ->badge()
                    ->color('gray'),

                Tables\Columns\IconColumn::make('is_active')
                    ->label('Status')
                    ->boolean()
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),

                Tables\Columns\TextColumn::make('affected_users_count')
                    ->label('Jumlah User')
                    ->getStateUsing(function ($record) {
                        $service = app(ActivityAssignmentService::class);
                        return $service->previewRuleEffect(
                            $record->company,
                            $record->rule_type,
                            $record->target_values
                        )->count();
                    })
                    ->badge()
                    ->color('info'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Dibuat')
                    ->dateTime('d M Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('rule_type')
                    ->label('Tipe Aturan')
                    ->options([
                        'all_users' => 'Semua Karyawan',
                        'specific_users' => 'Karyawan Tertentu',
                        'departments' => 'Departemen',
                        'positions' => 'Jabatan',
                    ])
                    ->native(false),

                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Status Aktif'),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make()
                        ->icon('heroicon-o-eye'),

                    Tables\Actions\EditAction::make()
                        ->icon('heroicon-o-pencil-square'),

                    Tables\Actions\Action::make('toggle')
                        ->label(fn ($record) => $record->is_active ? 'Nonaktifkan' : 'Aktifkan')
                        ->icon(fn ($record) => $record->is_active ? 'heroicon-o-pause' : 'heroicon-o-play')
                        ->color(fn ($record) => $record->is_active ? 'warning' : 'success')
                        ->requiresConfirmation()
                        ->action(function ($record) {
                            $record->update(['is_active' => !$record->is_active]);

                            Notification::make()
                                ->success()
                                ->title('Status Diubah')
                                ->body('Aturan berhasil ' . ($record->is_active ? 'diaktifkan' : 'dinonaktifkan'))
                                ->send();
                        }),

                    Tables\Actions\DeleteAction::make(),
                ])
                    ->icon('heroicon-m-ellipsis-vertical')
                    ->tooltip('Aksi'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\BulkAction::make('activate')
                        ->label('Aktifkan Terpilih')
                        ->icon('heroicon-o-play')
                        ->color('success')
                        ->action(function ($records) {
                            $records->each->update(['is_active' => true]);

                            Notification::make()
                                ->success()
                                ->title('Aturan Diaktifkan')
                                ->body(count($records) . ' aturan berhasil diaktifkan')
                                ->send();
                        }),

                    Tables\Actions\BulkAction::make('deactivate')
                        ->label('Nonaktifkan Terpilih')
                        ->icon('heroicon-o-pause')
                        ->color('warning')
                        ->action(function ($records) {
                            $records->each->update(['is_active' => false]);

                            Notification::make()
                                ->success()
                                ->title('Aturan Dinonaktifkan')
                                ->body(count($records) . ' aturan berhasil dinonaktifkan')
                                ->send();
                        }),

                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();
        $user = Auth::user();

        // Filter by company for non-super admin
        if ($user && !$user->hasRole('super_admin')) {
            $query->where('company_id', $user->company_id);
        }

        return $query;
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListActivityAssignmentRules::route('/'),
            'create' => Pages\CreateActivityAssignmentRule::route('/create'),
            'view' => Pages\ViewActivityAssignmentRule::route('/{record}'),
            'edit' => Pages\EditActivityAssignmentRule::route('/{record}/edit'),
        ];
    }
}
