<?php

namespace App\Filament\Resources\Workspaces\RelationManagers;

use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Services\Auth\WorkspaceMembershipManager;
use App\Support\Auth\Capabilities;
use App\Support\Auth\WorkspaceRole;
use App\Support\Rbac\WorkspaceUiEnforcement;
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class WorkspaceMembershipsRelationManager extends RelationManager
{
    protected static string $relationship = 'memberships';

    public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
    {
        return ActionSurfaceDeclaration::forRelationManager(ActionSurfaceProfile::RelationManager)
            ->satisfy(ActionSurfaceSlot::ListHeader, 'Add member action is available in the relation header.')
            ->exempt(ActionSurfaceSlot::InspectAffordance, 'Workspace membership rows are managed inline and have no separate inspect destination.')
            ->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Change role stays inline while destructive removal is grouped under More.')
            ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk membership mutations are intentionally omitted.')
            ->exempt(ActionSurfaceSlot::ListEmptyState, 'No empty-state actions are exposed; add member remains available in the header.');
    }

    public function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn (Builder $query) => $query->with('user'))
            ->defaultSort('created_at', 'desc')
            ->paginated(\App\Support\Filament\TablePaginationProfiles::relationManager())
            ->columns([
                Tables\Columns\TextColumn::make('user.email')
                    ->label(__('User'))
                    ->searchable(),
                Tables\Columns\TextColumn::make('user_domain')
                    ->label(__('Domain'))
                    ->getStateUsing(function (WorkspaceMembership $record): ?string {
                        $email = $record->user?->email;

                        if (! is_string($email) || $email === '' || ! str_contains($email, '@')) {
                            return null;
                        }

                        return (string) str($email)->after('@')->lower();
                    }),
                Tables\Columns\TextColumn::make('user.name')
                    ->label(__('Name'))
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('role')
                    ->badge()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')->since()->sortable(),
            ])
            ->headerActions([
                WorkspaceUiEnforcement::forTableAction(
                    Action::make('add_member')
                        ->label(__('Add member'))
                        ->icon('heroicon-o-plus')
                        ->form([
                            Forms\Components\Select::make('user_id')
                                ->label(__('User'))
                                ->required()
                                ->searchable()
                                ->options(fn () => User::query()
                                    ->orderBy('email')
                                    ->get(['id', 'name', 'email'])
                                    ->mapWithKeys(fn (User $user): array => [
                                        (string) $user->id => trim((string) ($user->name ? "{$user->name} ({$user->email})" : $user->email)),
                                    ])
                                    ->all()),
                            Forms\Components\Select::make('role')
                                ->label(__('Role'))
                                ->required()
                                ->options([
                                    WorkspaceRole::Owner->value => __('Owner'),
                                    WorkspaceRole::Manager->value => __('Manager'),
                                    WorkspaceRole::Operator->value => __('Operator'),
                                    WorkspaceRole::Readonly->value => __('Readonly'),
                                ]),
                        ])
                        ->action(function (array $data, WorkspaceMembershipManager $manager): void {
                            $workspace = $this->getOwnerRecord();

                            if (! $workspace instanceof Workspace) {
                                abort(404);
                            }

                            $actor = auth()->user();
                            if (! $actor instanceof User) {
                                abort(403);
                            }

                            $member = User::query()->find((int) $data['user_id']);
                            if (! $member) {
                                Notification::make()->title(__('User not found'))->danger()->send();

                                return;
                            }

                            try {
                                $manager->addMember(
                                    workspace: $workspace,
                                    actor: $actor,
                                    member: $member,
                                    role: (string) $data['role'],
                                    source: 'manual',
                                );
                            } catch (\Throwable $throwable) {
                                Notification::make()
                                    ->title(__('Failed to add member'))
                                    ->body($throwable->getMessage())
                                    ->danger()
                                    ->send();

                                return;
                            }

                            Notification::make()->title(__('Member added'))->success()->send();
                            $this->resetTable();
                        }),
                    fn () => $this->getOwnerRecord(),
                )
                    ->requireCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE)
                    ->tooltip('You do not have permission to manage workspace memberships.')
                    ->apply(),
            ])
            ->actions([
                WorkspaceUiEnforcement::forTableAction(
                    Action::make('change_role')
                        ->label(__('Change role'))
                        ->icon('heroicon-o-pencil')
                        ->requiresConfirmation()
                        ->form([
                            Forms\Components\Select::make('role')
                                ->label(__('Role'))
                                ->required()
                                ->options([
                                    WorkspaceRole::Owner->value => __('Owner'),
                                    WorkspaceRole::Manager->value => __('Manager'),
                                    WorkspaceRole::Operator->value => __('Operator'),
                                    WorkspaceRole::Readonly->value => __('Readonly'),
                                ]),
                        ])
                        ->action(function (WorkspaceMembership $record, array $data, WorkspaceMembershipManager $manager): void {
                            $workspace = $this->getOwnerRecord();

                            if (! $workspace instanceof Workspace) {
                                abort(404);
                            }

                            $actor = auth()->user();
                            if (! $actor instanceof User) {
                                abort(403);
                            }

                            try {
                                $manager->changeRole(
                                    workspace: $workspace,
                                    actor: $actor,
                                    membership: $record,
                                    newRole: (string) $data['role'],
                                );
                            } catch (\Throwable $throwable) {
                                Notification::make()
                                    ->title(__('Failed to change role'))
                                    ->body($throwable->getMessage())
                                    ->danger()
                                    ->send();

                                return;
                            }

                            Notification::make()->title(__('Role updated'))->success()->send();
                            $this->resetTable();
                        }),
                    fn () => $this->getOwnerRecord(),
                )
                    ->requireCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE)
                    ->tooltip('You do not have permission to manage workspace memberships.')
                    ->apply(),
                ActionGroup::make([
                    WorkspaceUiEnforcement::forTableAction(
                        Action::make('remove')
                            ->label(__('Remove'))
                            ->color('danger')
                            ->icon('heroicon-o-x-mark')
                            ->requiresConfirmation()
                            ->action(function (WorkspaceMembership $record, WorkspaceMembershipManager $manager): void {
                                $workspace = $this->getOwnerRecord();

                                if (! $workspace instanceof Workspace) {
                                    abort(404);
                                }

                                $actor = auth()->user();
                                if (! $actor instanceof User) {
                                    abort(403);
                                }

                                try {
                                    $manager->removeMember(workspace: $workspace, actor: $actor, membership: $record);
                                } catch (\Throwable $throwable) {
                                    Notification::make()
                                        ->title(__('Failed to remove member'))
                                        ->body($throwable->getMessage())
                                        ->danger()
                                        ->send();

                                    return;
                                }

                                Notification::make()->title(__('Member removed'))->success()->send();
                                $this->resetTable();
                            }),
                        fn () => $this->getOwnerRecord(),
                    )
                        ->requireCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE)
                        ->tooltip('You do not have permission to manage workspace memberships.')
                        ->destructive()
                        ->apply(),
                ])->label('More'),
            ])
            ->bulkActions([])
            ->emptyStateHeading(__('No workspace members'))
            ->emptyStateDescription(__('Add a member to grant workspace access.'));
    }
}
