<?php

namespace App\Filament\Resources\DisputeResource\RelationManagers;

use Filament\Forms;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Storage;

class EventsRelationManager extends RelationManager
{
    protected static string $relationship = 'events';

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('action'),
                Tables\Columns\TextColumn::make('notes')->limit(50),
                Tables\Columns\TextColumn::make('user.name')->label('Actor'),
                Tables\Columns\TextColumn::make('created_at')->since(),
                Tables\Columns\TextColumn::make('evidence_paths')
                    ->label('Evidence')
                    ->formatStateUsing(function ($state) {
                        if (empty($state)) {
                            return '-';
                        }

                        return collect($state)->map(function ($path) {
                            $name = basename($path);
                            return "<a class=\"text-emerald-600 underline\" href=\"".e(Storage::url($path))."\" target=\"_blank\" rel=\"noreferrer\">{$name}</a>";
                        })->join('<br>');
                    })
                    ->html(),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->form([
                        Forms\Components\TextInput::make('action')->required(),
                        Forms\Components\Textarea::make('notes'),
                        Forms\Components\FileUpload::make('evidence_paths')
                            ->multiple()
                            ->directory('disputes')
                            ->preserveFilenames()
                            ->maxSize(10240),
                    ])
                    ->mutateFormDataUsing(function (array $data): array {
                        $data['user_id'] = auth()->id();
                        return $data;
                    }),
            ]);
    }
}
