<?php

namespace App\Filament\Employee\Resources;

use App\Filament\Employee\Resources\MyAttendanceResource\Pages;
use App\Models\Attendance;
use App\Models\Location;
use Carbon\Carbon;
use Filament\Forms;
use Filament\Infolists;
use Filament\Infolists\Infolist;
use Filament\Resources\Resource;
use Filament\Support\Enums\FontWeight;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class MyAttendanceResource extends Resource
{
    protected static ?string $model = Attendance::class;

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

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

    protected static ?string $navigationLabel = 'Data Kehadiran';

    protected static ?string $modelLabel = 'Kehadiran';

    protected static ?string $pluralModelLabel = 'Data Kehadiran';

    protected static ?int $navigationSort = 1;

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('date')
                    ->label('Tanggal')
                    ->date('D, d M Y')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('type')
                    ->label('Tipe')
                    ->badge()
                    ->formatStateUsing(function (string $state, $record): string {
                        $label = match ($state) {
                            'office' => 'Kantor',
                            'wfh' => 'WFH',
                            'business_trip' => 'Dinas',
                            default => $state,
                        };
                        // Add warning icon if business trip without location
                        if ($state === 'business_trip' && $record->isBusinessTripWithIncompleteLocation()) {
                            $label .= ' ⚠️';
                        }
                        return $label;
                    })
                    ->color(function (string $state, $record): string {
                        // Highlight incomplete business trip with danger color
                        if ($state === 'business_trip' && $record->isBusinessTripWithIncompleteLocation()) {
                            return 'danger';
                        }
                        return match ($state) {
                            'office' => 'primary',
                            'wfh' => 'info',
                            'business_trip' => 'warning',
                            default => 'gray',
                        };
                    })
                    ->tooltip(function ($record): ?string {
                        if ($record->type === 'business_trip' && $record->isBusinessTripWithIncompleteLocation()) {
                            return 'Lokasi belum lengkap - Klik tombol Isi Lokasi';
                        }
                        return null;
                    }),

                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->formatStateUsing(fn(string $state): string => match ($state) {
                        'present' => 'Hadir',
                        'late' => 'Terlambat',
                        'absent' => 'Tidak Hadir',
                        'sick' => 'Sakit',
                        'leave' => 'Cuti',
                        'permission' => 'Izin',
                        'early_leave' => 'Pulang Awal',
                        default => ucfirst($state),
                    })
                    ->color(fn(string $state): string => match ($state) {
                        'present' => 'success',
                        'late' => 'warning',
                        'absent' => 'danger',
                        'sick' => 'purple',
                        'leave' => 'info',
                        'permission' => 'gray',
                        default => 'gray',
                    }),

                Tables\Columns\TextColumn::make('check_in_time')
                    ->label('Masuk')
                    ->time('H:i')
                    ->placeholder('-'),

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

                Tables\Columns\TextColumn::make('work_duration')
                    ->label('Durasi')
                    ->formatStateUsing(function ($state) {
                        if (!$state) return '-';
                        $hours = floor($state / 60);
                        $mins = $state % 60;
                        return "{$hours}j {$mins}m";
                    }),

                Tables\Columns\TextColumn::make('office.name')
                    ->label('Lokasi')
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\IconColumn::make('has_activity')
                    ->label('Aktivitas')
                    ->boolean()
                    ->getStateUsing(fn($record) => $record->activities()->exists())
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),
            ])
            ->defaultSort('date', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('type')
                    ->label('Tipe')
                    ->options([
                        'office' => 'Kantor',
                        'wfh' => 'WFH',
                        'business_trip' => 'Dinas',
                    ]),
                Tables\Filters\SelectFilter::make('status')
                    ->label('Status')
                    ->options([
                        'present' => 'Hadir',
                        'late' => 'Terlambat',
                        'absent' => 'Tidak Hadir',
                        'sick' => 'Sakit',
                        'leave' => 'Cuti',
                        'permission' => 'Izin',
                    ]),
                Tables\Filters\Filter::make('date')
                    ->form([
                        \Filament\Forms\Components\DatePicker::make('from')
                            ->label('Dari Tanggal'),
                        \Filament\Forms\Components\DatePicker::make('until')
                            ->label('Sampai Tanggal'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'], fn(Builder $query, $date) => $query->whereDate('date', '>=', $date))
                            ->when($data['until'], fn(Builder $query, $date) => $query->whereDate('date', '<=', $date));
                    }),
                Tables\Filters\Filter::make('no_activity')
                    ->label('Tanpa Aktivitas')
                    ->query(fn(Builder $query) => $query->whereDoesntHave('activities')),
                Tables\Filters\Filter::make('business_trip_no_location')
                    ->label('Dinas Tanpa Lokasi')
                    ->query(fn(Builder $query): Builder => $query->businessTripIncompleteLocation())
                    ->toggle()
                    ->visible(fn(): bool => self::canFillLocation()),
            ])
            ->actions([
                // Action untuk mengisi lokasi dinas yang belum lengkap (hanya jika backdate & editable enabled)
                Tables\Actions\Action::make('fill_location')
                    ->label('Isi Lokasi')
                    ->icon('heroicon-o-map-pin')
                    ->color('danger')
                    ->visible(fn($record): bool => self::canFillLocation() && $record->isBusinessTripWithIncompleteLocation())
                    ->form(function ($record) {
                        $user = auth()->user();

                        // Check for ALL active ST (multiple possible)
                        $activeSTList = \App\Models\SuratTugas::findAllActiveForUserOnDate(
                            $user->id,
                            $record->date
                        );

                        $schema = [];

                        // If ST detected, show improved UI
                        if ($activeSTList->isNotEmpty()) {
                            // Build options for ST dropdown with detailed info
                            $stOptions = $activeSTList->mapWithKeys(function ($st) {
                                $label = $st->location_name;
                                if ($st->no_st) {
                                    $label .= ' (ST: ' . $st->no_st . ')';
                                }
                                $label .= ' | ' . $st->tanggal_mulai->format('d M') . ' - ' . $st->tanggal_selesai->format('d M Y');
                                return [$st->id => $label];
                            })->toArray();

                            // Get first ST for display
                            $firstST = $activeSTList->first();
                            $stCount = $activeSTList->count();

                            // Compact ST info banner with keterangan
                            $schema[] = Forms\Components\Placeholder::make('st_detected')
                                ->label('')
                                ->content(function () use ($firstST, $stCount) {
                                    $locationName = $firstST->location_name ?? 'Lokasi ST';
                                    $stNo = $firstST->no_st ? "ST: {$firstST->no_st}" : '';
                                    $period = $firstST->tanggal_mulai->format('d M') . ' - ' . $firstST->tanggal_selesai->format('d M Y');
                                    $countBadge = $stCount > 1 ? '<span class="ml-2 px-2 py-0.5 text-xs bg-success-100 dark:bg-success-800 text-success-700 dark:text-success-300 rounded-full">+' . ($stCount - 1) . ' lainnya</span>' : '';

                                    // Keterangan ST (truncate if too long)
                                    $keterangan = $firstST->keterangan;
                                    $keteranganHtml = '';
                                    if ($keterangan) {
                                        $keteranganTruncated = \Illuminate\Support\Str::limit($keterangan, 100);
                                        $keteranganHtml = '<div class="mt-1 text-xs text-gray-500 dark:text-gray-400 italic">"' . e($keteranganTruncated) . '"</div>';
                                    }

                                    return new \Illuminate\Support\HtmlString(
                                        '<div class="p-3 bg-success-50 dark:bg-success-900/20 border border-success-200 dark:border-success-700 rounded-lg">' .
                                        '<div class="flex items-center justify-between">' .
                                        '<div class="flex items-center gap-2">' .
                                        '<svg class="w-5 h-5 text-success-600 dark:text-success-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>' .
                                        '<span class="font-medium text-success-700 dark:text-success-400">Rekomendasi Surat Tugas</span>' .
                                        $countBadge .
                                        '</div>' .
                                        '</div>' .
                                        '<div class="mt-2 pl-7">' .
                                        '<div class="font-medium text-gray-900 dark:text-gray-100">' . e($locationName) . '</div>' .
                                        '<div class="text-sm text-gray-500 dark:text-gray-400">' . $stNo . ($stNo ? ' · ' : '') . $period . '</div>' .
                                        $keteranganHtml .
                                        '</div>' .
                                        '</div>'
                                    );
                                })
                                ->columnSpanFull();

                            // Horizontal segmented control style using ToggleButtons
                            $schema[] = Forms\Components\ToggleButtons::make('location_source')
                                ->label('Sumber Lokasi')
                                ->options([
                                    'st' => 'Surat Tugas',
                                    'other' => 'Lokasi Lain',
                                    'manual' => 'Manual',
                                ])
                                ->icons([
                                    'st' => 'heroicon-o-document-text',
                                    'other' => 'heroicon-o-map-pin',
                                    'manual' => 'heroicon-o-pencil',
                                ])
                                ->default('st')
                                ->inline()
                                ->live()
                                ->columnSpanFull();

                            // ST selection dropdown (only if multiple ST)
                            if ($stCount > 1) {
                                $schema[] = Forms\Components\Select::make('st_id')
                                    ->label('Pilih Surat Tugas')
                                    ->options($stOptions)
                                    ->default($firstST->id)
                                    ->visible(fn($get) => $get('location_source') === 'st')
                                    ->required(fn($get) => $get('location_source') === 'st')
                                    ->live()
                                    ->columnSpanFull();
                            } else {
                                // Hidden field for single ST
                                $schema[] = Forms\Components\Hidden::make('st_id')
                                    ->default($firstST->id);
                            }

                            // Check for other dates that can be filled
                            $overlappingDates = $firstST->getOverlappingAttendanceDates($user->id);
                            $overlappingDates = array_filter($overlappingDates, fn($d) => $d !== $record->date->format('Y-m-d'));
                            $hasOtherDates = !empty($overlappingDates);

                            // Checkbox with inline date preview
                            if ($hasOtherDates) {
                                $formattedDates = array_map(fn($d) => Carbon::parse($d)->format('d M'), $overlappingDates);
                                $datePreview = count($formattedDates) <= 3
                                    ? implode(', ', $formattedDates)
                                    : implode(', ', array_slice($formattedDates, 0, 3)) . ' +' . (count($formattedDates) - 3) . ' lagi';

                                $schema[] = Forms\Components\Checkbox::make('apply_to_range')
                                    ->label('Isi juga ' . count($overlappingDates) . ' tanggal lain: ' . $datePreview)
                                    ->helperText('Kehadiran dinas tanpa lokasi dalam periode ST ini.')
                                    ->default(false)
                                    ->visible(fn($get) => $get('location_source') === 'st')
                                    ->columnSpanFull();
                            } else {
                                $schema[] = Forms\Components\Hidden::make('apply_to_range')
                                    ->default(false);
                            }
                        } else {
                            // No ST detected - simpler UI
                            $schema[] = Forms\Components\ToggleButtons::make('location_source')
                                ->label('Sumber Lokasi')
                                ->options([
                                    'existing' => 'Pilih Lokasi',
                                    'manual' => 'Input Manual',
                                ])
                                ->icons([
                                    'existing' => 'heroicon-o-map-pin',
                                    'manual' => 'heroicon-o-pencil',
                                ])
                                ->default('existing')
                                ->inline()
                                ->live()
                                ->columnSpanFull();
                        }

                        // Location dropdown (visible when choosing 'other' or 'existing')
                        $schema[] = Forms\Components\Select::make('location_id')
                            ->label('Pilih Lokasi Dinas')
                            ->options(function () use ($user) {
                                return Location::query()
                                    ->where('is_active', true)
                                    ->where('company_id', $user->company_id)
                                    ->where('allow_business_trip', true)
                                    ->orderBy('is_primary', 'desc')
                                    ->orderBy('sort_order', 'asc')
                                    ->orderBy('name', 'asc')
                                    ->get()
                                    ->mapWithKeys(fn($loc) => [
                                        $loc->id => ($loc->is_primary ? '* ' : '') . $loc->name . ' - ' . $loc->city
                                    ]);
                            })
                            ->searchable()
                            ->preload()
                            ->visible(fn($get) => in_array($get('location_source'), ['other', 'existing']))
                            ->required(fn($get) => in_array($get('location_source'), ['other', 'existing']))
                            ->live()
                            ->afterStateUpdated(function ($state, Forms\Set $set) {
                                if ($state) {
                                    $location = Location::find($state);
                                    if ($location) {
                                        // Set original coordinates (random offset applied on submit)
                                        $set('check_in_latitude', $location->latitude);
                                        $set('check_in_longitude', $location->longitude);
                                        $set('check_in_address', $location->address);
                                    }
                                }
                            });

                        // Manual input fields
                        $schema[] = Forms\Components\TextInput::make('custom_location_name')
                            ->label('Nama Lokasi')
                            ->visible(fn($get) => $get('location_source') === 'manual')
                            ->required(fn($get) => $get('location_source') === 'manual')
                            ->columnSpanFull();

                        // Lat/Long fields - only show for manual input
                        $schema[] = Forms\Components\Grid::make(2)
                            ->schema([
                                Forms\Components\TextInput::make('check_in_latitude')
                                    ->label('Latitude')
                                    ->numeric()
                                    ->step(0.000001)
                                    ->required()
                                    ->prefixIcon('heroicon-o-map-pin')
                                    ->placeholder('-6.123456'),
                                Forms\Components\TextInput::make('check_in_longitude')
                                    ->label('Longitude')
                                    ->numeric()
                                    ->step(0.000001)
                                    ->required()
                                    ->prefixIcon('heroicon-o-map-pin')
                                    ->placeholder('106.123456'),
                            ])
                            ->visible(fn($get) => $get('location_source') === 'manual');

                        $schema[] = Forms\Components\Textarea::make('check_in_address')
                            ->label('Alamat')
                            ->rows(2)
                            ->visible(fn($get) => $get('location_source') === 'manual');

                        return $schema;
                    })
                    ->action(function (Attendance $record, array $data): void {
                        $user = auth()->user();
                        $locationId = null;
                        $latitude = null;
                        $longitude = null;
                        $address = null;
                        $applyToRange = $data['apply_to_range'] ?? false;
                        $selectedST = null;

                        if ($data['location_source'] === 'st' && isset($data['st_id'])) {
                            // Use ST location
                            $selectedST = \App\Models\SuratTugas::find($data['st_id']);
                            if ($selectedST) {
                                $coords = $selectedST->getLocationCoordinates();
                                if ($coords) {
                                    $latitude = $coords['latitude'];
                                    $longitude = $coords['longitude'];
                                    $address = $coords['address'];
                                    $locationId = $selectedST->location_id;
                                }
                            }
                        } elseif (in_array($data['location_source'], ['other', 'existing']) && isset($data['location_id'])) {
                            // Get coordinates from Location model
                            $location = Location::find($data['location_id']);
                            if ($location) {
                                $locationId = $location->id;
                                $latitude = $location->latitude;
                                $longitude = $location->longitude;
                                $address = $location->address;
                            }
                        } elseif ($data['location_source'] === 'manual') {
                            $latitude = $data['check_in_latitude'];
                            $longitude = $data['check_in_longitude'];
                            $address = $data['check_in_address'] ?? null;
                        }

                        if (!$latitude || !$longitude) {
                            \Filament\Notifications\Notification::make()
                                ->danger()
                                ->title('Gagal menyimpan')
                                ->body('Koordinat tidak valid.')
                                ->send();
                            return;
                        }

                        // Collect records to update
                        $recordsToUpdate = collect([$record]);

                        // If apply_to_range is enabled, get other overlapping dates
                        if ($applyToRange && $selectedST) {
                            $overlappingDates = $selectedST->getOverlappingAttendanceDates($user->id);
                            // Exclude current record date
                            $overlappingDates = array_filter($overlappingDates, fn($d) => $d !== $record->date->format('Y-m-d'));

                            if (!empty($overlappingDates)) {
                                $additionalRecords = Attendance::where('user_id', $user->id)
                                    ->where('type', 'business_trip')
                                    ->whereIn('date', $overlappingDates)
                                    ->where(function ($q) {
                                        $q->whereNull('check_in_latitude')->orWhereNull('check_in_longitude');
                                    })
                                    ->get();
                                $recordsToUpdate = $recordsToUpdate->merge($additionalRecords);
                            }
                        }

                        $updatedCount = 0;
                        foreach ($recordsToUpdate as $att) {
                            // Apply random offset 5-50 meter for dinas (business trip) for each record (different offset)
                            $offset = \App\Models\SuratTugas::applyRandomOffsetDinas(
                                (float) $latitude,
                                (float) $longitude
                            );

                            $updateData = [
                                'location_id' => $locationId,
                                'check_in_latitude' => $offset['latitude'],
                                'check_in_longitude' => $offset['longitude'],
                                'check_in_address' => $address,
                            ];

                            // Also generate random offset for check-out if attendance has check_out_time
                            if ($att->check_out_time) {
                                $checkoutOffset = \App\Models\SuratTugas::applyRandomOffsetDinas(
                                    (float) $latitude,
                                    (float) $longitude
                                );
                                $updateData['check_out_latitude'] = $checkoutOffset['latitude'];
                                $updateData['check_out_longitude'] = $checkoutOffset['longitude'];
                                $updateData['check_out_address'] = $address;
                            }

                            // Set timestamps to look natural:
                            // - created_at should be near check_in_time
                            // - updated_at should be near check_out_time (if exists)
                            if ($att->check_in_time) {
                                // Add small random offset (0-5 minutes) to created_at
                                $createdAt = $att->check_in_time->copy()->addSeconds(rand(0, 300));
                                $updateData['created_at'] = $createdAt;
                            }

                            if ($att->check_out_time) {
                                // Add small random offset (0-5 minutes) to updated_at
                                $updatedAt = $att->check_out_time->copy()->addSeconds(rand(0, 300));
                                $updateData['updated_at'] = $updatedAt;
                            } elseif ($att->check_in_time) {
                                // If no checkout, updated_at same as created_at
                                $updateData['updated_at'] = $updateData['created_at'] ?? $att->check_in_time;
                            }

                            // Use query builder to bypass Eloquent's automatic timestamp handling
                            \App\Models\Attendance::where('id', $att->id)
                                ->update($updateData);

                            $updatedCount++;
                        }

                        $message = $updatedCount > 1
                            ? "Lokasi berhasil diisi untuk {$updatedCount} kehadiran."
                            : 'Data lokasi dinas telah dilengkapi.';

                        \Filament\Notifications\Notification::make()
                            ->success()
                            ->title('Lokasi berhasil diisi')
                            ->body($message)
                            ->send();
                    })
                    ->modalHeading('Lengkapi Lokasi Dinas')
                    ->modalDescription('Pilih lokasi dinas atau masukkan koordinat manual.')
                    ->modalSubmitActionLabel('Simpan Lokasi')
                    ->modalIcon('heroicon-o-map-pin'),

                Tables\Actions\ViewAction::make(),
                Tables\Actions\Action::make('addActivity')
                    ->label('Tambah Aktivitas')
                    ->icon('heroicon-o-plus')
                    ->color('success')
                    ->url(fn(Attendance $record) => route('filament.employee.resources.my-activities.create') . '?attendance_id=' . $record->id . '&date=' . $record->date->format('Y-m-d')),
            ])
            ->bulkActions([])
            ->emptyStateHeading('Belum ada data kehadiran')
            ->emptyStateDescription('Data kehadiran Anda akan muncul di sini.')
            ->emptyStateIcon('heroicon-o-clock');
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Section::make()
                    ->schema([
                        Infolists\Components\Split::make([
                            Infolists\Components\ImageEntry::make('user.avatar')
                                ->label('')
                                ->circular()
                                ->size(80)
                                ->defaultImageUrl(fn($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->user?->name ?? 'N/A') . '&background=3b82f6&color=fff&bold=true&size=80')
                                ->grow(false),
                            Infolists\Components\Group::make([
                                Infolists\Components\TextEntry::make('user.name')
                                    ->label('')
                                    ->size('lg')
                                    ->weight(FontWeight::Bold),
                                Infolists\Components\TextEntry::make('date')
                                    ->label('')
                                    ->date('l, d F Y')
                                    ->icon('heroicon-o-calendar')
                                    ->iconColor('primary'),
                            ]),
                        ])->from('md'),
                    ]),

                Infolists\Components\Grid::make(3)
                    ->schema([
                        Infolists\Components\Section::make('Check In')
                            ->icon('heroicon-o-arrow-right-circle')
                            ->iconColor('success')
                            ->schema([
                                Infolists\Components\TextEntry::make('check_in_time')
                                    ->label('Waktu')
                                    ->dateTime('H:i')
                                    ->size('lg')
                                    ->weight(FontWeight::Bold)
                                    ->placeholder('--:--'),
                                Infolists\Components\TextEntry::make('check_in_address')
                                    ->label('Alamat')
                                    ->placeholder('-')
                                    ->icon('heroicon-o-map-pin')
                                    ->iconColor('gray'),
                                Infolists\Components\TextEntry::make('check_in_distance')
                                    ->label('Jarak dari Kantor')
                                    ->suffix(' meter')
                                    ->placeholder('-')
                                    ->icon('heroicon-o-arrows-right-left')
                                    ->iconColor('gray'),
                            ]),

                        Infolists\Components\Section::make('Check Out')
                            ->icon('heroicon-o-arrow-left-circle')
                            ->iconColor('danger')
                            ->schema([
                                Infolists\Components\TextEntry::make('check_out_time')
                                    ->label('Waktu')
                                    ->dateTime('H:i')
                                    ->size('lg')
                                    ->weight(FontWeight::Bold)
                                    ->placeholder('--:--'),
                                Infolists\Components\TextEntry::make('check_out_address')
                                    ->label('Alamat')
                                    ->placeholder('-')
                                    ->icon('heroicon-o-map-pin')
                                    ->iconColor('gray'),
                                Infolists\Components\TextEntry::make('check_out_distance')
                                    ->label('Jarak dari Kantor')
                                    ->suffix(' meter')
                                    ->placeholder('-')
                                    ->icon('heroicon-o-arrows-right-left')
                                    ->iconColor('gray'),
                            ]),

                        Infolists\Components\Section::make('Durasi Kerja')
                            ->icon('heroicon-o-clock')
                            ->iconColor('primary')
                            ->schema([
                                Infolists\Components\TextEntry::make('work_duration')
                                    ->label('Durasi')
                                    ->formatStateUsing(function ($state, $record) {
                                        if (!$state) return '-';
                                        
                                        $hours = floor($state / 60);
                                        $minutes = $state % 60;
                                        $durationText = $hours . ' jam ' . $minutes . ' menit';
                                        
                                        // Calculate minimum required duration
                                        $minDuration = null;
                                        $user = $record->user;
                                        $company = $user?->company;
                                        
                                        if ($company && $record->date) {
                                            // Try to get shift for this date
                                            $shift = $user?->getCurrentShift($record->date);
                                            
                                            if ($shift && $shift->start_time && $shift->end_time) {
                                                // Use shift duration (start_time and end_time are datetime objects)
                                                $startTime = \Carbon\Carbon::parse($shift->start_time);
                                                $endTime = \Carbon\Carbon::parse($shift->end_time);
                                                $minDuration = $startTime->diffInMinutes($endTime);
                                            } elseif ($company->work_start_time && $company->work_end_time) {
                                                // Fallback to company work hours
                                                $startTime = \Carbon\Carbon::parse($company->work_start_time);
                                                $endTime = \Carbon\Carbon::parse($company->work_end_time);
                                                $minDuration = $startTime->diffInMinutes($endTime);
                                            }
                                            
                                            // Check if duration is less than minimum
                                            if ($minDuration && $state < $minDuration) {
                                                $minHours = floor($minDuration / 60);
                                                $minMinutes = $minDuration % 60;
                                                $durationText .= ' ⚠️ (Minimal: ' . $minHours . ' jam ' . $minMinutes . ' menit)';
                                            }
                                        }
                                        
                                        return $durationText;
                                    })
                                    ->size('lg')
                                    ->weight(FontWeight::Bold)
                                    ->color(function ($state, $record) {
                                        if (!$state) return null;
                                        
                                        // Calculate minimum required duration
                                        $minDuration = null;
                                        $user = $record->user;
                                        $company = $user?->company;
                                        
                                        if ($company && $record->date) {
                                            // Try to get shift for this date
                                            $shift = $user?->getCurrentShift($record->date);
                                            
                                            if ($shift && $shift->start_time && $shift->end_time) {
                                                // Use shift duration (start_time and end_time are datetime objects)
                                                $startTime = \Carbon\Carbon::parse($shift->start_time);
                                                $endTime = \Carbon\Carbon::parse($shift->end_time);
                                                $minDuration = $startTime->diffInMinutes($endTime);
                                            } elseif ($company->work_start_time && $company->work_end_time) {
                                                // Fallback to company work hours
                                                $startTime = \Carbon\Carbon::parse($company->work_start_time);
                                                $endTime = \Carbon\Carbon::parse($company->work_end_time);
                                                $minDuration = $startTime->diffInMinutes($endTime);
                                            }
                                            
                                            // Return danger color if duration is less than minimum
                                            if ($minDuration && $state < $minDuration) {
                                                return 'danger';
                                            }
                                        }
                                        
                                        return null;
                                    }),
                                Infolists\Components\TextEntry::make('type')
                                    ->label('Tipe')
                                    ->badge()
                                    ->formatStateUsing(fn(string $state): string => match ($state) {
                                        'office' => 'Kantor',
                                        'wfh' => 'WFH',
                                        'business_trip' => 'Dinas',
                                        default => $state,
                                    })
                                    ->color(fn(string $state): string => match ($state) {
                                        'office' => 'primary',
                                        'wfh' => 'info',
                                        'business_trip' => 'warning',
                                        default => 'gray',
                                    }),
                                Infolists\Components\TextEntry::make('status')
                                    ->label('Status')
                                    ->badge()
                                    ->color(fn(string $state): string => match ($state) {
                                        'present' => 'success',
                                        'late' => 'warning',
                                        'early_leave' => 'info',
                                        'absent' => 'danger',
                                        'sick' => 'purple',
                                        'leave' => 'info',
                                        'permission' => 'gray',
                                        default => 'gray',
                                    }),
                                Infolists\Components\TextEntry::make('overtime_duration')
                                    ->label('Lembur')
                                    ->formatStateUsing(function ($state) {
                                        if (!$state) return '-';
                                        $hours = floor($state / 60);
                                        $minutes = $state % 60;
                                        return $hours . ' jam ' . $minutes . ' menit';
                                    })
                                    ->icon('heroicon-o-clock')
                                    ->iconColor('warning'),
                            ]),
                    ]),

                Infolists\Components\Section::make('Peta Lokasi')
                    ->icon('heroicon-o-map')
                    ->iconColor('info')
                    ->schema([
                        Infolists\Components\ViewEntry::make('map')
                            ->label('')
                            ->view('filament.infolists.attendance-map-editable'),
                    ])
                    ->collapsible(),

                Infolists\Components\Section::make('Aktivitas Hari Ini')
                    ->icon('heroicon-o-clipboard-document-list')
                    ->iconColor('success')
                    ->schema([
                        Infolists\Components\RepeatableEntry::make('activities')
                            ->label('')
                            ->schema([
                                Infolists\Components\TextEntry::make('start_time')
                                    ->label('Mulai')
                                    ->time('H:i'),
                                Infolists\Components\TextEntry::make('end_time')
                                    ->label('Selesai')
                                    ->time('H:i'),
                                Infolists\Components\TextEntry::make('activity')
                                    ->label('Aktivitas')
                                    ->columnSpan(2),
                                Infolists\Components\TextEntry::make('output')
                                    ->label('Output')
                                    ->placeholder('-')
                                    ->columnSpan(2),
                            ])
                            ->columns(6)
                            ->columnSpanFull(),
                    ])
                    ->visible(fn($record) => $record?->activities()->exists() ?? false)
                    ->collapsible(),

                Infolists\Components\Section::make('Informasi Tambahan')
                    ->icon('heroicon-o-information-circle')
                    ->iconColor('gray')
                    ->schema([
                        Infolists\Components\TextEntry::make('office.name')
                            ->label('Kantor')
                            ->icon('heroicon-o-map-pin')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('created_at')
                            ->label('Dibuat')
                            ->dateTime('d M Y H:i')
                            ->icon('heroicon-o-calendar'),
                        Infolists\Components\TextEntry::make('updated_at')
                            ->label('Diperbarui')
                            ->dateTime('d M Y H:i')
                            ->icon('heroicon-o-clock'),
                    ])
                    ->columns(3)
                    ->collapsible(),
            ]);
    }

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

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->where('user_id', auth()->id())
            ->orderBy('date', 'desc');
    }

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

    /**
     * Check if user can fill location for incomplete business trip attendance
     * Requires: backdate_enabled AND allow_editable_location
     */
    public static function canFillLocation(): bool
    {
        $user = auth()->user();
        $company = $user?->company;

        if (!$company) {
            return false;
        }

        return ($company->backdate_enabled ?? false) && ($company->allow_editable_location ?? false);
    }
}
