<?php

namespace App\Filament\Association\Resources;

use App\Filament\Association\Resources\InvitationResource\Pages;
use App\Filament\Association\Resources\InvitationResource\RelationManagers;
use App\Models\Invitation;
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\Js;

class InvitationResource extends Resource
{
    protected static ?string $model = Invitation::class;

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

    protected static ?string $navigationGroup = 'Member Management';

    protected static ?string $tenantOwnershipRelationshipName = 'association';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('email')
                    ->email()
                    ->required()
                    ->maxLength(255),
                Forms\Components\Select::make('role')
                    ->options([
                        'Member' => 'Member',
                        'Executive' => 'Executive',
                    ])
                    ->required()
                    ->default('Member'),
                Forms\Components\Hidden::make('token')
                    ->default(fn () => \Illuminate\Support\Str::random(64)),
                Forms\Components\Hidden::make('invited_by')
                    ->default(fn () => auth()->id()),
                Forms\Components\Hidden::make('expires_at')
                    ->default(fn () => now()->addDays(7)),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('email')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('role')
                    ->badge(),
                Tables\Columns\TextColumn::make('inviter.firstname')
                    ->label('Invited By'),
                Tables\Columns\TextColumn::make('expires_at')
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->getStateUsing(fn ($record): string => match (true) {
                        $record->isAccepted() => 'Accepted',
                        $record->isExpired() => 'Expired',
                        default => 'Pending',
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'Accepted' => 'success',
                        'Pending' => 'warning',
                        'Expired' => 'danger',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('accepted')
                    ->placeholder('All invitations')
                    ->trueLabel('Accepted')
                    ->falseLabel('Pending/Expired')
                    ->queries(
                        true: fn (Builder $query) => $query->whereNotNull('accepted_at'),
                        false: fn (Builder $query) => $query->whereNull('accepted_at'),
                    ),
            ])
            ->actions([
                Tables\Actions\Action::make('viewLink')
                    ->label('View Link')
                    ->icon('heroicon-o-eye')
                    ->color('info')
                    ->modalWidth('md')
                    ->form([
                        Forms\Components\TextInput::make('registration_link')
                            ->label('Registration Link')
                            ->default(fn ($record) => route('filament.association.auth.register', [
                                'tenant' => filament()->getTenant(),
                                'token' => $record->token,
                            ]))
                            ->readOnly()
                            ->columnSpanFull()
                            ->suffixAction(
                                Forms\Components\Actions\Action::make('copy')
                                    ->icon('heroicon-o-clipboard-document')
                                    ->action(fn () => null)
                                    ->extraAttributes(fn ($state) => [
                                        'x-data' => '{ url: ' . Js::from($state) . ' }',
                                        'x-on:click' => "
                                            window.navigator.clipboard.writeText(url);
                                            \$tooltip('Copied!', { timeout: 1500 });
                                        ",
                                    ])
                            ),
                    ])
                    ->modalSubmitAction(false)
                    ->modalCancelAction(false),
                Tables\Actions\Action::make('resend')
                    ->label('Resend')
                    ->icon('heroicon-o-arrow-path')
                    ->color('info')
                    ->requiresConfirmation()
                    ->hidden(fn ($record) => $record->isAccepted())
                    ->action(function ($record) {
                        $record->update([
                            'token' => \Illuminate\Support\Str::random(64),
                            'expires_at' => now()->addDays(7),
                        ]);

                        app(\App\Services\NotificationService::class)->sendInvitation($record);

                        \Filament\Notifications\Notification::make()
                            ->title('Invitation Resent')
                            ->success()
                            ->send();
                    }),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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