<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource\RelationManagers;
use App\Models\Company;
use App\Models\Shift;
use App\Models\User;
use App\Models\UserShift;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Infolists;
use Filament\Infolists\Infolist;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Support\Enums\FontWeight;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;

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

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

    protected static ?string $navigationGroup = 'Manajemen User';

    protected static ?int $navigationSort = 1;

    protected static ?string $recordTitleAttribute = 'name';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Informasi Dasar')
                            ->description('Data utama karyawan')
                            ->icon('heroicon-o-user')
                            ->schema([
                                Forms\Components\Select::make('company_id')
                                    ->label('Perusahaan/Instansi')
                                    ->relationship('company', 'name')
                                    ->searchable()
                                    ->preload()
                                    ->required()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-building-office'),
                                Forms\Components\TextInput::make('employee_id')
                                    ->label('ID Karyawan')
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-identification'),
                                Forms\Components\TextInput::make('nip')
                                    ->label('NIP')
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-document-text')
                                    ->helperText('Nomor Induk Pegawai (untuk instansi pemerintah)'),
                                Forms\Components\TextInput::make('name')
                                    ->label('Nama Lengkap')
                                    ->required()
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-user')
                                    ->autofocus(),
                                Forms\Components\TextInput::make('email')
                                    ->email()
                                    ->required()
                                    ->unique(ignoreRecord: true)
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-envelope'),
                                Forms\Components\TextInput::make('phone')
                                    ->label('No. Telepon')
                                    ->tel()
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-phone'),
                            ])
                            ->columns(2)
                            ->collapsible(),

                        Forms\Components\Section::make('Posisi & Jabatan')
                            ->description('Informasi posisi di perusahaan')
                            ->icon('heroicon-o-briefcase')
                            ->schema([
                                Forms\Components\TextInput::make('department')
                                    ->label('Departemen/Unit')
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-building-library'),
                                Forms\Components\TextInput::make('position')
                                    ->label('Jabatan')
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-academic-cap'),
                                Forms\Components\ToggleButtons::make('role')
                                    ->label('Tipe User')
                                    ->options([
                                        'admin' => 'Admin',
                                        'employee' => 'Karyawan',
                                    ])
                                    ->icons([
                                        'admin' => 'heroicon-o-shield-check',
                                        'employee' => 'heroicon-o-user',
                                    ])
                                    ->colors([
                                        'admin' => 'warning',
                                        'employee' => 'success',
                                    ])
                                    ->required()
                                    ->default('employee')
                                    ->inline()
                                    ->grouped(),
                                Forms\Components\Select::make('roles')
                                    ->label('Role Sistem')
                                    ->relationship(
                                        'roles',
                                        'name',
                                        fn ($query) => auth()->user()?->hasRole('super_admin')
                                            ? $query->whereNotIn('name', ['super_admin'])
                                            : $query->whereNotIn('name', ['super_admin', 'admin'])
                                    )
                                    ->multiple()
                                    ->preload()
                                    ->searchable()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-key'),
                            ])
                            ->columns(2)
                            ->collapsible(),

                        Forms\Components\Section::make('Lokasi Rumah')
                            ->description('Koordinat untuk validasi WFH')
                            ->icon('heroicon-o-home')
                            ->schema([
                                Forms\Components\Textarea::make('address')
                                    ->label('Alamat')
                                    ->rows(3)
                                    ->columnSpanFull(),
                                Forms\Components\TextInput::make('home_latitude')
                                    ->label('Latitude Rumah')
                                    ->numeric()
                                    ->step(0.00000001)
                                    ->prefixIcon('heroicon-o-map-pin'),
                                Forms\Components\TextInput::make('home_longitude')
                                    ->label('Longitude Rumah')
                                    ->numeric()
                                    ->step(0.00000001)
                                    ->prefixIcon('heroicon-o-map-pin'),
                            ])
                            ->columns(2)
                            ->collapsible()
                            ->collapsed(),
                    ])
                    ->columnSpan(['lg' => 2]),

                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Foto Profil')
                            ->icon('heroicon-o-camera')
                            ->schema([
                                Forms\Components\FileUpload::make('avatar')
                                    ->label('')
                                    ->image()
                                    ->avatar()
                                    ->imageEditor()
                                    ->circleCropper()
                                    ->directory('avatars')
                                    ->maxSize(2048)
                                    ->columnSpanFull(),
                            ]),

                        Forms\Components\Section::make('Status & Keamanan')
                            ->icon('heroicon-o-shield-check')
                            ->schema([
                                Forms\Components\Toggle::make('is_active')
                                    ->label('Akun Aktif')
                                    ->default(true)
                                    ->onIcon('heroicon-o-check')
                                    ->offIcon('heroicon-o-x-mark')
                                    ->onColor('success')
                                    ->offColor('danger'),
                                Forms\Components\ToggleButtons::make('approval_status')
                                    ->label('Status Approval')
                                    ->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',
                                    ])
                                    ->default('approved')
                                    ->required()
                                    ->inline()
                                    ->columnSpanFull(),
                                Forms\Components\TextInput::make('password')
                                    ->password()
                                    ->revealable()
                                    ->dehydrateStateUsing(fn($state) => filled($state) ? Hash::make($state) : null)
                                    ->dehydrated(fn($state) => filled($state))
                                    ->required(fn(string $operation): bool => $operation === 'create')
                                    ->maxLength(255)
                                    ->prefixIcon('heroicon-o-lock-closed')
                                    ->helperText(fn(string $operation): string => $operation === 'edit' ? 'Kosongkan jika tidak ingin mengubah password' : ''),
                            ]),
                    ])
                    ->columnSpan(['lg' => 1]),
            ])
            ->columns(3);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('avatar')
                    ->label('')
                    ->circular()
                    ->size(40)
                    ->defaultImageUrl(fn($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->name) . '&background=1565C0&color=fff&bold=true'),

                Tables\Columns\TextColumn::make('name')
                    ->label('Nama')
                    ->weight(FontWeight::Bold)
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('email')
                    ->label('Email')
                    ->color('gray')
                    ->searchable(),

                Tables\Columns\TextColumn::make('employee_id')
                    ->label('ID Karyawan')
                    ->placeholder('-')
                    ->searchable(),

                Tables\Columns\TextColumn::make('department')
                    ->label('Departemen')
                    ->placeholder('-')
                    ->searchable(),

                Tables\Columns\TextColumn::make('position')
                    ->label('Jabatan')
                    ->placeholder('-')
                    ->searchable(),

                Tables\Columns\TextColumn::make('company.name')
                    ->label('Perusahaan')
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('roles.name')
                    ->label('Role')
                    ->badge()
                    ->color(fn(string $state): string => match ($state) {
                        'super_admin' => 'danger',
                        'admin' => 'warning',
                        'employee' => 'info',
                        default => 'gray',
                    }),

                Tables\Columns\TextColumn::make('approval_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,
                    }),

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

                Tables\Columns\TextColumn::make('phone')
                    ->label('Telepon')
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Terdaftar')
                    ->since()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('approval_status')
                    ->label('Status Approval')
                    ->options([
                        'pending' => 'Menunggu Approval',
                        'approved' => 'Disetujui',
                        'rejected' => 'Ditolak',
                    ])
                    ->native(false)
                    ->indicator('Status'),
                Tables\Filters\SelectFilter::make('roles')
                    ->label('Role')
                    ->relationship('roles', 'name')
                    ->native(false)
                    ->indicator('Role'),
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Status Aktif')
                    ->indicator('Aktif'),
                Tables\Filters\SelectFilter::make('company_id')
                    ->label('Perusahaan')
                    ->relationship('company', 'name')
                    ->native(false)
                    ->searchable()
                    ->preload()
                    ->indicator('Perusahaan'),
            ])
            ->filtersFormColumns(2)
            ->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('approve')
                        ->label('Approve')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalIcon('heroicon-o-check-circle')
                        ->modalIconColor('success')
                        ->modalHeading('Approve User')
                        ->modalDescription('Apakah Anda yakin ingin menyetujui user ini? User akan dapat mengakses aplikasi setelah disetujui.')
                        ->visible(fn(User $record): bool => $record->approval_status === 'pending' && auth()->user()->canApprove())
                        ->action(function (User $record) {
                            $record->update([
                                'approval_status' => 'approved',
                                'approved_by' => auth()->id(),
                                'approved_at' => now(),
                                'is_active' => true,
                            ]);
                            Notification::make()
                                ->success()
                                ->title('User Disetujui')
                                ->body('User ' . $record->name . ' berhasil disetujui dan sekarang dapat mengakses aplikasi.')
                                ->icon('heroicon-o-check-circle')
                                ->iconColor('success')
                                ->send();
                        }),
                    Tables\Actions\Action::make('reject')
                        ->label('Reject')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->modalIcon('heroicon-o-x-circle')
                        ->modalIconColor('danger')
                        ->form([
                            Forms\Components\Textarea::make('rejection_reason')
                                ->label('Alasan Penolakan')
                                ->placeholder('Jelaskan alasan penolakan...')
                                ->required()
                                ->rows(3),
                        ])
                        ->visible(fn(User $record): bool => $record->approval_status === 'pending' && auth()->user()->canApprove())
                        ->action(function (User $record, array $data) {
                            $record->update([
                                'approval_status' => 'rejected',
                                'rejection_reason' => $data['rejection_reason'],
                                'approved_by' => auth()->id(),
                                'approved_at' => now(),
                                'is_active' => false,
                            ]);
                            Notification::make()
                                ->success()
                                ->title('User Ditolak')
                                ->body('User ' . $record->name . ' telah ditolak.')
                                ->icon('heroicon-o-x-circle')
                                ->iconColor('danger')
                                ->send();
                        }),
                    Tables\Actions\DeleteAction::make()
                        ->icon('heroicon-o-trash'),
                ])
                    ->icon('heroicon-m-ellipsis-vertical')
                    ->tooltip('Aksi'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->icon('heroicon-o-trash'),
                    Tables\Actions\BulkAction::make('approveSelected')
                        ->label('Approve Terpilih')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalIcon('heroicon-o-check-circle')
                        ->modalIconColor('success')
                        ->modalHeading('Approve Users Terpilih')
                        ->modalDescription('Apakah Anda yakin ingin menyetujui semua user yang dipilih?')
                        ->action(function ($records) {
                            $count = 0;
                            $records->each(function ($record) use (&$count) {
                                if ($record->approval_status === 'pending') {
                                    $record->update([
                                        'approval_status' => 'approved',
                                        'approved_by' => auth()->id(),
                                        'approved_at' => now(),
                                        'is_active' => true,
                                    ]);
                                    $count++;
                                }
                            });
                            Notification::make()
                                ->success()
                                ->title('Users Disetujui')
                                ->body($count . ' user berhasil disetujui.')
                                ->icon('heroicon-o-check-circle')
                                ->send();
                        }),
                    Tables\Actions\BulkAction::make('assignShift')
                        ->label('Assign Shift')
                        ->icon('heroicon-o-clock')
                        ->color('primary')
                        ->modalIcon('heroicon-o-clock')
                        ->modalIconColor('primary')
                        ->modalHeading('Assign Shift ke Karyawan Terpilih')
                        ->modalDescription('Pilih shift dan tanggal mulai berlaku. Shift sebelumnya akan otomatis diakhiri.')
                        ->form([
                            Forms\Components\Select::make('shift_id')
                                ->label('Shift')
                                ->options(function () {
                                    $companyId = auth()->user()?->company_id;
                                    return Shift::where('company_id', $companyId)
                                        ->where('is_active', true)
                                        ->get()
                                        ->mapWithKeys(fn($s) => [$s->id => $s->name . ' (' . $s->start_time?->format('H:i') . ' - ' . $s->end_time?->format('H:i') . ')']);
                                })
                                ->required()
                                ->native(false)
                                ->prefixIcon('heroicon-o-clock'),
                            Forms\Components\DatePicker::make('effective_date')
                                ->label('Tanggal Mulai')
                                ->required()
                                ->default(now())
                                ->native(false),
                        ])
                        ->action(function ($records, array $data) {
                            $count = 0;
                            $today = now()->toDateString();

                            $records->each(function ($record) use ($data, $today, &$count) {
                                // End existing active shifts for this user
                                UserShift::where('user_id', $record->id)
                                    ->where(function ($q) use ($today) {
                                        $q->whereNull('end_date')
                                            ->orWhere('end_date', '>=', $today);
                                    })
                                    ->update(['end_date' => $today]);

                                // Create new shift assignment
                                UserShift::create([
                                    'user_id' => $record->id,
                                    'shift_id' => $data['shift_id'],
                                    'effective_date' => $data['effective_date'],
                                    'end_date' => null,
                                ]);

                                $count++;
                            });

                            $shiftName = Shift::find($data['shift_id'])?->name ?? 'Shift';

                            Notification::make()
                                ->success()
                                ->title('Shift Berhasil Diassign')
                                ->body("{$count} karyawan berhasil diassign ke {$shiftName}.")
                                ->icon('heroicon-o-check-circle')
                                ->send();
                        }),
                    Tables\Actions\BulkAction::make('deactivateSelected')
                        ->label('Nonaktifkan Terpilih')
                        ->icon('heroicon-o-no-symbol')
                        ->color('warning')
                        ->requiresConfirmation()
                        ->modalIcon('heroicon-o-exclamation-triangle')
                        ->modalIconColor('warning')
                        ->action(function ($records) {
                            $records->each(fn($record) => $record->update(['is_active' => false]));
                            Notification::make()
                                ->success()
                                ->title('Users Dinonaktifkan')
                                ->body($records->count() . ' user telah dinonaktifkan.')
                                ->send();
                        }),
                ]),
            ])
            ->defaultSort('created_at', 'desc')
            ->striped()
            ->poll('30s');
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Section::make()
                    ->schema([
                        Infolists\Components\Split::make([
                            Infolists\Components\ImageEntry::make('avatar')
                                ->label('')
                                ->circular()
                                ->size(120)
                                ->defaultImageUrl(fn($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->name) . '&background=3b82f6&color=fff&bold=true&size=120')
                                ->grow(false),
                            Infolists\Components\Group::make([
                                Infolists\Components\TextEntry::make('name')
                                    ->label('')
                                    ->size('lg')
                                    ->weight(FontWeight::Bold),
                                Infolists\Components\TextEntry::make('email')
                                    ->label('')
                                    ->icon('heroicon-o-envelope')
                                    ->iconColor('primary'),
                                Infolists\Components\TextEntry::make('phone')
                                    ->label('')
                                    ->icon('heroicon-o-phone')
                                    ->iconColor('success')
                                    ->placeholder('-'),
                            ]),
                        ])->from('md'),
                    ]),

                Infolists\Components\Section::make('Informasi Pekerjaan')
                    ->icon('heroicon-o-briefcase')
                    ->schema([
                        Infolists\Components\TextEntry::make('company.name')
                            ->label('Perusahaan')
                            ->icon('heroicon-o-building-office'),
                        Infolists\Components\TextEntry::make('employee_id')
                            ->label('ID Karyawan')
                            ->icon('heroicon-o-identification'),
                        Infolists\Components\TextEntry::make('nip')
                            ->label('NIP')
                            ->icon('heroicon-o-document-text')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('department')
                            ->label('Departemen')
                            ->icon('heroicon-o-building-library')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('position')
                            ->label('Jabatan')
                            ->icon('heroicon-o-academic-cap')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('roles.name')
                            ->label('Role')
                            ->badge()
                            ->color(fn(string $state): string => match ($state) {
                                'super_admin' => 'danger',
                                'admin' => 'warning',
                                default => 'info',
                            }),
                    ])
                    ->columns(3),

                Infolists\Components\Section::make('Status')
                    ->icon('heroicon-o-shield-check')
                    ->schema([
                        Infolists\Components\IconEntry::make('is_active')
                            ->label('Status Aktif')
                            ->boolean()
                            ->trueIcon('heroicon-o-check-circle')
                            ->falseIcon('heroicon-o-x-circle')
                            ->trueColor('success')
                            ->falseColor('danger'),
                        Infolists\Components\TextEntry::make('approval_status')
                            ->label('Status Approval')
                            ->badge()
                            ->color(fn(string $state): string => match ($state) {
                                'pending' => 'warning',
                                'approved' => 'success',
                                'rejected' => 'danger',
                                default => 'gray',
                            }),
                        Infolists\Components\TextEntry::make('approver.name')
                            ->label('Disetujui Oleh')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('approved_at')
                            ->label('Tanggal Approval')
                            ->dateTime('d M Y H:i')
                            ->placeholder('-'),
                    ])
                    ->columns(4),

                Infolists\Components\Section::make('Lokasi')
                    ->icon('heroicon-o-map-pin')
                    ->schema([
                        Infolists\Components\TextEntry::make('address')
                            ->label('Alamat')
                            ->columnSpanFull()
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('home_latitude')
                            ->label('Latitude')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('home_longitude')
                            ->label('Longitude')
                            ->placeholder('-'),
                    ])
                    ->columns(2)
                    ->collapsible(),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\UserShiftsRelationManager::class,
        ];
    }

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

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

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

    public static function getGloballySearchableAttributes(): array
    {
        return ['name', 'email', 'employee_id', 'nip', 'department', 'position'];
    }

    public static function getGlobalSearchResultDetails($record): array
    {
        return [
            'Email' => $record->email,
            'Departemen' => $record->department ?? '-',
            'Jabatan' => $record->position ?? '-',
        ];
    }

    /**
     * Hide super_admin from all user lists
     * Hide admin users from non-super_admin (untuk keamanan audit)
     */
    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();

        // Always hide super_admin from list (using Spatie roles)
        $query->whereDoesntHave('roles', function ($q) {
            $q->where('name', 'super_admin');
        });

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

            // Admin biasa tidak boleh melihat user dengan role admin (keamanan audit)
            $query->whereDoesntHave('roles', function ($q) {
                $q->where('name', 'admin');
            });
        }

        return $query;
    }
}
