<?php

namespace App\Filament\Pages;

use App\Models\Attendance;
use App\Models\Office;
use Carbon\Carbon;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Pages\Page;
use Illuminate\Support\Collection;

class AttendanceMap extends Page implements HasForms
{
    use InteractsWithForms;

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

    protected static string $view = 'filament.pages.attendance-map';

    protected static ?string $navigationLabel = 'Peta Presensi';

    protected static ?string $title = 'Peta Lokasi Presensi';

    protected static ?string $navigationGroup = 'Kehadiran';

    protected static ?int $navigationSort = 5;

    public ?string $selectedDate = null;
    public ?string $filterType = 'all';

    public function mount(): void
    {
        $this->selectedDate = now()->format('Y-m-d');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                DatePicker::make('selectedDate')
                    ->label('Tanggal')
                    ->native(false)
                    ->displayFormat('d M Y')
                    ->live()
                    ->columnSpan(1),
                Select::make('filterType')
                    ->label('Tampilkan')
                    ->options([
                        'all' => 'Semua',
                        'check_in' => 'Check In Saja',
                        'check_out' => 'Check Out Saja',
                    ])
                    ->default('all')
                    ->live()
                    ->columnSpan(1),
            ])
            ->columns(2)
            ->extraAttributes([
                'class' => 'max-w-2xl'
            ]);
    }

    public function getOffices(): Collection
    {
        return Office::where('is_active', true)
            ->select(['id', 'name', 'latitude', 'longitude', 'radius', 'address'])
            ->get()
            ->map(function ($office) {
                return [
                    'id' => $office->id,
                    'name' => $office->name,
                    'lat' => (float) $office->latitude,
                    'lng' => (float) $office->longitude,
                    'radius' => $office->radius,
                    'address' => $office->address,
                    'type' => 'office',
                ];
            });
    }

    public function getAttendanceMarkers(): Collection
    {
        $query = Attendance::with('user')
            ->whereDate('date', $this->selectedDate)
            // Hide super_admin
            ->whereHas('user', fn ($q) => $q->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')));

        $attendances = $query->get();
        $markers = collect();

        foreach ($attendances as $attendance) {
            // Check-in marker
            if (($this->filterType === 'all' || $this->filterType === 'check_in')
                && $attendance->check_in_latitude && $attendance->check_in_longitude) {
                $markers->push([
                    'id' => 'in_' . $attendance->id,
                    'name' => $attendance->user->name,
                    'lat' => (float) $attendance->check_in_latitude,
                    'lng' => (float) $attendance->check_in_longitude,
                    'time' => $attendance->check_in_time?->format('H:i'),
                    'address' => $attendance->check_in_address,
                    'type' => 'check_in',
                    'status' => $attendance->status,
                    'distance' => $attendance->check_in_distance,
                ]);
            }

            // Check-out marker
            if (($this->filterType === 'all' || $this->filterType === 'check_out')
                && $attendance->check_out_latitude && $attendance->check_out_longitude) {
                $markers->push([
                    'id' => 'out_' . $attendance->id,
                    'name' => $attendance->user->name,
                    'lat' => (float) $attendance->check_out_latitude,
                    'lng' => (float) $attendance->check_out_longitude,
                    'time' => $attendance->check_out_time?->format('H:i'),
                    'address' => $attendance->check_out_address,
                    'type' => 'check_out',
                    'status' => $attendance->status,
                    'distance' => $attendance->check_out_distance,
                ]);
            }
        }

        return $markers;
    }

    public function getMapCenter(): array
    {
        // Default to first office or Jakarta
        $office = Office::where('is_active', true)->first();

        if ($office) {
            return [
                'lat' => (float) $office->latitude,
                'lng' => (float) $office->longitude,
            ];
        }

        // Default Jakarta
        return [
            'lat' => -6.2088,
            'lng' => 106.8456,
        ];
    }

    public function getStats(): array
    {
        $attendances = Attendance::whereDate('date', $this->selectedDate)
            // Hide super_admin
            ->whereHas('user', fn ($q) => $q->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')))
            ->get();

        return [
            'total' => $attendances->count(),
            'checked_in' => $attendances->whereNotNull('check_in_time')->count(),
            'checked_out' => $attendances->whereNotNull('check_out_time')->count(),
            'in_radius' => $attendances->where('check_in_distance', '<=', 100)->count(),
            'out_radius' => $attendances->where('check_in_distance', '>', 100)->count(),
        ];
    }
}
