<?php

namespace App\Filament\Resources;

use App\Filament\Resources\AttendanceResource\Pages;
use App\Models\Attendance;
use Filament\Forms;
use Filament\Forms\Form;
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;
use App\Models\Location;

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

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

    protected static ?string $navigationGroup = 'Kehadiran';

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

    protected static ?int $navigationSort = 1;

    protected static ?string $recordTitleAttribute = 'user.name';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Informasi Karyawan')
                            ->description('Data karyawan dan lokasi kehadiran')
                            ->icon('heroicon-o-user')
                            ->schema([
                                Forms\Components\Select::make('user_id')
                                    ->label('Karyawan')
                                    ->relationship('user', 'name', fn ($query) => $query->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')))
                                    ->searchable()
                                    ->preload()
                                    ->required()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-user'),
                                Forms\Components\Select::make('company_id')
                                    ->label('Perusahaan')
                                    ->relationship('company', 'name')
                                    ->searchable()
                                    ->preload()
                                    ->required()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-building-office'),
                                Forms\Components\Select::make('office_id')
                                    ->label('Kantor/Lokasi')
                                    ->relationship('office', 'name')
                                    ->searchable()
                                    ->preload()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-map-pin'),
                                Forms\Components\DatePicker::make('date')
                                    ->label('Tanggal')
                                    ->required()
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-calendar')
                                    ->displayFormat('d M Y'),
                            ])
                            ->columns(2)
                            ->collapsible(),

                        Forms\Components\Section::make('Check In')
                            ->description('Data waktu dan lokasi masuk')
                            ->icon('heroicon-o-arrow-right-circle')
                            ->iconColor('success')
                            ->schema([
                                Forms\Components\DateTimePicker::make('check_in_time')
                                    ->label('Waktu Check In')
                                    ->seconds(false)
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-clock')
                                    ->displayFormat('d M Y H:i'),
                                Forms\Components\Grid::make(2)
                                    ->schema([
                                        Forms\Components\TextInput::make('check_in_latitude')
                                            ->label('Latitude')
                                            ->numeric()
                                            ->step(0.00000001)
                                            ->prefixIcon('heroicon-o-map-pin'),
                                        Forms\Components\TextInput::make('check_in_longitude')
                                            ->label('Longitude')
                                            ->numeric()
                                            ->step(0.00000001)
                                            ->prefixIcon('heroicon-o-map-pin'),
                                    ]),
                                Forms\Components\TextInput::make('check_in_distance')
                                    ->label('Jarak dari Kantor')
                                    ->numeric()
                                    ->suffix('meter')
                                    ->prefixIcon('heroicon-o-arrows-right-left'),
                                Forms\Components\Textarea::make('check_in_address')
                                    ->label('Alamat')
                                    ->rows(2)
                                    ->columnSpanFull(),
                                Forms\Components\Textarea::make('check_in_notes')
                                    ->label('Catatan')
                                    ->rows(2)
                                    ->columnSpanFull(),
                            ])
                            ->columns(2)
                            ->collapsible(),

                        Forms\Components\Section::make('Check Out')
                            ->description('Data waktu dan lokasi pulang')
                            ->icon('heroicon-o-arrow-left-circle')
                            ->iconColor('danger')
                            ->schema([
                                Forms\Components\DateTimePicker::make('check_out_time')
                                    ->label('Waktu Check Out')
                                    ->seconds(false)
                                    ->native(false)
                                    ->prefixIcon('heroicon-o-clock')
                                    ->displayFormat('d M Y H:i'),
                                Forms\Components\Grid::make(2)
                                    ->schema([
                                        Forms\Components\TextInput::make('check_out_latitude')
                                            ->label('Latitude')
                                            ->numeric()
                                            ->step(0.00000001)
                                            ->prefixIcon('heroicon-o-map-pin'),
                                        Forms\Components\TextInput::make('check_out_longitude')
                                            ->label('Longitude')
                                            ->numeric()
                                            ->step(0.00000001)
                                            ->prefixIcon('heroicon-o-map-pin'),
                                    ]),
                                Forms\Components\TextInput::make('check_out_distance')
                                    ->label('Jarak dari Kantor')
                                    ->numeric()
                                    ->suffix('meter')
                                    ->prefixIcon('heroicon-o-arrows-right-left'),
                                Forms\Components\Textarea::make('check_out_address')
                                    ->label('Alamat')
                                    ->rows(2)
                                    ->columnSpanFull(),
                                Forms\Components\Textarea::make('check_out_notes')
                                    ->label('Catatan')
                                    ->rows(2)
                                    ->columnSpanFull(),
                            ])
                            ->columns(2)
                            ->collapsible()
                            ->collapsed(),
                    ])
                    ->columnSpan(['lg' => 2]),

                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Tipe & Status')
                            ->icon('heroicon-o-tag')
                            ->schema([
                                Forms\Components\ToggleButtons::make('type')
                                    ->label('Tipe Kehadiran')
                                    ->options([
                                        'office' => 'Kantor',
                                        'wfh' => 'WFH',
                                        'business_trip' => 'Dinas',
                                    ])
                                    ->icons([
                                        'office' => 'heroicon-o-building-office',
                                        'wfh' => 'heroicon-o-home',
                                        'business_trip' => 'heroicon-o-paper-airplane',
                                    ])
                                    ->colors([
                                        'office' => 'primary',
                                        'wfh' => 'info',
                                        'business_trip' => 'warning',
                                    ])
                                    ->required()
                                    ->inline()
                                    ->columnSpanFull(),
                                Forms\Components\ToggleButtons::make('status')
                                    ->label('Status Kehadiran')
                                    ->options([
                                        'present' => 'Hadir',
                                        'late' => 'Terlambat',
                                        'early_leave' => 'Pulang Awal',
                                        'absent' => 'Tidak Hadir',
                                        'incomplete' => 'Tidak Lengkap',
                                    ])
                                    ->icons([
                                        'present' => 'heroicon-o-check-circle',
                                        'late' => 'heroicon-o-clock',
                                        'early_leave' => 'heroicon-o-arrow-left-circle',
                                        'absent' => 'heroicon-o-x-circle',
                                        'incomplete' => 'heroicon-o-exclamation-circle',
                                    ])
                                    ->colors([
                                        'present' => 'success',
                                        'late' => 'warning',
                                        'early_leave' => 'info',
                                        'absent' => 'danger',
                                        'incomplete' => 'gray',
                                    ])
                                    ->required()
                                    ->default('present')
                                    ->inline()
                                    ->columnSpanFull(),
                            ]),

                        Forms\Components\Section::make('Durasi Kerja')
                            ->icon('heroicon-o-clock')
                            ->schema([
                                Forms\Components\TextInput::make('work_duration')
                                    ->label('Durasi Kerja')
                                    ->numeric()
                                    ->suffix('menit')
                                    ->prefixIcon('heroicon-o-clock')
                                    ->helperText('Total waktu kerja dalam menit'),
                                Forms\Components\TextInput::make('overtime_duration')
                                    ->label('Durasi Lembur')
                                    ->numeric()
                                    ->suffix('menit')
                                    ->prefixIcon('heroicon-o-plus-circle')
                                    ->helperText('Waktu lembur dalam menit'),
                            ])
                            ->collapsible()
                            ->collapsed(),
                    ])
                    ->columnSpan(['lg' => 1]),
            ])
            ->columns(3);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('user.avatar')
                    ->label('')
                    ->circular()
                    ->size(40)
                    ->defaultImageUrl(fn($record) => 'https://ui-avatars.com/api/?name=' . urlencode($record->user?->name ?? 'N/A') . '&background=1565C0&color=fff&bold=true'),

                Tables\Columns\TextColumn::make('user.name')
                    ->label('Karyawan')
                    ->weight(FontWeight::Bold)
                    ->searchable()
                    ->sortable(),

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

                Tables\Columns\TextColumn::make('check_in_time')
                    ->label('Masuk')
                    ->time('H:i')
                    ->icon('heroicon-o-arrow-right-circle')
                    ->iconColor('success')
                    ->sortable(),

                Tables\Columns\TextColumn::make('check_out_time')
                    ->label('Pulang')
                    ->time('H:i')
                    ->icon('heroicon-o-arrow-left-circle')
                    ->iconColor('danger')
                    ->placeholder('--:--')
                    ->sortable(),

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

                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 untuk mengisi';
                        }
                        return null;
                    }),

                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->formatStateUsing(fn(string $state): string => match ($state) {
                        'present' => 'Hadir',
                        'late' => 'Terlambat',
                        'early_leave' => 'Pulang Awal',
                        'absent' => 'Tidak Hadir',
                        'incomplete' => 'Belum Checkout',
                        default => $state,
                    })
                    ->color(fn(string $state): string => match ($state) {
                        'present' => 'success',
                        'late' => 'warning',
                        'early_leave' => 'info',
                        'absent' => 'danger',
                        'incomplete' => 'gray',
                        default => 'gray',
                    }),

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

                Tables\Columns\TextColumn::make('check_in_distance')
                    ->label('Jarak')
                    ->suffix(' m')
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('type')
                    ->label('Tipe')
                    ->options([
                        'office' => 'Kantor',
                        'wfh' => 'WFH',
                        'business_trip' => 'Perjalanan Dinas',
                    ])
                    ->native(false)
                    ->indicator('Tipe'),
                Tables\Filters\SelectFilter::make('status')
                    ->label('Status')
                    ->options([
                        'present' => 'Hadir',
                        'late' => 'Terlambat',
                        'early_leave' => 'Pulang Awal',
                        'absent' => 'Tidak Hadir',
                        'incomplete' => 'Tidak Lengkap',
                    ])
                    ->native(false)
                    ->indicator('Status'),
                Tables\Filters\SelectFilter::make('user_id')
                    ->label('Karyawan')
                    ->relationship('user', 'name')
                    ->searchable()
                    ->preload()
                    ->native(false)
                    ->indicator('Karyawan'),
                Tables\Filters\Filter::make('date_range')
                    ->form([
                        Forms\Components\DatePicker::make('from')
                            ->label('Dari Tanggal')
                            ->native(false)
                            ->prefixIcon('heroicon-o-calendar'),
                        Forms\Components\DatePicker::make('until')
                            ->label('Sampai Tanggal')
                            ->native(false)
                            ->prefixIcon('heroicon-o-calendar'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'], fn($q) => $q->whereDate('date', '>=', $data['from']))
                            ->when($data['until'], fn($q) => $q->whereDate('date', '<=', $data['until']));
                    })
                    ->columns(2)
                    ->indicateUsing(function (array $data): ?string {
                        if (!$data['from'] && !$data['until']) {
                            return null;
                        }
                        return 'Periode: ' . ($data['from'] ?? '...') . ' - ' . ($data['until'] ?? '...');
                    }),
                Tables\Filters\Filter::make('today')
                    ->label('Hari Ini')
                    ->query(fn(Builder $query): Builder => $query->whereDate('date', today()))
                    ->toggle(),
                Tables\Filters\Filter::make('incomplete')
                    ->label('Belum Checkout')
                    ->query(fn(Builder $query): Builder => $query->whereNull('check_out_time'))
                    ->toggle(),
                Tables\Filters\Filter::make('business_trip_no_location')
                    ->label('Dinas Tanpa Lokasi')
                    ->query(fn(Builder $query): Builder => $query->businessTripIncompleteLocation())
                    ->toggle()
                    ->indicator('Dinas Tanpa Lokasi')
                    ->visible(fn(): bool => self::canFillLocation()),
            ])
            ->filtersFormColumns(2)
            ->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) {
                        // Check for ALL active ST on this date (could be multiple)
                        $allActiveST = \App\Models\SuratTugas::findAllActiveForUserOnDate(
                            $record->user_id,
                            $record->date
                        );

                        $schema = [];

                        // If ST detected, show info and option
                        if ($allActiveST->isNotEmpty()) {
                            // Build ST options for dropdown
                            $stOptions = $allActiveST->mapWithKeys(function ($st) {
                                $label = $st->location_name ?? 'Lokasi tidak diset';
                                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();

                            $firstST = $allActiveST->first();
                            $stCount = $allActiveST->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 (when multiple ST available)
                            $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()
                                ->afterStateUpdated(function ($state, Forms\Set $set) use ($record) {
                                    if ($state) {
                                        $st = \App\Models\SuratTugas::find($state);
                                        if ($st) {
                                            // Get overlapping dates for this ST
                                            $overlappingDates = $st->getOverlappingAttendanceDates($record->user_id);
                                            $set('available_dates', $overlappingDates);
                                        }
                                    }
                                })
                                ->helperText('Pilih ST yang akan digunakan untuk mengisi lokasi');

                            // Show ST details when selected
                            $schema[] = Forms\Components\Placeholder::make('st_details')
                                ->label('Detail ST Terpilih')
                                ->content(function ($get) {
                                    $stId = $get('st_id');
                                    if (!$stId) return '-';
                                    $st = \App\Models\SuratTugas::with('location')->find($stId);
                                    if (!$st) return '-';

                                    $coords = $st->getLocationCoordinates();
                                    $coordText = $coords ? $coords['latitude'] . ', ' . $coords['longitude'] : 'Tidak tersedia';

                                    return new \Illuminate\Support\HtmlString(
                                        '<div class="text-sm space-y-1">' .
                                        '<p><strong>Lokasi:</strong> ' . e($st->location_name ?? '-') . '</p>' .
                                        '<p><strong>Koordinat:</strong> ' . $coordText . '</p>' .
                                        '<p><strong>Periode:</strong> ' . $st->tanggal_mulai->format('d M Y') . ' - ' . $st->tanggal_selesai->format('d M Y') . '</p>' .
                                        '</div>'
                                    );
                                })
                                ->visible(fn($get) => $get('location_source') === 'st' && $get('st_id'))
                                ->columnSpanFull();

                            // Checkbox with inline date preview for multi-date fill
                            $schema[] = Forms\Components\Checkbox::make('apply_to_range')
                                ->label(function ($get) use ($record) {
                                    $stId = $get('st_id');
                                    if (!$stId) return 'Terapkan ke tanggal dinas lainnya';

                                    $st = \App\Models\SuratTugas::find($stId);
                                    if (!$st) return 'Terapkan ke tanggal dinas lainnya';

                                    $dates = $st->getOverlappingAttendanceDates($record->user_id);
                                    if (empty($dates)) {
                                        return 'Tidak ada tanggal lain yang perlu diisi';
                                    }

                                    $count = count($dates);
                                    $preview = collect($dates)
                                        ->take(3)
                                        ->map(fn($d) => \Carbon\Carbon::parse($d)->format('d M'))
                                        ->join(', ');
                                    if ($count > 3) {
                                        $preview .= ' +' . ($count - 3) . ' lainnya';
                                    }

                                    return "Terapkan juga ke {$count} tanggal lain ({$preview})";
                                })
                                ->default(false)
                                ->visible(function ($get) use ($record) {
                                    if ($get('location_source') !== 'st' || !$get('st_id')) return false;

                                    $st = \App\Models\SuratTugas::find($get('st_id'));
                                    if (!$st) return false;

                                    $dates = $st->getOverlappingAttendanceDates($record->user_id);
                                    return !empty($dates);
                                })
                                ->columnSpanFull();

                        } else {
                            // No ST detected - show ToggleButtons for location source
                            $schema[] = Forms\Components\ToggleButtons::make('location_source')
                                ->label('Sumber Lokasi')
                                ->options([
                                    'existing' => 'Pilih Lokasi',
                                    'manual' => '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 ($record) {
                                return Location::active()
                                    ->forCompany($record->company_id)
                                    ->where('allow_business_trip', true)
                                    ->ordered()
                                    ->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']));

                        // Manual input fields (only visible for manual mode)
                        $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();

                        $schema[] = Forms\Components\Grid::make(2)
                            ->schema([
                                Forms\Components\TextInput::make('check_in_latitude')
                                    ->label('Latitude')
                                    ->numeric()
                                    ->step(0.000001)
                                    ->required(fn($get) => $get('location_source') === 'manual')
                                    ->prefixIcon('heroicon-o-map-pin')
                                    ->placeholder('-6.123456'),
                                Forms\Components\TextInput::make('check_in_longitude')
                                    ->label('Longitude')
                                    ->numeric()
                                    ->step(0.000001)
                                    ->required(fn($get) => $get('location_source') === 'manual')
                                    ->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 {
                        $locationId = null;
                        $baseLat = null;
                        $baseLon = null;
                        $address = null;

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

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

                        // Check if apply to range is enabled
                        $applyToRange = $data['apply_to_range'] ?? false;

                        if ($applyToRange && isset($data['st_id'])) {
                            // Get all attendance dates within ST range that need location
                            $st = \App\Models\SuratTugas::find($data['st_id']);
                            $datesToUpdate = $st ? $st->getOverlappingAttendanceDates($record->user_id) : [];

                            // Also include current record's date
                            $currentDate = $record->date->format('Y-m-d');
                            if (!in_array($currentDate, $datesToUpdate)) {
                                $datesToUpdate[] = $currentDate;
                            }

                            $updatedCount = 0;
                            foreach ($datesToUpdate as $dateStr) {
                                $attendance = Attendance::where('user_id', $record->user_id)
                                    ->where('type', 'business_trip')
                                    ->whereDate('date', $dateStr)
                                    ->first();

                                if ($attendance) {
                                    // Generate unique random offset for each day's check-in (5-50 meter for dinas)
                                    $checkinOffset = \App\Models\SuratTugas::applyRandomOffsetDinas($baseLat, $baseLon);

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

                                    // Generate different random offset for check-out (5-50 meter for dinas)
                                    if ($attendance->check_out_time) {
                                        $checkoutOffset = \App\Models\SuratTugas::applyRandomOffsetDinas($baseLat, $baseLon);
                                        $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 ($attendance->check_in_time) {
                                        $createdAt = $attendance->check_in_time->copy()->addSeconds(rand(0, 300));
                                        $updateData['created_at'] = $createdAt;
                                    }

                                    if ($attendance->check_out_time) {
                                        $updatedAt = $attendance->check_out_time->copy()->addSeconds(rand(0, 300));
                                        $updateData['updated_at'] = $updatedAt;
                                    } elseif ($attendance->check_in_time) {
                                        $updateData['updated_at'] = $updateData['created_at'] ?? $attendance->check_in_time;
                                    }

                                    // Use query builder to bypass Eloquent's automatic timestamp handling
                                    Attendance::where('id', $attendance->id)->update($updateData);
                                    $updatedCount++;
                                }
                            }

                            \Filament\Notifications\Notification::make()
                                ->success()
                                ->title('Lokasi berhasil diisi')
                                ->body("Data lokasi dinas telah dilengkapi untuk {$updatedCount} tanggal.")
                                ->send();
                        } else {
                            // Single record update (5-50 meter for dinas)
                            $checkinOffset = \App\Models\SuratTugas::applyRandomOffsetDinas($baseLat, $baseLon);

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

                            // Also generate random offset for check-out if attendance has check_out_time (5-50 meter for dinas)
                            if ($record->check_out_time) {
                                $checkoutOffset = \App\Models\SuratTugas::applyRandomOffsetDinas($baseLat, $baseLon);
                                $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 ($record->check_in_time) {
                                $createdAt = $record->check_in_time->copy()->addSeconds(rand(0, 300));
                                $updateData['created_at'] = $createdAt;
                            }

                            if ($record->check_out_time) {
                                $updatedAt = $record->check_out_time->copy()->addSeconds(rand(0, 300));
                                $updateData['updated_at'] = $updatedAt;
                            } elseif ($record->check_in_time) {
                                $updateData['updated_at'] = $updateData['created_at'] ?? $record->check_in_time;
                            }

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

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

                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make()
                        ->icon('heroicon-o-eye'),
                    Tables\Actions\EditAction::make()
                        ->icon('heroicon-o-pencil-square'),
                    Tables\Actions\DeleteAction::make()
                        ->icon('heroicon-o-trash'),
                ])
                    ->icon('heroicon-m-ellipsis-vertical')
                    ->tooltip('Aksi'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->icon('heroicon-o-trash'),
                ]),
            ])
            ->defaultSort('date', 'desc')
            ->striped()
            ->poll('60s');
    }

    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),
                                Infolists\Components\TextEntry::make('check_in_address')
                                    ->label('Alamat')
                                    ->placeholder('-'),
                                Infolists\Components\TextEntry::make('check_in_distance')
                                    ->label('Jarak')
                                    ->suffix(' meter')
                                    ->placeholder('-'),
                                Infolists\Components\TextEntry::make('check_in_notes')
                                    ->label('Catatan')
                                    ->placeholder('-'),
                            ]),

                        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('-'),
                                Infolists\Components\TextEntry::make('check_out_distance')
                                    ->label('Jarak')
                                    ->suffix(' meter')
                                    ->placeholder('-'),
                                Infolists\Components\TextEntry::make('check_out_notes')
                                    ->label('Catatan')
                                    ->placeholder('-'),
                            ]),

                        Infolists\Components\Section::make('Ringkasan')
                            ->icon('heroicon-o-chart-bar')
                            ->iconColor('primary')
                            ->schema([
                                Infolists\Components\TextEntry::make('work_duration')
                                    ->label('Durasi Kerja')
                                    ->formatStateUsing(function ($state) {
                                        if (!$state) return '-';
                                        $hours = floor($state / 60);
                                        $minutes = $state % 60;
                                        return $hours . ' jam ' . $minutes . ' menit';
                                    })
                                    ->size('lg')
                                    ->weight(FontWeight::Bold),
                                Infolists\Components\TextEntry::make('type')
                                    ->label('Tipe')
                                    ->badge()
                                    ->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',
                                        'incomplete' => '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';
                                    }),
                            ]),
                    ]),

                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('Informasi Tambahan')
                    ->icon('heroicon-o-information-circle')
                    ->schema([
                        Infolists\Components\TextEntry::make('company.name')
                            ->label('Perusahaan')
                            ->icon('heroicon-o-building-office'),
                        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'),
                        Infolists\Components\TextEntry::make('updated_at')
                            ->label('Diperbarui')
                            ->dateTime('d M Y H:i'),
                    ])
                    ->columns(4)
                    ->collapsible(),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAttendances::route('/'),
            'create' => Pages\CreateAttendance::route('/create'),
            'view' => Pages\ViewAttendance::route('/{record}'),
            'edit' => Pages\EditAttendance::route('/{record}/edit'),
        ];
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::whereDate('date', today())->count() ?: null;
    }

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

    public static function getGloballySearchableAttributes(): array
    {
        return ['user.name', 'user.email', 'check_in_address', 'check_out_address'];
    }

    /**
     * Hide super_admin attendance from all lists
     */
    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();

        // Hide super_admin attendance (using Spatie roles)
        $query->whereHas('user', function ($q) {
            $q->whereDoesntHave('roles', function ($r) {
                $r->where('name', 'super_admin');
            });
        });

        // Admin biasa hanya lihat company mereka
        $user = auth()->user();
        if ($user && !$user->hasRole('super_admin')) {
            $query->where('company_id', $user->company_id);
        }

        return $query;
    }

    /**
     * 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();

        // Super admin can always fill location
        if ($user?->hasRole('super_admin')) {
            return true;
        }

        $company = $user?->company;

        if (!$company) {
            return false;
        }

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