<?php

namespace App\Filament\Employee\Resources;

use App\Filament\Employee\Resources\MyEarlyLeaveResource\Pages;
use App\Models\Attendance;
use App\Models\EarlyLeaveRequest;
use App\Services\AttendanceCorrectionService;
use App\Services\EarlyLeaveService;
use Carbon\Carbon;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Infolists;
use Filament\Infolists\Infolist;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class MyEarlyLeaveResource extends Resource
{
    protected static ?string $model = EarlyLeaveRequest::class;

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

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

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

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

    protected static ?string $navigationGroup = 'Kehadiran Saya';

    protected static ?int $navigationSort = 4;

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

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

    public static function form(Form $form): Form
    {
        $user = auth()->user();
        $company = $user?->company;
        $earlyLeaveService = new EarlyLeaveService();
        $correctionService = new AttendanceCorrectionService();
        $isBackdateMode = $company ? $earlyLeaveService->isBackdateMode($company) : false;

        // Calculate threshold for problematic attendances
        $threshold = 0;
        if ($company?->work_start_time && $company?->work_end_time) {
            $workStart = Carbon::parse($company->work_start_time);
            $workEnd = Carbon::parse($company->work_end_time);
            $expectedDuration = $workStart->diffInMinutes($workEnd);
            $threshold = $expectedDuration - 45;
        }

        return $form
            ->schema([
                Forms\Components\Section::make('Dari Kehadiran (Opsional)')
                    ->description('Pilih kehadiran yang sudah checkout lebih awal. Lewati jika ingin input manual.')
                    ->collapsed()
                    ->schema([
                        Forms\Components\Select::make('attendance_id')
                            ->label('Pilih Tanggal')
                            ->options(function () use ($user, $threshold, $isBackdateMode, $correctionService) {
                                if ($threshold === 0) {
                                    return [];
                                }

                                // Get attendances with problematic duration
                                $query = Attendance::where('user_id', $user->id)
                                    ->whereNotNull('work_duration')
                                    ->where('work_duration', '<', $threshold)
                                    // Mutual exclusion: exclude yang sudah ada di koreksi absen (pending)
                                    ->whereDoesntHave('corrections', function ($q) {
                                        $q->where('status', 'pending');
                                    })
                                    // Mutual exclusion: exclude yang sudah ada di early leave request (pending)
                                    ->whereDoesntHave('earlyLeaveRequests', function ($q) {
                                        $q->whereIn('status', ['pending', 'approved', 'used']);
                                    })
                                    ->whereNotNull('check_out_time'); // Must have checkout time

                                // For normal mode, limit to eligible dates
                                if (!$isBackdateMode) {
                                    $eligibleDates = $correctionService->getEligibleDatesForCorrection($user);
                                    if (is_array($eligibleDates) && !isset($eligibleDates['all'])) {
                                        $query->whereIn('date', $eligibleDates);
                                    }
                                }

                                return $query->orderBy('date', 'desc')
                                    ->limit(30)
                                    ->get()
                                    ->mapWithKeys(function ($att) use ($threshold) {
                                        $shortage = $threshold - $att->work_duration;
                                        $hours = floor($shortage / 60);
                                        $mins = $shortage % 60;
                                        return [
                                            $att->id => $att->date->format('d M Y') . ' - ' .
                                                ($att->check_in_time?->format('H:i') ?? '-') . ' s/d ' .
                                                ($att->check_out_time?->format('H:i') ?? '-') .
                                                " (Durasi kurang {$hours}j {$mins}m)"
                                        ];
                                    });
                            })
                            ->searchable()
                            ->live()
                            ->placeholder('Ketik untuk mencari...')
                            ->afterStateUpdated(function ($state, Forms\Set $set) use ($user) {
                                if ($state) {
                                    $att = Attendance::find($state);
                                    if ($att) {
                                        // Auto-fill date and time from attendance
                                        $set('request_date', $att->date->toDateString());
                                        if ($att->check_out_time) {
                                            $set('planned_leave_time', $att->check_out_time->format('H:i'));
                                        }
                                    }
                                }
                            })
                            ->helperText('Tanggal dan jam akan otomatis terisi setelah memilih'),
                    ])
                    ->collapsible()
                    ->collapsed()
                    ->visible($isBackdateMode), // Only show in backdate mode

                Forms\Components\Section::make('Informasi Izin')
                    ->schema([
                        Forms\Components\DatePicker::make('request_date')
                            ->label('Tanggal')
                            ->required()
                            ->default(now())
                            ->minDate($isBackdateMode ? null : now())
                            ->maxDate($isBackdateMode ? now() : null)
                            ->native(false)
                            ->live(),

                        Forms\Components\TimePicker::make('planned_leave_time')
                            ->label('Jam Pulang')
                            ->required()
                            ->seconds(false)
                            ->native(false)
                            ->live(),

                        Forms\Components\Select::make('reason_type')
                            ->label('Alasan')
                            ->options(EarlyLeaveRequest::REASON_TYPES)
                            ->required()
                            ->native(false)
                            ->live(),

                        Forms\Components\Textarea::make('reason_detail')
                            ->label('Keterangan')
                            ->rows(3)
                            ->required(fn($get) => $get('reason_type') === 'other')
                            ->visible(fn($get) => $get('reason_type') === 'other'),
                    ]),

                // Backdate
                Forms\Components\Section::make('Pengaturan Backdate')
                    ->schema([
                        Forms\Components\DateTimePicker::make('simulated_request_at')
                            ->label('Waktu Pengajuan')
                            ->required()
                            ->native(false)
                            ->default(function ($get) {
                                $requestDate = $get('request_date');
                                if ($requestDate) {
                                    // Default: request date at 09:00
                                    return Carbon::parse($requestDate)->setTime(9, 0);
                                }
                                return now();
                            })
                            ->minDate(function ($get) {
                                $requestDate = $get('request_date');
                                return $requestDate ? Carbon::parse($requestDate)->startOfDay() : null;
                            })
                            ->maxDate(function ($get) {
                                $requestDate = $get('request_date');
                                $plannedTime = $get('planned_leave_time');

                                if ($requestDate && $plannedTime) {
                                    // Max is planned leave time on that date
                                    return Carbon::parse($requestDate)->setTimeFromTimeString(
                                        Carbon::parse($plannedTime)->format('H:i:s')
                                    )->subMinute(); // 1 minute before planned leave
                                }

                                return now();
                            })
                            ->helperText('Waktu harus sebelum jam pulang yang direncanakan'),
                    ])
                    ->visible($isBackdateMode)
                    ->hidden(fn($get) => !$get('request_date') || !$get('planned_leave_time')),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                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')
                    ->sortable(),

                Tables\Columns\TextColumn::make('reason_type')
                    ->label('Alasan')
                    ->formatStateUsing(fn($state) => EarlyLeaveRequest::REASON_TYPES[$state] ?? $state)
                    ->badge()
                    ->color(fn($state) => match ($state) {
                        'sick' => 'danger',
                        'family' => 'warning',
                        'emergency' => 'danger',
                        'appointment' => 'info',
                        'official' => 'success',
                        default => 'gray',
                    }),

                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->color(fn($state) => 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(),

                Tables\Columns\TextColumn::make('approver.name')
                    ->label('Diproses Oleh')
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('Status')
                    ->options(EarlyLeaveRequest::STATUSES)
                    ->native(false),
            ])
            ->actions([
                Tables\Actions\ViewAction::make()
                    ->icon('heroicon-o-eye'),

                Tables\Actions\Action::make('cancel')
                    ->label('Batalkan')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->visible(fn($record) => $record->status === 'pending')
                    ->requiresConfirmation()
                    ->modalHeading('Batalkan Pengajuan')
                    ->modalDescription('Apakah Anda yakin ingin membatalkan pengajuan izin pulang cepat ini?')
                    ->action(function ($record) {
                        $record->delete();

                        Notification::make()
                            ->success()
                            ->title('Pengajuan Dibatalkan')
                            ->body('Pengajuan izin pulang cepat berhasil dibatalkan.')
                            ->send();
                    }),
            ])
            ->bulkActions([])
            ->defaultSort('created_at', 'desc')
            ->striped();
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Section::make('Detail Izin')
                    ->schema([
                        Infolists\Components\TextEntry::make('request_date')
                            ->label('Tanggal')
                            ->date('d M Y'),
                        Infolists\Components\TextEntry::make('planned_leave_time')
                            ->label('Jam Pulang')
                            ->time('H:i'),
                        Infolists\Components\TextEntry::make('status')
                            ->label('Status')
                            ->badge()
                            ->color(fn($state) => match ($state) {
                                'pending' => 'warning',
                                'approved' => 'success',
                                'rejected' => 'danger',
                                'used' => 'info',
                                'expired' => 'gray',
                                default => 'gray',
                            })
                            ->formatStateUsing(fn($state) => EarlyLeaveRequest::STATUSES[$state] ?? $state),
                    ])
                    ->columns(3),

                Infolists\Components\Section::make('Alasan')
                    ->schema([
                        Infolists\Components\TextEntry::make('reason_type')
                            ->label('Jenis Alasan')
                            ->formatStateUsing(fn($state) => EarlyLeaveRequest::REASON_TYPES[$state] ?? $state)
                            ->badge(),
                        Infolists\Components\TextEntry::make('reason_detail')
                            ->label('Keterangan')
                            ->placeholder('-')
                            ->columnSpanFull(),
                    ]),

                Infolists\Components\Section::make('Informasi Proses')
                    ->schema([
                        Infolists\Components\TextEntry::make('created_at')
                            ->label('Tanggal Pengajuan')
                            ->dateTime('d M Y H:i'),
                        Infolists\Components\TextEntry::make('approver.name')
                            ->label('Diproses Oleh')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('approved_at')
                            ->label('Tanggal Proses')
                            ->dateTime('d M Y H:i')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('rejection_reason')
                            ->label('Alasan Penolakan')
                            ->placeholder('-')
                            ->visible(fn($record) => $record->status === 'rejected')
                            ->columnSpanFull(),
                        Infolists\Components\TextEntry::make('actual_checkout_at')
                            ->label('Waktu Checkout Aktual')
                            ->dateTime('d M Y H:i')
                            ->placeholder('-')
                            ->visible(fn($record) => $record->status === 'used'),
                    ])
                    ->columns(3),
            ]);
    }

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

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

    public static function getEloquentQuery(): Builder
    {
        $user = auth()->user();

        return parent::getEloquentQuery()
            ->with(['approver'])
            ->where('user_id', $user?->id)
            ->orderBy('created_at', 'desc');
    }
}
