<?php

namespace App\Filament\Resources;

use App\Filament\Resources\InventarisResource\Pages;
use App\Filament\Resources\InventarisResource\Pages\CreateInventaris;
use App\Filament\Resources\InventarisResource\Pages\EditInventaris;
use App\Filament\Resources\InventarisResource\Pages\ListInventaris;
use App\Models\Inventaris;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
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\DeleteAction;
use Filament\Tables\Actions\DeleteBulkAction;
use Filament\Tables\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Enums\FiltersLayout;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;

class InventarisResource extends Resource
{
    protected static ?string $model = Inventaris::class;

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

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

    protected static ?string $modelLabel = 'Inventaris';
    protected static ?string $navigationLabel  = 'Manajemen Inventaris';
    protected static ?string $pluralModelLabel = 'Daftar Inventaris';
    
    protected static ?string $slug = 'inventaris';

    protected static ?string $navigationBadgeTooltip = 'Inventaris 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([
                TextInput::make('kode_barang')
                    ->label('Kode Barang')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-tag')
                    ->required()
                    ->unique(ignoreRecord: true)
                    ->maxLength(50),
                TextInput::make('nama_barang')
                    ->label('Nama Barang')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-tv')
                    ->required()
                    ->maxLength(100),
                TextInput::make('merk')
                    ->label('Merk')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-building-storefront')
                    ->maxLength(50),
                Select::make('tahun_beli_perolehan')
                    ->label('Tahun Beli/Perolehan')
                    ->options(function () {
                        $years = range(now()->year, 1900);
                        return array_combine($years, $years);
                    })
                    ->prefixIcon('heroicon-o-calendar')
                    ->prefixIconColor('primary')
                    ->required()
                    ->searchable()
                    ->native(false),
                Select::make('asal_usul')
                    ->label('Asal Usul')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-question-mark-circle')
                    ->options([
                        'bpopp' => 'BPOPP',
                        'bos' => 'BOS',
                        'hibah' => 'HIBAH',
                        'beli_sendiri' => 'BELI SENDIRI',
                        'lainnya' => 'LAINNYA',
                    ])
                    ->required()
                    ->live()
                    ->default('bpopp')
                    ->searchable(),
                TextInput::make('jumlah_baik')
                    ->label('Jumlah Baik')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-check-circle')
                    ->required()
                    ->numeric()
                    ->minValue(0),
                TextInput::make('jumlah_rusak')
                    ->label('Jumlah Rusak')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-x-circle')
                    ->required()
                    ->numeric()
                    ->minValue(0),
                TextInput::make('satuan')
                    ->label('Satuan')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-scale')
                    ->required()
                    ->maxLength(20),
                Select::make('kepemilikan')
                    ->label('Kepemilikan')
                    ->prefixIconColor('primary')
                    ->prefixIcon('heroicon-o-shield-check')
                    ->options([
                        'ak' => 'Akuntansi',
                        'mp' => 'Manajemen Perkantoran',
                    ])
                    ->required()
                    ->live()
                    ->default('ak')
                    ->searchable(),
                Textarea::make('keterangan')
                    ->label('Keterangan')
                    ->maxLength(255)
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('kepemilikan')
                    ->label('Kepemilikan')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'ak' => 'Akuntansi',
                        'mp' => 'Manajemen Perkantoran',
                        default => ucfirst(str_replace('_', ' ', $state)),
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'ak' => 'success',
                        'mp' => 'warning',
                        default => 'gray',
                    })
                    ->sortable(),
                TextColumn::make('kode_barang')
                    ->label('Kode Barang')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('nama_barang')
                    ->label('Nama Barang')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('merk')
                    ->label('Merk')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('tahun_beli_perolehan')
                    ->label('Tahun')
                    ->date('Y')
                    ->sortable(),
                TextColumn::make('asal_usul')
                    ->label('Asal Usul')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'bpopp' => 'BPOPP',
                        'bos' => 'BOS',
                        'hibah' => 'HIBAH',
                        'beli_sendiri' => 'BELI SENDIRI',
                        'lainnya' => 'LAINNYA',
                        default => ucfirst(str_replace('_', ' ', $state)),
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'bpopp' => 'success',
                        'bos' => 'danger',
                        'hibah' => 'warning',
                        'beli_sendiri' => 'info',
                        'lainnya' => 'primary',
                        default => 'gray',
                    })
                    ->searchable(),
                TextColumn::make('jumlah_baik')
                    ->label('Baik')
                    ->numeric(),
                TextColumn::make('jumlah_rusak')
                    ->label('Rusak')
                    ->numeric(),
                TextColumn::make('jumlah_total')
                    ->label('Total')
                    ->numeric()
                    ->sortable(),
                TextColumn::make('satuan')
                    ->label('Satuan'),
            ])
            ->filters([
                SelectFilter::make('kondisi')
                    ->label('Kondisi')
                    ->options([
                        'baik' => 'Baik',
                        'rusak' => 'Rusak',
                    ])
                    ->query(function ($query, $data) {
                        if (!empty($data['value'])) {
                            $value = $data['value'];
                            if ($value === 'baik') {
                                return $query->where('jumlah_baik', '>', 0);
                            } elseif ($value === 'rusak') {
                                return $query->where('jumlah_rusak', '>', 0);
                            }
                        }
                        return $query;
                    })
                    ->native(false),
                Filter::make('tahun_beli_perolehan')
                    ->form([
                        TextInput::make('tahun_dari')
                            ->numeric()
                            ->placeholder('Tahun dari'),
                        TextInput::make('tahun_sampai')
                            ->numeric()
                            ->placeholder('Tahun sampai'),
                    ])
                    ->query(function ($query, array $data) {
                        return $query
                            ->when($data['tahun_dari'],
                                fn($query) => $query->where('tahun_beli_perolehan', '>=', $data['tahun_dari']))
                            ->when($data['tahun_sampai'],
                                fn($query) => $query->where('tahun_beli_perolehan', '<=', $data['tahun_sampai']));
                    })
                    ->label('Tahun Perolehan'),
            ])
            ->filtersLayout(FiltersLayout::Modal)
            ->actions([
                EditAction::make(),
                DeleteAction::make()
                    ->successNotification(null)
                    ->after(function ($record) {
                        Notification::make()
                            ->title('Data Inventaris Dihapus')
                            ->success()
                            ->body("Data inventaris {$record->nama_barang} dengan kode barang {$record->kode_barang} berhasil dihapus")
                            ->sendToDatabase(Auth::user());
                    }),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->label('Hapus Data Terpilih')
                        ->successNotification(null)
                        ->after(function ($records) {
                            $count = $records->count();

                            Notification::make()
                                ->title('Data Inventaris Dihapus')
                                ->success()
                                ->body("{$count} inventaris berhasil dihapus")
                                ->sendToDatabase(Auth::user());
                        }),
                ]),
            ])
            ->emptyStateHeading('Belum ada data inventaris')
            ->emptyStateDescription('Klik tombol dibawah untuk membuat inventaris baru')
            ->emptyStateActions([
                CreateAction::make()
                    ->label('Buat Inventaris')
                    ->icon('heroicon-o-plus'),
            ])
            ->deferLoading();
    }

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

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