<?php

namespace App\Filament\Resources\Publication\Announcements;

use App\Enums\AnnouncementType;
use App\Enums\RoleEnum;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use App\Filament\Resources\Publication\Announcements\Pages\ManageAnnouncements;
use App\Models\Announcement;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use UnitEnum;

class AnnouncementResource extends Resource
{
    protected static ?string $model = Announcement::class;

    protected static string|UnitEnum|null $navigationGroup = 'Publikasi';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::Megaphone;

    protected static ?string $navigationLabel = 'Pengumuman';

    protected static ?int $navigationSort = 2;

    protected static ?string $recordTitleAttribute = 'title';

    protected static ?string $slug = 'publication/announcements';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('title')
                    ->label('Judul')
                    ->placeholder('Pencairan Dana Kerja Sama Media')
                    ->autocomplete(false)
                    ->autofocus()
                    ->required()
                    ->maxLength(200)
                    ->columnSpanFull(),

                RichEditor::make('content')
                    ->label('Konten')
                    ->placeholder('...')
                    ->required()
                    ->columnSpanFull(),

                Radio::make('type')
                    ->label('Tipe')
                    ->options(AnnouncementType::class)
                    ->required()
                    ->default(AnnouncementType::PUBLIC->value)
                    ->live()
                    ->inline(),

                CheckboxList::make('partnerMedia')
                    ->label('Kirim Kepada')
                    ->relationship('partnerMedia', 'name', fn (Builder $query): Builder => $query->verified())
                    ->visible(fn (Get $get): bool => in_array($get('type'), [AnnouncementType::COMPANY, AnnouncementType::COMPANY->value]))
                    ->required(fn (Get $get): bool => in_array($get('type'), [AnnouncementType::COMPANY, AnnouncementType::COMPANY->value]))
                    ->searchable()
                    ->noSearchResultsMessage('Tidak ada media yang ditemukan.')
                    ->helperText('Pilih media yang akan menerima pengumuman ini')
                    ->columnSpanFull()
                    ->bulkToggleable()
                    ->selectAllAction(
                        fn (Action $action): Action => $action->label('Pilih Semua Media'),
                    )
                    ->dehydrated(),

            ])
            ->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('title')
                    ->label('Judul')
                    ->searchable()
                    ->sortable()
                    ->wrap(),

                TextColumn::make('content')
                    ->label('Konten')
                    ->searchable()
                    ->sortable()
                    ->wrap()
                    ->limit(100)
                    ->html()
                    ->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('type')
                    ->label('Tipe')
                    ->badge()
                    ->sortable(),

                TextColumn::make('partnerMedia')
                    ->label('Penerima')
                    ->getStateUsing(
                        fn ($record) => $record->partnerMedia->pluck('name')->toArray()
                    )
                    ->listWithLineBreaks()
                    ->limitList(3)
                    ->expandableLimitedList()
                    ->badge()
                    ->placeholder(
                        fn (Announcement $record) => $record->type === AnnouncementType::PUBLIC ? 'Publik' : 'Tidak ada penerima'
                    ),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false)
                    ->visible(fn () => auth()->user()?->hasRole(RoleEnum::DEVELOPER->value)),
            ])
            ->recordActions([
                EditAction::make()
                    ->modalWidth(Width::FiveExtraLarge)
                    ->visible(fn (Announcement $record): bool => $record->type === AnnouncementType::PUBLIC),

                DeleteAction::make(),

                ForceDeleteAction::make(),

                RestoreAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Pengumuman'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::Megaphone)
            ->emptyStateDescription('Setelah Anda membuat data pertama, maka akan muncul disini.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false);
    }

    public static function getPages(): array
    {
        return [
            'index' => ManageAnnouncements::route('/'),
        ];
    }

    public static function getRecordRouteBindingEloquentQuery(): Builder
    {
        return parent::getRecordRouteBindingEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
