<?php

namespace App\Filament\Employee\Resources;

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

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

    protected static ?string $navigationLabel = 'Izin Terlambat';

    protected static ?string $modelLabel = 'Izin Terlambat';

    protected static ?string $pluralModelLabel = 'Izin Terlambat';

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

    protected static ?int $navigationSort = 5;

    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;
        $lateArrivalService = new LateArrivalService();
        $isBackdateMode = $company ? $lateArrivalService->isBackdateMode($company) : false;

        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Izin Terlambat')
                    ->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_arrival_time')
                            ->label('Jam Rencana Datang')
                            ->required()
                            ->seconds(false)
                            ->native(false)
                            ->live()
                            ->helperText('Jam perkiraan Anda akan tiba di kantor'),

                        Forms\Components\Select::make('reason_type')
                            ->label('Alasan')
                            ->options(LateArrivalRequest::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 settings
                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: night before at 21:00 or morning at 06:00
                                    $date = Carbon::parse($requestDate);
                                    return $date->copy()->subDay()->setTime(21, 0);
                                }
                                return now();
                            })
                            ->maxDate(function ($get) {
                                $requestDate = $get('request_date');
                                $plannedTime = $get('planned_arrival_time');

                                if ($requestDate && $plannedTime) {
                                    return Carbon::parse($requestDate)->setTimeFromTimeString(
                                        Carbon::parse($plannedTime)->format('H:i:s')
                                    )->subMinute();
                                }

                                return now();
                            })
                            ->helperText('Waktu harus sebelum jam rencana datang'),
                    ])
                    ->visible($isBackdateMode)
                    ->hidden(fn($get) => !$get('request_date') || !$get('planned_arrival_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_arrival_time')
                    ->label('Jam Rencana Datang')
                    ->time('H:i')
                    ->sortable(),

                Tables\Columns\TextColumn::make('reason_type')
                    ->label('Alasan')
                    ->formatStateUsing(fn($state) => LateArrivalRequest::REASON_TYPES[$state] ?? $state)
                    ->badge()
                    ->color(fn($state) => match ($state) {
                        'traffic' => 'warning',
                        '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) => LateArrivalRequest::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(LateArrivalRequest::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 terlambat ini?')
                    ->action(function ($record) {
                        $record->delete();

                        Notification::make()
                            ->success()
                            ->title('Pengajuan Dibatalkan')
                            ->body('Pengajuan izin terlambat 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_arrival_time')
                            ->label('Jam Rencana Datang')
                            ->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) => LateArrivalRequest::STATUSES[$state] ?? $state),
                    ])
                    ->columns(3),

                Infolists\Components\Section::make('Alasan')
                    ->schema([
                        Infolists\Components\TextEntry::make('reason_type')
                            ->label('Jenis Alasan')
                            ->formatStateUsing(fn($state) => LateArrivalRequest::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_checkin_at')
                            ->label('Waktu Check-in 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\ListMyLateArrivals::route('/'),
            'create' => Pages\CreateMyLateArrival::route('/create'),
            'view' => Pages\ViewMyLateArrival::route('/{record}'),
        ];
    }

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

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