<?php

namespace App\Filament\Resources;

use App\Filament\Resources\DocumentResource\Pages;
use App\Models\Document;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Storage;

class DocumentResource extends Resource
{
    protected static ?string $model = Document::class;

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

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

    protected static ?string $navigationLabel = 'Dokumen Pendukung';

    protected static ?int $navigationSort = 3;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Dokumen')
                    ->schema([
                        Forms\Components\Select::make('business_trip_id')
                            ->label('Perjalanan Dinas')
                            ->relationship('businessTrip', 'title')
                            ->searchable()
                            ->preload(),
                        Forms\Components\Select::make('user_id')
                            ->label('Pengirim')
                            ->relationship('user', 'name', fn ($query) => $query->whereDoesntHave('roles', fn ($r) => $r->where('name', 'super_admin')))
                            ->searchable()
                            ->preload()
                            ->required()
                            ->default(auth()->id()),
                        Forms\Components\Select::make('type')
                            ->label('Tipe Dokumen')
                            ->options([
                                'tiket_pesawat' => 'Tiket Pesawat',
                                'tiket_kereta' => 'Tiket Kereta',
                                'tiket_bus' => 'Tiket Bus',
                                'boarding_pass' => 'Boarding Pass',
                                'hotel_invoice' => 'Invoice Hotel',
                                'kwitansi_bbm' => 'Kwitansi BBM',
                                'toll_receipt' => 'Struk Tol',
                                'surat_tugas' => 'Surat Tugas',
                                'lainnya' => 'Lainnya',
                            ])
                            ->required()
                            ->searchable(),
                        Forms\Components\Textarea::make('description')
                            ->label('Keterangan')
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Upload File')
                    ->schema([
                        Forms\Components\FileUpload::make('file_path')
                            ->label('File Dokumen')
                            ->required()
                            ->directory('documents')
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'])
                            ->maxSize(5120)
                            ->downloadable()
                            ->openable()
                            ->preserveFilenames()
                            ->getUploadedFileNameForStorageUsing(function ($file) {
                                return time() . '_' . $file->getClientOriginalName();
                            })
                            ->afterStateUpdated(function ($state, Forms\Set $set) {
                                if ($state) {
                                    $set('file_name', $state->getClientOriginalName());
                                    $set('file_type', $state->getMimeType());
                                    $set('file_size', $state->getSize());
                                }
                            }),
                    ]),

                Forms\Components\Section::make('Status')
                    ->schema([
                        Forms\Components\Select::make('status')
                            ->label('Status Approval')
                            ->options([
                                'pending' => 'Menunggu Approval',
                                'approved' => 'Disetujui',
                                'rejected' => 'Ditolak',
                            ])
                            ->default('pending')
                            ->required()
                            ->disabled(fn() => !auth()->user()->hasPermissionTo('approve_documents')),
                        Forms\Components\Toggle::make('hardcopy_received')
                            ->label('Hardcopy Diterima')
                            ->default(false)
                            ->disabled(fn() => !auth()->user()->hasPermissionTo('receive_hardcopy')),
                    ])
                    ->columns(2)
                    ->visible(fn(string $operation): bool => $operation === 'edit'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('user.name')
                    ->label('Pengirim')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('businessTrip.title')
                    ->label('Perjalanan Dinas')
                    ->searchable()
                    ->sortable()
                    ->limit(30),
                Tables\Columns\TextColumn::make('type')
                    ->label('Tipe')
                    ->badge()
                    ->formatStateUsing(fn(string $state): string => match ($state) {
                        'tiket_pesawat' => 'Tiket Pesawat',
                        'tiket_kereta' => 'Tiket Kereta',
                        'tiket_bus' => 'Tiket Bus',
                        'boarding_pass' => 'Boarding Pass',
                        'hotel_invoice' => 'Invoice Hotel',
                        'kwitansi_bbm' => 'Kwitansi BBM',
                        'toll_receipt' => 'Struk Tol',
                        'surat_tugas' => 'Surat Tugas',
                        'lainnya' => 'Lainnya',
                        default => $state,
                    })
                    ->color(fn(string $state): string => match ($state) {
                        'tiket_pesawat', 'tiket_kereta', 'tiket_bus', 'boarding_pass' => 'info',
                        'hotel_invoice' => 'warning',
                        'kwitansi_bbm', 'toll_receipt' => 'success',
                        'surat_tugas' => 'primary',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('file_name')
                    ->label('Nama File')
                    ->searchable()
                    ->limit(25),
                Tables\Columns\TextColumn::make('file_size')
                    ->label('Ukuran')
                    ->formatStateUsing(fn($state) => $state ? number_format($state / 1024, 2) . ' KB' : '-')
                    ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->color(fn(string $state): string => match ($state) {
                        'pending' => 'warning',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn(string $state): string => match ($state) {
                        'pending' => 'Menunggu',
                        'approved' => 'Disetujui',
                        'rejected' => 'Ditolak',
                        default => $state,
                    }),
                Tables\Columns\IconColumn::make('hardcopy_received')
                    ->label('Hardcopy')
                    ->boolean()
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),
                Tables\Columns\TextColumn::make('approvedBy.name')
                    ->label('Disetujui Oleh')
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Tanggal Upload')
                    ->dateTime('d M Y H:i')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('Status')
                    ->options([
                        'pending' => 'Menunggu Approval',
                        'approved' => 'Disetujui',
                        'rejected' => 'Ditolak',
                    ]),
                Tables\Filters\SelectFilter::make('type')
                    ->label('Tipe Dokumen')
                    ->options([
                        'tiket_pesawat' => 'Tiket Pesawat',
                        'tiket_kereta' => 'Tiket Kereta',
                        'tiket_bus' => 'Tiket Bus',
                        'boarding_pass' => 'Boarding Pass',
                        'hotel_invoice' => 'Invoice Hotel',
                        'kwitansi_bbm' => 'Kwitansi BBM',
                        'toll_receipt' => 'Struk Tol',
                        'surat_tugas' => 'Surat Tugas',
                        'lainnya' => 'Lainnya',
                    ]),
                Tables\Filters\TernaryFilter::make('hardcopy_received')
                    ->label('Hardcopy Diterima'),
                Tables\Filters\SelectFilter::make('user_id')
                    ->label('Pengirim')
                    ->relationship('user', 'name')
                    ->searchable()
                    ->preload(),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\Action::make('download')
                        ->label('Download')
                        ->icon('heroicon-o-arrow-down-tray')
                        ->color('info')
                        ->url(fn(Document $record) => Storage::url($record->file_path))
                        ->openUrlInNewTab(),
                    Tables\Actions\Action::make('approve')
                        ->label('Approve')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalHeading('Approve Dokumen')
                        ->modalDescription('Apakah Anda yakin ingin menyetujui dokumen ini?')
                        ->visible(fn(Document $record): bool => $record->status === 'pending' && auth()->user()->hasPermissionTo('approve_documents'))
                        ->action(function (Document $record) {
                            $record->update([
                                'status' => 'approved',
                                'approved_by' => auth()->id(),
                                'approved_at' => now(),
                            ]);
                            Notification::make()
                                ->success()
                                ->title('Dokumen disetujui')
                                ->send();
                        }),
                    Tables\Actions\Action::make('reject')
                        ->label('Reject')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->form([
                            Forms\Components\Textarea::make('rejection_reason')
                                ->label('Alasan Penolakan')
                                ->required(),
                        ])
                        ->visible(fn(Document $record): bool => $record->status === 'pending' && auth()->user()->hasPermissionTo('approve_documents'))
                        ->action(function (Document $record, array $data) {
                            $record->update([
                                'status' => 'rejected',
                                'rejection_reason' => $data['rejection_reason'],
                                'approved_by' => auth()->id(),
                                'approved_at' => now(),
                            ]);
                            Notification::make()
                                ->success()
                                ->title('Dokumen ditolak')
                                ->send();
                        }),
                    Tables\Actions\Action::make('receiveHardcopy')
                        ->label('Terima Hardcopy')
                        ->icon('heroicon-o-clipboard-document-check')
                        ->color('warning')
                        ->requiresConfirmation()
                        ->modalHeading('Konfirmasi Penerimaan Hardcopy')
                        ->modalDescription('Apakah Anda sudah menerima hardcopy dokumen ini?')
                        ->visible(fn(Document $record): bool => $record->status === 'approved' && !$record->hardcopy_received && auth()->user()->hasPermissionTo('receive_hardcopy'))
                        ->action(function (Document $record) {
                            $record->update([
                                'hardcopy_received' => true,
                                'hardcopy_received_by' => auth()->id(),
                                'hardcopy_received_at' => now(),
                            ]);
                            Notification::make()
                                ->success()
                                ->title('Hardcopy telah diterima')
                                ->send();
                        }),
                    Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\BulkAction::make('approveSelected')
                        ->label('Approve Terpilih')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->visible(fn() => auth()->user()->hasPermissionTo('approve_documents'))
                        ->action(function ($records) {
                            $records->each(function ($record) {
                                if ($record->status === 'pending') {
                                    $record->update([
                                        'status' => 'approved',
                                        'approved_by' => auth()->id(),
                                        'approved_at' => now(),
                                    ]);
                                }
                            });
                            Notification::make()
                                ->success()
                                ->title('Dokumen terpilih disetujui')
                                ->send();
                        }),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

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

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

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('status', 'pending')->count() ?: null;
    }

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

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

        // Hide super_admin documents (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->whereHas('user', function ($q) use ($user) {
                $q->where('company_id', $user->company_id);
            });
        }

        return $query;
    }
}
