<?php

namespace App\Filament\Resources;

use App\Filament\Resources\QrAttendanceLogResource\Pages;
use App\Models\QrAttendanceLog;
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\Support\Facades\Auth;

class QrAttendanceLogResource extends Resource
{
    protected static ?string $model = QrAttendanceLog::class;

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

    protected static ?string $navigationGroup = 'Kehadiran';

    protected static ?string $navigationLabel = 'Log Scan QR';

    protected static ?string $modelLabel = 'Log Scan QR';

    protected static ?string $pluralModelLabel = 'Log Scan QR';

    protected static ?int $navigationSort = 5;

    public static function shouldRegisterNavigation(): bool
    {
        return true;
    }

    public static function getNavigationBadge(): ?string
    {
        $user = Auth::user();
        $count = static::getModel()::where('company_id', $user?->company_id)
            ->whereDate('scanned_at', today())
            ->count();
        return $count > 0 ? (string) $count : null;
    }

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Scan')
                    ->schema([
                        Forms\Components\Select::make('scanned_user_id')
                            ->label('Karyawan yang Discan')
                            ->relationship('scannedUser', 'name')
                            ->disabled(),

                        Forms\Components\Select::make('scanner_user_id')
                            ->label('Admin yang Scan')
                            ->relationship('scannerUser', 'name')
                            ->disabled(),

                        Forms\Components\Select::make('scan_type')
                            ->label('Tipe Scan')
                            ->options([
                                'check_in' => 'Check In',
                                'check_out' => 'Check Out',
                            ])
                            ->disabled(),

                        Forms\Components\Select::make('scan_status')
                            ->label('Status')
                            ->options([
                                'success' => 'Berhasil',
                                'failed' => 'Gagal',
                            ])
                            ->disabled(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Detail')
                    ->schema([
                        Forms\Components\DateTimePicker::make('scanned_at')
                            ->label('Waktu Scan')
                            ->disabled(),

                        Forms\Components\TextInput::make('latitude')
                            ->label('Latitude')
                            ->disabled(),

                        Forms\Components\TextInput::make('longitude')
                            ->label('Longitude')
                            ->disabled(),

                        Forms\Components\Textarea::make('failure_reason')
                            ->label('Alasan Gagal')
                            ->visible(fn ($record) => $record?->scan_status === 'failed')
                            ->disabled()
                            ->columnSpanFull(),
                    ])
                    ->columns(3),

                Forms\Components\Section::make('Informasi Device')
                    ->schema([
                        Forms\Components\KeyValue::make('device_info')
                            ->label('Device Info')
                            ->disabled(),
                    ])
                    ->collapsible(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('scannedUser.name')
                    ->label('Karyawan')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('scannerUser.name')
                    ->label('Admin Scan')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('scan_type')
                    ->label('Tipe')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'check_in' => 'success',
                        'check_out' => 'warning',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => $state === 'check_in' ? 'Check In' : 'Check Out'),

                Tables\Columns\TextColumn::make('scan_status')
                    ->label('Status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'success' => 'success',
                        'failed' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => $state === 'success' ? 'Berhasil' : 'Gagal'),

                Tables\Columns\TextColumn::make('scanned_at')
                    ->label('Waktu Scan')
                    ->dateTime('d M Y H:i:s')
                    ->sortable(),

                Tables\Columns\TextColumn::make('failure_reason')
                    ->label('Alasan Gagal')
                    ->limit(30)
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('scan_type')
                    ->label('Tipe Scan')
                    ->options([
                        'check_in' => 'Check In',
                        'check_out' => 'Check Out',
                    ]),

                Tables\Filters\SelectFilter::make('scan_status')
                    ->label('Status')
                    ->options([
                        'success' => 'Berhasil',
                        'failed' => 'Gagal',
                    ]),

                Tables\Filters\Filter::make('scanned_at')
                    ->form([
                        Forms\Components\DatePicker::make('from')
                            ->label('Dari Tanggal'),
                        Forms\Components\DatePicker::make('until')
                            ->label('Sampai Tanggal'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['from'],
                                fn (Builder $query, $date): Builder => $query->whereDate('scanned_at', '>=', $date),
                            )
                            ->when(
                                $data['until'],
                                fn (Builder $query, $date): Builder => $query->whereDate('scanned_at', '<=', $date),
                            );
                    }),

                Tables\Filters\Filter::make('today')
                    ->label('Hari Ini')
                    ->query(fn (Builder $query): Builder => $query->whereDate('scanned_at', today()))
                    ->default(),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
            ])
            ->bulkActions([])
            ->defaultSort('scanned_at', 'desc');
    }

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

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

    public static function getEloquentQuery(): Builder
    {
        $user = Auth::user();
        return parent::getEloquentQuery()
            ->where('company_id', $user?->company_id);
    }

    public static function canCreate(): bool
    {
        return false;
    }
}
