<?php

namespace App\Filament\App\Resources;

use App\Filament\App\Resources\PesanResource\Pages;
use App\Filament\App\Resources\PesanResource\RelationManagers;
use App\Models\AgendaRapat;
use App\Models\Pesan;
use App\Models\User;
use Filament\Actions\StaticAction;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Auth;
use Filament\Infolists;
use Filament\Infolists\Components\TextEntry\TextEntrySize;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Illuminate\Support\HtmlString;

class PesanResource extends Resource
{
    protected static ?string $model = Pesan::class;
    protected static ?int $navigationSort = -1;
    protected static ?string $navigationGroup = 'hidden-nav';

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('user_id')
                    ->label('Penerima')
                    ->options(User::all()->pluck('name', 'id'))
                    ->searchable()
                    ->preload()
                    ->optionsLimit(10)
                    ->required(),
                Forms\Components\TextInput::make('type')
                    ->label('Teks Url')
                    ->maxLength(255),
                Forms\Components\TextInput::make('title')
                    ->maxLength(255),
                Forms\Components\TextInput::make('action')
                    ->label('Link Url')
                    ->maxLength(255),
                Forms\Components\RichEditor::make('body')
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(function (Builder $query) {
                $query->where('user_id', Auth::id());
            })
            ->columns([
                Tables\Columns\Layout\Stack::make([
                    Tables\Columns\TextColumn::make('title')
                        ->size('lg')
                        ->weight('bold')
                        ->limit(30)
                        ->tooltip(function (TextColumn $column): ?string {
                            $state = $column->getState();

                            if (strlen($state) <= $column->getCharacterLimit()) {
                                return null;
                            }
                            // Only render the tooltip if the column content exceeds the length limit.
                            return $state;
                        })
                        ->searchable(),
                    Tables\Columns\Layout\Split::make([
                        Tables\Columns\TextColumn::make('created_at')
                            ->label('Diterima')
                            ->size('sm')
                            ->color('gray')
                            ->dateTime()
                            ->sortable()
                            ->since(),
                        Tables\Columns\TextColumn::make('status')
                            ->badge()
                            ->grow(false)
                            ->sortable()
                            ->color(fn(string $state): string => match ($state) {
                                'unread' => 'warning',
                                'read' => 'gray',
                            }),
                    ]),
                    Tables\Columns\TextColumn::make('body')
                        ->limit(100)
                        ->html(),

                ])
                    ->space(2),
            ])
            ->filters([
                //
            ])
            ->contentGrid([
                'md' => 2,
                'xl' => 2,
                '2xl' => 3
            ])
            //->recordAction(Tables\Actions\ViewAction::class)
            ->recordUrl(null)
            ->actions([
                Tables\Actions\Action::make("Aksi")
                    ->button()
                    ->label(function ($record) {
                        return $record->type;
                    })
                    ->icon('heroicon-c-eye')
                    ->visible(function ($record) {
                        if ($record->action == null) {
                            return false;
                        }
                        return true;
                    })
                    ->action(function ($record) {
                        $record->update([
                            "status" => "read"
                        ]);
                        return redirect($record->action);
                    }),
                Tables\Actions\Action::make("Lihat")
                    ->button()
                    ->label('Lihat')
                    ->icon('heroicon-c-eye')
                    ->modalHeading(function ($record) {
                        return $record->title;
                    })
                    ->closeModalByClickingAway(false)
                    ->closeModalByEscaping(false)
                    ->modalCloseButton(false)
                    ->modalCancelAction(false)
                    ->stickyModalHeader()
                    ->stickyModalFooter()
                    ->modalSubmitActionLabel('Tutup')
                    ->action(function ($record) {
                        $record->update([
                            "status" => "read"
                        ]);
                    })
                    ->visible(function ($record) {
                        if ($record->action != null) {
                            return false;
                        }
                        return true;
                    })
                    ->infolist([
                        Infolists\Components\TextEntry::make('body')
                            ->label('')
                            ->columnSpanFull()
                            ->html(),

                    ])
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function infolist(Infolists\Infolist $infolist): Infolists\Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\TextEntry::make('title')
                    ->size('lg')
                    ->label('')
                    ->columnSpanFull(),
                Infolists\Components\TextEntry::make('status')
                    ->size('lg')
                    ->label('')
                    ->columnSpanFull(),
                Infolists\Components\TextEntry::make('body')
                    ->label('')
                    ->columnSpanFull()
                    ->html(),
            ]);
    }
    protected static ?string $navigationBadgeTooltip = 'Pesan yang belum dibaca';

    public static function getNavigationBadge(): ?string
    {
        return static::$model::where('user_id', Auth::id())
            ->where('status', 'unread')
            ->count();
    }

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

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