<?php

namespace App\Filament\Resources;

use App\Filament\Resources\EarlyLeaveRequestResource\Pages;
use App\Models\EarlyLeaveRequest;
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 EarlyLeaveRequestResource extends Resource
{
    protected static ?string $model = EarlyLeaveRequest::class;

    protected static ?string $navigationIcon = 'heroicon-o-arrow-left-start-on-rectangle';

    protected static ?string $navigationGroup = 'Approval';

    protected static ?string $navigationLabel = 'Izin Pulang Awal';

    protected static ?string $modelLabel = 'Izin Pulang Awal';

    protected static ?string $pluralModelLabel = 'Izin Pulang Awal';

    protected static ?int $navigationSort = 2;

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

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

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

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

                        Forms\Components\DatePicker::make('request_date')
                            ->label('Tanggal')
                            ->disabled(),

                        Forms\Components\TimePicker::make('planned_leave_time')
                            ->label('Jam Pulang Direncanakan')
                            ->disabled(),

                        Forms\Components\Select::make('status')
                            ->label('Status')
                            ->options(EarlyLeaveRequest::STATUSES)
                            ->disabled(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Alasan')
                    ->schema([
                        Forms\Components\Select::make('reason_type')
                            ->label('Tipe Alasan')
                            ->options(EarlyLeaveRequest::REASON_TYPES)
                            ->disabled(),

                        Forms\Components\Textarea::make('reason_detail')
                            ->label('Detail Alasan')
                            ->disabled()
                            ->columnSpanFull(),

                        Forms\Components\Textarea::make('rejection_reason')
                            ->label('Alasan Penolakan')
                            ->visible(fn ($record) => $record?->status === 'rejected')
                            ->disabled()
                            ->columnSpanFull(),
                    ]),

                Forms\Components\Section::make('Penggunaan')
                    ->schema([
                        Forms\Components\DateTimePicker::make('actual_checkout_at')
                            ->label('Waktu Checkout Aktual')
                            ->disabled(),
                    ])
                    ->visible(fn ($record) => $record?->actual_checkout_at !== null),
            ]);
    }

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

                Tables\Columns\TextColumn::make('request_date')
                    ->label('Tanggal')
                    ->date('d M Y')
                    ->sortable(),

                Tables\Columns\TextColumn::make('planned_leave_time')
                    ->label('Jam Pulang')
                    ->time('H:i'),

                Tables\Columns\TextColumn::make('reason_type')
                    ->label('Alasan')
                    ->badge()
                    ->formatStateUsing(fn ($state) => EarlyLeaveRequest::REASON_TYPES[$state] ?? $state),

                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'pending' => 'warning',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        'used' => 'info',
                        'expired' => 'gray',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => EarlyLeaveRequest::STATUSES[$state] ?? $state),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Diajukan')
                    ->dateTime('d M Y H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('approver.name')
                    ->label('Disetujui Oleh')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('Status')
                    ->options(EarlyLeaveRequest::STATUSES),

                Tables\Filters\SelectFilter::make('reason_type')
                    ->label('Tipe Alasan')
                    ->options(EarlyLeaveRequest::REASON_TYPES),

                Tables\Filters\Filter::make('pending')
                    ->label('Menunggu Approval')
                    ->query(fn (Builder $query): Builder => $query->where('status', 'pending'))
                    ->default(),
            ])
            ->actions([
                Tables\Actions\Action::make('approve')
                    ->label('Setujui')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->modalHeading('Setujui Izin Pulang Awal')
                    ->modalDescription('Apakah Anda yakin ingin menyetujui izin pulang awal ini?')
                    ->visible(fn ($record) => $record->status === 'pending')
                    ->action(function (EarlyLeaveRequest $record) {
                        $record->update([
                            'status' => 'approved',
                            'approved_by' => Auth::id(),
                            'approved_at' => now(),
                        ]);

                        Notification::make()
                            ->title('Izin Pulang Awal Disetujui')
                            ->success()
                            ->send();
                    }),

                Tables\Actions\Action::make('reject')
                    ->label('Tolak')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->form([
                        Forms\Components\Textarea::make('rejection_reason')
                            ->label('Alasan Penolakan')
                            ->required(),
                    ])
                    ->visible(fn ($record) => $record->status === 'pending')
                    ->action(function (EarlyLeaveRequest $record, array $data) {
                        $record->update([
                            'status' => 'rejected',
                            'rejection_reason' => $data['rejection_reason'],
                            'approved_by' => Auth::id(),
                            'approved_at' => now(),
                        ]);

                        Notification::make()
                            ->title('Izin Pulang Awal Ditolak')
                            ->warning()
                            ->send();
                    }),

                Tables\Actions\ViewAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkAction::make('bulkApprove')
                    ->label('Setujui Terpilih')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->action(function ($records) {
                        $records->each(function ($record) {
                            if ($record->status === 'pending') {
                                $record->update([
                                    'status' => 'approved',
                                    'approved_by' => Auth::id(),
                                    'approved_at' => now(),
                                ]);
                            }
                        });

                        Notification::make()
                            ->title('Izin Pulang Awal Disetujui')
                            ->success()
                            ->send();
                    }),
            ])
            ->defaultSort('created_at', 'desc');
    }

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

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

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