<?php

declare(strict_types=1);

namespace App\Filament\Resources\SupportTickets\RelationManagers;

use App\Models\SupportTicket;
use App\Models\SupportTicketReply;
use Filament\Actions\CreateAction;
use Filament\Forms\Components\Textarea;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;

class RepliesRelationManager extends RelationManager
{
    protected static string $relationship = 'replies';

    protected static ?string $title = 'مکالمه (پاسخ‌ها)';

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('user.getFilamentName')
                    ->label('فرستنده')
                    ->getStateUsing(fn (SupportTicketReply $reply) => $reply->user?->getFilamentName()),
                TextColumn::make('is_admin')
                    ->label('ادمین')
                    ->badge()
                    ->formatStateUsing(fn ($state) => $state ? 'بله' : 'خیر')
                    ->color(fn ($state) => $state ? 'success' : 'gray'),
                TextColumn::make('body')->label('متن')->limit(80)->wrap(),
                TextColumn::make('edited_at')->label('ویرایش')->jalaliDateTime('Y/m/d H:i')->placeholder('-'),
                TextColumn::make('created_at')->label('تاریخ')->jalaliDateTime('Y/m/d H:i'),
            ])
            ->defaultSort('created_at', 'asc')
            ->headerActions([
                CreateAction::make()
                    ->label('ارسال پاسخ')
                    ->visible(fn (): bool => $this->getOwnerRecord()->status !== SupportTicket::STATUS_CLOSED)
                    ->mutateDataUsing(function (array $data): array {
                        $data['user_id'] = Auth::id();
                        $data['is_admin'] = true;

                        return $data;
                    })
                    ->after(function (): void {
                        /** @var SupportTicket $ticket */
                        $ticket = $this->getOwnerRecord();

                        $ticket->update([
                            'status' => SupportTicket::STATUS_READ,
                            'updated_by' => Auth::id(),
                        ]);
                    })
                    ->schema([
                        Textarea::make('body')->label('متن پاسخ')->required()->rows(4),
                    ]),
            ]);
    }
}
