<?php

namespace App\Filament\Resources;

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

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

    protected static ?string $navigationGroup = 'Approval';

    protected static ?string $navigationLabel = 'Koreksi Absensi';

    protected static ?string $modelLabel = 'Koreksi Absensi';

    protected static ?string $pluralModelLabel = 'Koreksi Absensi';

    protected static ?int $navigationSort = 1;

    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('target_date')
                            ->label('Tanggal')
                            ->disabled(),

                        Forms\Components\Select::make('correction_type')
                            ->label('Tipe Koreksi')
                            ->options(AttendanceCorrection::CORRECTION_TYPES)
                            ->disabled(),

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

                Forms\Components\Section::make('Data Original')
                    ->schema([
                        Forms\Components\TimePicker::make('original_check_in')
                            ->label('Check In Original')
                            ->disabled(),

                        Forms\Components\TimePicker::make('original_check_out')
                            ->label('Check Out Original')
                            ->disabled(),

                        Forms\Components\TextInput::make('original_duration')
                            ->label('Durasi Original (menit)')
                            ->disabled(),
                    ])
                    ->columns(3),

                Forms\Components\Section::make('Data Koreksi')
                    ->schema([
                        Forms\Components\TimePicker::make('corrected_check_in')
                            ->label('Check In Koreksi')
                            ->disabled(),

                        Forms\Components\TimePicker::make('corrected_check_out')
                            ->label('Check Out Koreksi')
                            ->disabled(),

                        Forms\Components\TextInput::make('corrected_duration')
                            ->label('Durasi Koreksi (menit)')
                            ->disabled(),
                    ])
                    ->columns(3),

                Forms\Components\Section::make('Alasan')
                    ->schema([
                        Forms\Components\Textarea::make('reason')
                            ->label('Alasan Pengajuan')
                            ->disabled()
                            ->columnSpanFull(),

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

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

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

                Tables\Columns\TextColumn::make('correction_type')
                    ->label('Tipe')
                    ->badge()
                    ->formatStateUsing(fn ($state) => AttendanceCorrection::CORRECTION_TYPES[$state] ?? $state),

                Tables\Columns\TextColumn::make('corrected_check_in')
                    ->label('Check In')
                    ->time('H:i'),

                Tables\Columns\TextColumn::make('corrected_check_out')
                    ->label('Check Out')
                    ->time('H:i'),

                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'pending' => 'warning',
                        'approved', 'auto_approved' => 'success',
                        'rejected' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => AttendanceCorrection::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(AttendanceCorrection::STATUSES),

                Tables\Filters\SelectFilter::make('correction_type')
                    ->label('Tipe Koreksi')
                    ->options(AttendanceCorrection::CORRECTION_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 Koreksi Absensi')
                    ->modalDescription('Apakah Anda yakin ingin menyetujui koreksi absensi ini?')
                    ->visible(fn ($record) => $record->status === 'pending')
                    ->action(function (AttendanceCorrection $record) {
                        $record->update([
                            'status' => 'approved',
                            'approved_by' => Auth::id(),
                            'approved_at' => now(),
                        ]);

                        // Update attendance record
                        if ($record->attendance) {
                            $updateData = [];
                            if ($record->corrected_check_in) {
                                $updateData['check_in_time'] = $record->corrected_check_in;
                            }
                            if ($record->corrected_check_out) {
                                $updateData['check_out_time'] = $record->corrected_check_out;
                            }
                            if ($record->corrected_duration) {
                                $updateData['work_duration'] = $record->corrected_duration;
                            }
                            if (!empty($updateData)) {
                                $record->attendance->update($updateData);
                            }
                        }

                        Notification::make()
                            ->title('Koreksi 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 (AttendanceCorrection $record, array $data) {
                        $record->update([
                            'status' => 'rejected',
                            'rejection_reason' => $data['rejection_reason'],
                            'approved_by' => Auth::id(),
                            'approved_at' => now(),
                        ]);

                        Notification::make()
                            ->title('Koreksi 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(),
                                ]);

                                if ($record->attendance) {
                                    $updateData = [];
                                    if ($record->corrected_check_in) {
                                        $updateData['check_in_time'] = $record->corrected_check_in;
                                    }
                                    if ($record->corrected_check_out) {
                                        $updateData['check_out_time'] = $record->corrected_check_out;
                                    }
                                    if ($record->corrected_duration) {
                                        $updateData['work_duration'] = $record->corrected_duration;
                                    }
                                    if (!empty($updateData)) {
                                        $record->attendance->update($updateData);
                                    }
                                }
                            }
                        });

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

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

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

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