<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SuratTugasResource\Pages;
use App\Models\SuratTugas;
use App\Models\Location;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Infolists;
use Filament\Infolists\Infolist;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Support\Enums\FontWeight;
use Illuminate\Database\Eloquent\Builder;

class SuratTugasResource extends Resource
{
    protected static ?string $model = SuratTugas::class;

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

    protected static ?string $navigationGroup = 'Perjalanan Dinas';

    protected static ?string $navigationLabel = 'Surat Tugas';

    protected static ?string $modelLabel = 'Surat Tugas';

    protected static ?string $pluralModelLabel = 'Surat Tugas';

    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Informasi Surat Tugas')
                            ->description('Data dasar surat tugas')
                            ->icon('heroicon-o-document-text')
                            ->schema([
                                Forms\Components\Select::make('company_id')
                                    ->label('Perusahaan')
                                    ->relationship('company', 'name')
                                    ->searchable()
                                    ->preload()
                                    ->required()
                                    ->native(false)
                                    ->default(fn() => auth()->user()->company_id)
                                    ->disabled(fn() => !auth()->user()->hasRole('super_admin'))
                                    ->dehydrated(true),
                                Forms\Components\TextInput::make('no_st')
                                    ->label('Nomor Surat Tugas')
                                    ->maxLength(100)
                                    ->placeholder('ST/001/2026')
                                    ->prefixIcon('heroicon-o-document-duplicate')
                                    ->helperText('Opsional - bisa diisi nanti'),
                                Forms\Components\DatePicker::make('tanggal_mulai')
                                    ->label('Tanggal Mulai')
                                    ->required()
                                    ->native(false)
                                    ->displayFormat('d M Y')
                                    ->prefixIcon('heroicon-o-calendar'),
                                Forms\Components\DatePicker::make('tanggal_selesai')
                                    ->label('Tanggal Selesai')
                                    ->required()
                                    ->native(false)
                                    ->displayFormat('d M Y')
                                    ->afterOrEqual('tanggal_mulai')
                                    ->prefixIcon('heroicon-o-calendar'),
                                Forms\Components\Textarea::make('keterangan')
                                    ->label('Keterangan')
                                    ->rows(2)
                                    ->columnSpanFull()
                                    ->placeholder('Keterangan tambahan mengenai surat tugas...'),
                            ])
                            ->columns(2),

                        Forms\Components\Section::make('Lokasi Dinas')
                            ->description('Pilih lokasi dari daftar atau input manual')
                            ->icon('heroicon-o-map-pin')
                            ->schema([
                                Forms\Components\Radio::make('location_type')
                                    ->label('Sumber Lokasi')
                                    ->options([
                                        'existing' => 'Pilih dari Lokasi Tersedia',
                                        'custom' => 'Input Manual',
                                    ])
                                    ->default('existing')
                                    ->inline()
                                    ->live()
                                    ->columnSpanFull()
                                    ->afterStateHydrated(function ($state, Forms\Set $set, $record) {
                                        // Determine location type based on existing data
                                        if ($record) {
                                            if ($record->location_id) {
                                                $set('location_type', 'existing');
                                            } elseif ($record->custom_location_name || $record->custom_latitude) {
                                                $set('location_type', 'custom');
                                            }
                                        }
                                    }),

                                // Existing location selection
                                Forms\Components\Select::make('location_id')
                                    ->label('Lokasi Dinas')
                                    ->options(function () {
                                        $user = auth()->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()
                                    ->native(false)
                                    ->visible(fn($get) => $get('location_type') === 'existing')
                                    ->required(fn($get) => $get('location_type') === 'existing')
                                    ->columnSpanFull()
                                    ->helperText('Pilih lokasi yang sudah terdaftar di sistem'),

                                // Custom location inputs
                                Forms\Components\TextInput::make('custom_location_name')
                                    ->label('Nama Lokasi')
                                    ->maxLength(255)
                                    ->visible(fn($get) => $get('location_type') === 'custom')
                                    ->required(fn($get) => $get('location_type') === 'custom')
                                    ->placeholder('Contoh: Kantor BPKP Jawa Timur')
                                    ->columnSpanFull(),
                                Forms\Components\Grid::make(2)
                                    ->schema([
                                        Forms\Components\TextInput::make('custom_latitude')
                                            ->label('Latitude')
                                            ->numeric()
                                            ->step(0.00000001)
                                            ->prefixIcon('heroicon-o-map-pin')
                                            ->placeholder('-6.123456')
                                            ->helperText('Contoh: -6.200000'),
                                        Forms\Components\TextInput::make('custom_longitude')
                                            ->label('Longitude')
                                            ->numeric()
                                            ->step(0.00000001)
                                            ->prefixIcon('heroicon-o-map-pin')
                                            ->placeholder('106.123456')
                                            ->helperText('Contoh: 106.816666'),
                                    ])
                                    ->visible(fn($get) => $get('location_type') === 'custom'),
                                Forms\Components\Textarea::make('custom_address')
                                    ->label('Alamat')
                                    ->rows(2)
                                    ->visible(fn($get) => $get('location_type') === 'custom')
                                    ->columnSpanFull()
                                    ->placeholder('Alamat lengkap lokasi...'),
                            ])
                            ->columns(2),
                    ])
                    ->columnSpan(['lg' => 2]),

                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Karyawan yang Ditugaskan')
                            ->description('Pilih satu atau lebih karyawan')
                            ->icon('heroicon-o-users')
                            ->schema([
                                Forms\Components\Select::make('users')
                                    ->label('Karyawan')
                                    ->relationship(
                                        'users',
                                        'name',
                                        fn($query) => $query
                                            ->where('is_active', true)
                                            ->where('approval_status', 'approved')
                                            ->whereDoesntHave('roles', fn($r) => $r->where('name', 'super_admin'))
                                            ->when(
                                                !auth()->user()->hasRole('super_admin'),
                                                fn($q) => $q->where('company_id', auth()->user()->company_id)
                                            )
                                            ->orderBy('name')
                                    )
                                    ->multiple()
                                    ->searchable()
                                    ->preload()
                                    ->native(false)
                                    ->helperText('Kosongkan jika belum ada yang ditugaskan'),
                            ]),

                        Forms\Components\Section::make('Status')
                            ->icon('heroicon-o-flag')
                            ->schema([
                                Forms\Components\Toggle::make('is_active')
                                    ->label('Aktif')
                                    ->default(true)
                                    ->helperText('Nonaktifkan jika ST sudah tidak berlaku'),
                            ]),

                        Forms\Components\Section::make('Ringkasan')
                            ->icon('heroicon-o-information-circle')
                            ->schema([
                                Forms\Components\Placeholder::make('duration')
                                    ->label('Durasi')
                                    ->content(function ($get) {
                                        $start = $get('tanggal_mulai');
                                        $end = $get('tanggal_selesai');
                                        if ($start && $end) {
                                            $days = \Carbon\Carbon::parse($start)->diffInDays(\Carbon\Carbon::parse($end)) + 1;
                                            return $days . ' hari';
                                        }
                                        return '-';
                                    }),
                                Forms\Components\Placeholder::make('created_info')
                                    ->label('Dibuat oleh')
                                    ->content(fn($record) => $record?->createdBy?->name ?? '-')
                                    ->visible(fn(string $operation): bool => $operation !== 'create'),
                            ])
                            ->visible(fn(string $operation): bool => $operation !== 'create'),
                    ])
                    ->columnSpan(['lg' => 1]),
            ])
            ->columns(3);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('no_st')
                    ->label('No. ST')
                    ->searchable()
                    ->sortable()
                    ->placeholder('-')
                    ->icon('heroicon-o-document-text'),

                Tables\Columns\TextColumn::make('location_name')
                    ->label('Lokasi')
                    ->getStateUsing(fn($record) => $record->location_name)
                    ->searchable(query: function (Builder $query, string $search) {
                        return $query->where(function ($q) use ($search) {
                            $q->whereHas('location', fn($l) => $l->where('name', 'like', "%{$search}%"))
                              ->orWhere('custom_location_name', 'like', "%{$search}%");
                        });
                    })
                    ->weight(FontWeight::Bold)
                    ->wrap(),

                Tables\Columns\TextColumn::make('tanggal_mulai')
                    ->label('Mulai')
                    ->date('d M Y')
                    ->sortable()
                    ->icon('heroicon-o-calendar'),

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

                Tables\Columns\TextColumn::make('users.name')
                    ->label('Karyawan')
                    ->badge()
                    ->separator(', ')
                    ->wrap()
                    ->searchable()
                    ->limitList(3)
                    ->expandableLimitedList(),

                Tables\Columns\TextColumn::make('duration')
                    ->label('Durasi')
                    ->getStateUsing(fn($record) => $record->getDurationDays() . ' hari')
                    ->badge()
                    ->color('info'),

                Tables\Columns\IconColumn::make('is_active')
                    ->label('Aktif')
                    ->boolean()
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Dibuat')
                    ->dateTime('d M Y H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Status Aktif'),
                Tables\Filters\Filter::make('active_now')
                    ->label('Berlaku Hari Ini')
                    ->query(fn(Builder $query) => $query
                        ->where('is_active', true)
                        ->where('tanggal_mulai', '<=', today())
                        ->where('tanggal_selesai', '>=', today())
                    )
                    ->toggle(),
                Tables\Filters\Filter::make('date_range')
                    ->form([
                        Forms\Components\DatePicker::make('from')
                            ->label('Dari Tanggal')
                            ->native(false),
                        Forms\Components\DatePicker::make('until')
                            ->label('Sampai Tanggal')
                            ->native(false),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'], fn($q) => $q->where('tanggal_mulai', '>=', $data['from']))
                            ->when($data['until'], fn($q) => $q->where('tanggal_selesai', '<=', $data['until']));
                    }),
                Tables\Filters\SelectFilter::make('users')
                    ->label('Karyawan')
                    ->relationship('users', 'name')
                    ->searchable()
                    ->preload()
                    ->multiple(),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('tanggal_mulai', 'desc');
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Section::make('Informasi Surat Tugas')
                    ->icon('heroicon-o-document-text')
                    ->schema([
                        Infolists\Components\TextEntry::make('no_st')
                            ->label('Nomor ST')
                            ->placeholder('-')
                            ->icon('heroicon-o-document-duplicate'),
                        Infolists\Components\TextEntry::make('tanggal_mulai')
                            ->label('Tanggal Mulai')
                            ->date('d F Y')
                            ->icon('heroicon-o-calendar'),
                        Infolists\Components\TextEntry::make('tanggal_selesai')
                            ->label('Tanggal Selesai')
                            ->date('d F Y'),
                        Infolists\Components\TextEntry::make('duration')
                            ->label('Durasi')
                            ->getStateUsing(fn($record) => $record->getDurationDays() . ' hari')
                            ->badge()
                            ->color('info'),
                    ])
                    ->columns(4),

                Infolists\Components\Section::make('Lokasi Dinas')
                    ->icon('heroicon-o-map-pin')
                    ->schema([
                        Infolists\Components\TextEntry::make('location_name')
                            ->label('Nama Lokasi')
                            ->getStateUsing(fn($record) => $record->location_name)
                            ->weight(FontWeight::Bold),
                        Infolists\Components\TextEntry::make('coordinates')
                            ->label('Koordinat')
                            ->getStateUsing(function ($record) {
                                $coords = $record->getLocationCoordinates();
                                if ($coords) {
                                    return $coords['latitude'] . ', ' . $coords['longitude'];
                                }
                                return '-';
                            }),
                        Infolists\Components\TextEntry::make('address')
                            ->label('Alamat')
                            ->getStateUsing(function ($record) {
                                $coords = $record->getLocationCoordinates();
                                return $coords['address'] ?? '-';
                            })
                            ->columnSpan(2),
                    ])
                    ->columns(4),

                Infolists\Components\Section::make('Karyawan yang Ditugaskan')
                    ->icon('heroicon-o-users')
                    ->schema([
                        Infolists\Components\TextEntry::make('users.name')
                            ->label('')
                            ->badge()
                            ->separator(', ')
                            ->placeholder('Belum ada karyawan yang ditugaskan'),
                    ]),

                Infolists\Components\Section::make('Keterangan')
                    ->icon('heroicon-o-chat-bubble-left-right')
                    ->schema([
                        Infolists\Components\TextEntry::make('keterangan')
                            ->label('')
                            ->placeholder('Tidak ada keterangan'),
                    ])
                    ->visible(fn($record) => $record->keterangan),

                Infolists\Components\Section::make('Informasi Tambahan')
                    ->icon('heroicon-o-information-circle')
                    ->schema([
                        Infolists\Components\TextEntry::make('is_active')
                            ->label('Status')
                            ->badge()
                            ->formatStateUsing(fn($state) => $state ? 'Aktif' : 'Tidak Aktif')
                            ->color(fn($state) => $state ? 'success' : 'danger'),
                        Infolists\Components\TextEntry::make('createdBy.name')
                            ->label('Dibuat oleh')
                            ->placeholder('-'),
                        Infolists\Components\TextEntry::make('created_at')
                            ->label('Dibuat pada')
                            ->dateTime('d M Y H:i'),
                        Infolists\Components\TextEntry::make('updated_at')
                            ->label('Diupdate pada')
                            ->dateTime('d M Y H:i'),
                    ])
                    ->columns(4)
                    ->collapsible(),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListSuratTugas::route('/'),
            'create' => Pages\CreateSuratTugas::route('/create'),
            'view' => Pages\ViewSuratTugas::route('/{record}'),
            'edit' => Pages\EditSuratTugas::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();

        $user = auth()->user();
        if ($user && !$user->hasRole('super_admin')) {
            $query->where('company_id', $user->company_id);
        }

        return $query;
    }

    public static function getNavigationBadge(): ?string
    {
        $user = auth()->user();
        $count = static::getModel()::active()
            ->activeOnDate(today())
            ->when(!$user->hasRole('super_admin'), fn($q) => $q->where('company_id', $user->company_id))
            ->count();

        return $count ?: null;
    }

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