<?php

namespace App\Filament\Resources;

use App\Filament\Resources\LocationResource\Pages;
use App\Models\Location;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class LocationResource extends Resource
{
    protected static ?string $model = Location::class;

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

    protected static ?string $navigationGroup = 'Master Data';

    protected static ?string $navigationLabel = 'Lokasi';

    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Lokasi')
                    ->schema([
                        Forms\Components\Select::make('company_id')
                            ->label('Perusahaan')
                            ->relationship('company', 'name')
                            ->searchable()
                            ->preload()
                            ->required(),
                        Forms\Components\TextInput::make('name')
                            ->label('Nama Lokasi')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('code')
                            ->label('Kode')
                            ->maxLength(50)
                            ->unique(ignoreRecord: true),
                        Forms\Components\Select::make('category')
                            ->label('Kategori')
                            ->options([
                                'internal' => 'Internal (Kantor)',
                                'external' => 'Eksternal (Dinas)',
                            ])
                            ->required()
                            ->reactive()
                            ->afterStateUpdated(function ($state, Forms\Set $set) {
                                // Set default values based on category
                                if ($state === 'internal') {
                                    $set('allow_daily_checkin', true);
                                    $set('radius', 100);
                                } else {
                                    $set('allow_daily_checkin', false);
                                    $set('radius', 500);
                                }
                            }),
                        Forms\Components\Select::make('type')
                            ->label('Tipe Lokasi')
                            ->options([
                                'headquarters' => 'Kantor Pusat',
                                'branch' => 'Kantor Cabang',
                                'pemda' => 'Pemerintah Daerah',
                                'kementerian' => 'Kementerian',
                                'lembaga' => 'Lembaga',
                                'other' => 'Lainnya',
                            ])
                            ->required()
                            ->searchable(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Alamat')
                    ->schema([
                        Forms\Components\Textarea::make('address')
                            ->label('Alamat Lengkap')
                            ->columnSpanFull(),
                        Forms\Components\TextInput::make('city')
                            ->label('Kota/Kabupaten')
                            ->maxLength(100),
                        Forms\Components\TextInput::make('province')
                            ->label('Provinsi')
                            ->maxLength(100),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Koordinat & Radius')
                    ->schema([
                        Forms\Components\TextInput::make('latitude')
                            ->label('Latitude')
                            ->numeric()
                            ->step(0.00000001),
                        Forms\Components\TextInput::make('longitude')
                            ->label('Longitude')
                            ->numeric()
                            ->step(0.00000001),
                        Forms\Components\TextInput::make('radius')
                            ->label('Radius (meter)')
                            ->required()
                            ->numeric()
                            ->default(100)
                            ->helperText('Internal: 100m, Eksternal: 500m'),
                    ])
                    ->columns(3),

                Forms\Components\Section::make('Pengaturan & Status')
                    ->schema([
                        Forms\Components\Toggle::make('allow_daily_checkin')
                            ->label('Izinkan Presensi Harian')
                            ->helperText('Lokasi ini bisa dipakai untuk check-in harian')
                            ->default(false),
                        Forms\Components\Toggle::make('allow_business_trip')
                            ->label('Izinkan Tujuan Dinas')
                            ->helperText('Lokasi ini bisa jadi tujuan perjalanan dinas')
                            ->default(true),
                        Forms\Components\Toggle::make('is_primary')
                            ->label('Lokasi Utama')
                            ->helperText('Lokasi ini akan tampil di atas saat user pilih lokasi')
                            ->default(false),
                        Forms\Components\Toggle::make('is_active')
                            ->label('Aktif')
                            ->default(true),
                        Forms\Components\TextInput::make('sort_order')
                            ->label('Urutan')
                            ->numeric()
                            ->default(0)
                            ->helperText('Semakin kecil semakin atas'),
                    ])
                    ->columns(3),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Nama')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('code')
                    ->label('Kode')
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('category')
                    ->label('Kategori')
                    ->badge()
                    ->formatStateUsing(fn(string $state): string => match ($state) {
                        'internal' => 'Internal',
                        'external' => 'Eksternal',
                        default => $state,
                    })
                    ->color(fn(string $state): string => match ($state) {
                        'internal' => 'primary',
                        'external' => 'warning',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('type')
                    ->label('Tipe')
                    ->badge()
                    ->formatStateUsing(fn(string $state): string => match ($state) {
                        'headquarters' => 'Kantor Pusat',
                        'branch' => 'Cabang',
                        'pemda' => 'Pemda',
                        'kementerian' => 'Kementerian',
                        'lembaga' => 'Lembaga',
                        'other' => 'Lainnya',
                        default => $state,
                    })
                    ->color(fn(string $state): string => match ($state) {
                        'headquarters' => 'primary',
                        'branch' => 'info',
                        'pemda' => 'warning',
                        'kementerian' => 'danger',
                        'lembaga' => 'gray',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('city')
                    ->label('Kota')
                    ->searchable(),
                Tables\Columns\TextColumn::make('province')
                    ->label('Provinsi')
                    ->searchable(),
                Tables\Columns\TextColumn::make('company.name')
                    ->label('Perusahaan')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('radius')
                    ->label('Radius')
                    ->suffix(' m')
                    ->sortable(),
                Tables\Columns\IconColumn::make('allow_daily_checkin')
                    ->label('Presensi')
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\IconColumn::make('allow_business_trip')
                    ->label('Dinas')
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\IconColumn::make('is_primary')
                    ->label('Utama')
                    ->boolean()
                    ->trueIcon('heroicon-o-star')
                    ->falseIcon('heroicon-o-minus')
                    ->trueColor('warning'),
                Tables\Columns\IconColumn::make('is_active')
                    ->label('Aktif')
                    ->boolean(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Dibuat')
                    ->dateTime('d M Y')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('category')
                    ->label('Kategori')
                    ->options([
                        'internal' => 'Internal (Kantor)',
                        'external' => 'Eksternal (Dinas)',
                    ]),
                Tables\Filters\SelectFilter::make('type')
                    ->label('Tipe')
                    ->options([
                        'headquarters' => 'Kantor Pusat',
                        'branch' => 'Kantor Cabang',
                        'pemda' => 'Pemerintah Daerah',
                        'kementerian' => 'Kementerian',
                        'lembaga' => 'Lembaga',
                        'other' => 'Lainnya',
                    ]),
                Tables\Filters\SelectFilter::make('province')
                    ->label('Provinsi')
                    ->options(fn() => Location::distinct()->pluck('province', 'province')->toArray()),
                Tables\Filters\TernaryFilter::make('allow_daily_checkin')
                    ->label('Presensi Harian'),
                Tables\Filters\TernaryFilter::make('allow_business_trip')
                    ->label('Tujuan Dinas'),
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Status Aktif'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('name');
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListLocations::route('/'),
            'create' => Pages\CreateLocation::route('/create'),
            'edit' => Pages\EditLocation::route('/{record}/edit'),
        ];
    }
}
