<?php

namespace App\Filament\Resources;

use App\Filament\Resources\EmployeeCardResource\Pages;
use App\Models\EmployeeCard;
use App\Models\User;
use App\Services\CardPdfService;
use App\Services\QrCardService;
use Filament\Forms;
use Filament\Forms\Form;
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 EmployeeCardResource extends Resource
{
    protected static ?string $model = EmployeeCard::class;

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

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

    protected static ?string $navigationLabel = 'Kartu Karyawan';

    protected static ?string $modelLabel = 'Kartu Karyawan';

    protected static ?string $pluralModelLabel = 'Kartu Karyawan';

    protected static ?int $navigationSort = 3;

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

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Kartu')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->label('Karyawan')
                            ->relationship('user', 'name')
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(),

                        Forms\Components\TextInput::make('card_number')
                            ->label('Nomor Kartu')
                            ->disabled(),

                        Forms\Components\Select::make('card_status')
                            ->label('Status')
                            ->options([
                                'active' => 'Aktif',
                                'revoked' => 'Dicabut',
                                'expired' => 'Kadaluarsa',
                            ])
                            ->disabled(),

                        Forms\Components\DateTimePicker::make('issued_at')
                            ->label('Tanggal Terbit')
                            ->disabled(),

                        Forms\Components\DateTimePicker::make('expires_at')
                            ->label('Tanggal Kadaluarsa')
                            ->disabled(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Informasi Pencabutan')
                    ->schema([
                        Forms\Components\DateTimePicker::make('revoked_at')
                            ->label('Tanggal Dicabut')
                            ->disabled(),

                        Forms\Components\Textarea::make('revoked_reason')
                            ->label('Alasan Pencabutan')
                            ->disabled()
                            ->columnSpanFull(),
                    ])
                    ->columns(2)
                    ->visible(fn ($record) => $record?->card_status === 'revoked'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('card_number')
                    ->label('No. Kartu')
                    ->searchable()
                    ->sortable()
                    ->copyable(),

                Tables\Columns\ImageColumn::make('user.avatar')
                    ->label('')
                    ->circular()
                    ->size(40)
                    ->defaultImageUrl(fn ($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->user?->name ?? 'N')),

                Tables\Columns\TextColumn::make('user.name')
                    ->label('Nama Karyawan')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('user.employee_id')
                    ->label('NIP')
                    ->searchable(),

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

                Tables\Columns\TextColumn::make('card_status')
                    ->label('Status')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'active' => 'Aktif',
                        'revoked' => 'Dicabut',
                        'expired' => 'Kadaluarsa',
                        default => $state,
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'active' => 'success',
                        'revoked' => 'danger',
                        'expired' => 'warning',
                        default => 'gray',
                    }),

                Tables\Columns\TextColumn::make('issued_at')
                    ->label('Tanggal Terbit')
                    ->dateTime('d M Y H:i')
                    ->sortable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Dibuat')
                    ->dateTime('d M Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('card_status')
                    ->label('Status')
                    ->options([
                        'active' => 'Aktif',
                        'revoked' => 'Dicabut',
                        'expired' => 'Kadaluarsa',
                    ])
                    ->native(false),

                Tables\Filters\SelectFilter::make('user_id')
                    ->label('Karyawan')
                    ->relationship('user', 'name')
                    ->searchable()
                    ->preload()
                    ->native(false),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make()
                        ->icon('heroicon-o-eye'),

                    Tables\Actions\Action::make('download')
                        ->label('Download PDF')
                        ->icon('heroicon-o-arrow-down-tray')
                        ->color('info')
                        ->action(function (EmployeeCard $record) {
                            $pdf = app(CardPdfService::class)->generateCardPdf($record);

                            return response()->streamDownload(
                                fn () => print($pdf),
                                "kartu-{$record->card_number}.pdf",
                                ['Content-Type' => 'application/pdf']
                            );
                        }),

                    Tables\Actions\Action::make('revoke')
                        ->label('Cabut Kartu')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->visible(fn (EmployeeCard $record): bool => $record->card_status === 'active')
                        ->requiresConfirmation()
                        ->modalIcon('heroicon-o-x-circle')
                        ->modalIconColor('danger')
                        ->modalHeading('Cabut Kartu Karyawan')
                        ->modalDescription('Apakah Anda yakin ingin mencabut kartu ini? Kartu tidak dapat digunakan lagi setelah dicabut.')
                        ->form([
                            Forms\Components\Textarea::make('reason')
                                ->label('Alasan Pencabutan')
                                ->required()
                                ->maxLength(255),
                        ])
                        ->action(function (EmployeeCard $record, array $data) {
                            $record->revoke($data['reason']);

                            Notification::make()
                                ->success()
                                ->title('Kartu Dicabut')
                                ->body("Kartu {$record->card_number} berhasil dicabut.")
                                ->icon('heroicon-o-x-circle')
                                ->send();
                        }),

                    Tables\Actions\Action::make('regenerate')
                        ->label('Generate Ulang')
                        ->icon('heroicon-o-arrow-path')
                        ->color('warning')
                        ->visible(fn (EmployeeCard $record): bool => $record->card_status !== 'active')
                        ->requiresConfirmation()
                        ->modalHeading('Generate Kartu Baru')
                        ->modalDescription('Ini akan membuat kartu baru untuk karyawan ini.')
                        ->action(function (EmployeeCard $record) {
                            $qrService = app(QrCardService::class);
                            $newCard = $qrService->createCard($record->user);

                            Notification::make()
                                ->success()
                                ->title('Kartu Baru Dibuat')
                                ->body("Kartu baru {$newCard->card_number} berhasil dibuat.")
                                ->send();
                        }),
                ])
                    ->icon('heroicon-m-ellipsis-vertical')
                    ->tooltip('Aksi'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\BulkAction::make('downloadBatch')
                        ->label('Download Batch PDF')
                        ->icon('heroicon-o-arrow-down-tray')
                        ->action(function ($records) {
                            $pdf = app(CardPdfService::class)->generateBatchPdf(
                                $records->pluck('id')->toArray()
                            );

                            return response()->streamDownload(
                                fn () => print($pdf),
                                'kartu-batch-' . now()->format('YmdHis') . '.pdf',
                                ['Content-Type' => 'application/pdf']
                            );
                        }),

                    Tables\Actions\BulkAction::make('revokeSelected')
                        ->label('Cabut Terpilih')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->requiresConfirmation()
                        ->modalHeading('Cabut Kartu Terpilih')
                        ->form([
                            Forms\Components\Textarea::make('reason')
                                ->label('Alasan Pencabutan')
                                ->required(),
                        ])
                        ->action(function ($records, array $data) {
                            $count = 0;
                            $records->each(function ($record) use ($data, &$count) {
                                if ($record->card_status === 'active') {
                                    $record->revoke($data['reason']);
                                    $count++;
                                }
                            });

                            Notification::make()
                                ->success()
                                ->title('Kartu Dicabut')
                                ->body("{$count} kartu berhasil dicabut.")
                                ->send();
                        }),
                ]),
            ])
            ->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\ListEmployeeCards::route('/'),
            'view' => Pages\ViewEmployeeCard::route('/{record}'),
        ];
    }
}
