<?php

namespace App\Filament\Resources;

use App\Filament\Resources\JenisPerawatanResource\Pages\CreateJenisPerawatan;
use App\Filament\Resources\JenisPerawatanResource\Pages\EditJenisPerawatan;
use App\Filament\Resources\JenisPerawatanResource\Pages\ListJenisPerawatans;
use App\Models\JenisPerawatan;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables\Actions\BulkActionGroup;
use Filament\Tables\Actions\CreateAction;
use Filament\Tables\Actions\DeleteBulkAction;
use Filament\Tables\Actions\EditAction;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\HtmlString;

class JenisPerawatanResource extends Resource
{
    protected static ?string $model = JenisPerawatan::class;

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

    protected static ?string $navigationGroup = 'Manajemen Perawatan';
    protected static ?int $navigationSort = 1;

    protected static ?string $modelLabel = 'Jenis Perawatan';
    protected static ?string $navigationLabel  = 'Manajemen Jenis Perawatan';
    protected static ?string $pluralModelLabel = 'Daftar Jenis Perawatan';
    
    protected static ?string $slug = 'jenis-perawatan';

    protected static ?string $navigationBadgeTooltip = 'Jenis Perawatan baru hari ini';

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

    public static function getNavigationBadgeColor(): ?string
    {
        return static::getModel()::whereDate('created_at', today())->exists() ? 'success' : null;
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('Informasi Dasar')
                    ->schema([
                        Select::make('kategori')
                            ->label('Kategori')
                            ->options([
                                'hardware' => 'Hardware',
                                'software' => 'Software',
                            ])
                            ->required()
                            ->live()
                            ->native(false)
                            ->afterStateUpdated(fn (Forms\Set $set) => $set('sub_kategori', null)),
                        TextInput::make('nama')
                            ->label('Nama Perawatan')
                            ->required()
                            ->maxLength(255),
                        Select::make('sub_kategori')
                            ->label('Sub Kategori')
                            ->options(function (Forms\Get $get) {
                                $kategori = $get('kategori');
                                
                                if ($kategori === 'hardware') {
                                    return [
                                        'printer' => 'Printer',
                                        'jaringan' => 'Jaringan',
                                        'pc' => 'PC Hardware',
                                        'peripheral' => 'Peripheral',
                                        'laboratorium' => 'Laboratorium',
                                    ];
                                }
                                
                                return [
                                    'os' => 'Sistem Operasi',
                                    'aplikasi' => 'Aplikasi',
                                    'keamanan' => 'Keamanan',
                                    'backup' => 'Backup',
                                    'update' => 'Update',
                                ];
                            })
                            ->searchable()
                            ->preload()
                            ->live()
                            ->native(false),
                    ])
                    ->columns(2),

                    Section::make('Pengaturan')
                    ->schema([
                        TextInput::make('urutan')
                            ->label('Urutan Tampilan')
                            ->numeric()
                            ->required()
                            ->default(fn () => JenisPerawatan::count() + 1)
                            ->minValue(1)
                            ->maxValue(100)
                            ->columnSpan(1),
                        Toggle::make('bersyarat')
                            ->label('Perawatan Bersyarat?')
                            ->helperText('Centang jika perawatan hanya dilakukan ketika diperlukan')
                            ->inline(false)
                            ->columnSpan(1),
                    ])
                    ->columns(2),
                
                Section::make('Detail Perawatan')
                    ->schema([
                        Textarea::make('deskripsi')
                            ->label('Alasan/Panduan')
                            ->helperText('Jelaskan kapan perawatan ini diperlukan dan prosedurnya')
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('kategori')
                    ->label('Kategori')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'hardware' => 'success',
                        'software' => 'info',
                    }),
                TextColumn::make('sub_kategori')
                    ->label('Sub Kategori')
                    ->badge(),
                TextColumn::make('nama')
                    ->label('Nama Perawatan')
                    ->searchable(),
                IconColumn::make('bersyarat')
                    ->label('Bersyarat')
                    ->boolean(),
                TextColumn::make('deskripsi')
                    ->label('Alasan')
                    ->searchable(),
            ])
            ->filters([
                SelectFilter::make('kategori')
                    ->label('Kategori')
                    ->options([
                        'hardware' => 'Hardware',
                        'software' => 'Software',
                    ]),
            ])
            ->actions([
                EditAction::make(),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->label('Hapus Data Terpilih')
                        ->successNotification(null)
                        ->action(function ($records) {
                            $successCount = 0;
                            $failedModels = [];
                            
                            foreach ($records as $record) {
                                try {
                                    $record->delete();
                                    $successCount++;
                                } catch (QueryException $e) {
                                    if ($e->getCode() == 23000) {
                                        $failedModels[] = $record;
                                    } else {
                                        throw $e;
                                    }
                                }
                            }
                            
                            if ($successCount > 0) {
                                Notification::make()
                                    ->title('Data Jenis Perawatan Dihapus')
                                    ->success()
                                    ->body("{$successCount} jenis perawatan berhasil dihapus")
                                    ->sendToDatabase(Auth::user());
                            }
                            
                            if (!empty($failedModels)) {
                                $errorMessages = [];
                                
                                foreach ($failedModels as $model) {
                                    $relations = [];
                                    
                                    if ($model->jadwal()->exists()) {
                                        $relations[] = 'Jadwal Perawatan';
                                    }
                                    if ($model->logPerawatan()->exists()) { 
                                        $relations[] = 'Log Perawatan';
                                    }
                                    
                                    $errorMessages[] = "{$model->nama} (terkait dengan: " . implode(', ', $relations) . ")";
                                }
                                
                                $notificationBody = "Data berikut masih memiliki relasi:<br>" . 
                                    "- " . implode("<br>- ", $errorMessages);

                                Notification::make()
                                    ->title('Data Jenis Perawatan Gagal Dihapus')
                                    ->danger()
                                    ->body(new HtmlString($notificationBody))
                                    ->sendToDatabase(Auth::user());
                            }
                        })
                        ->requiresConfirmation(),
                ]),
            ])
            ->emptyStateHeading('Belum ada data perawatan')
            ->emptyStateDescription('Klik tombol dibawah untuk membuat jenis perawatan baru')
            ->emptyStateActions([
                CreateAction::make()
                    ->label('Buat Jenis Perawatan')
                    ->icon('heroicon-o-plus'),
            ])
            ->deferLoading();
    }

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

    public static function getPages(): array
    {
        return [
            'index' => ListJenisPerawatans::route('/'),
            'create' => CreateJenisPerawatan::route('/create'),
            'edit' => EditJenisPerawatan::route('/{record}/edit'),
        ];
    }
}
