<?php

namespace App\Filament\Resources\Manage\Contacts\Actions;

use App\Filament\Support\CheerfulNotification;
use App\Mail\ContactReplyMail;
use App\Models\Contact;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Mail;

class ReplyAction extends Action
{
    public static function getDefaultName(): ?string
    {
        return 'reply';
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Balas')
            ->icon(Heroicon::OutlinedChatBubbleLeftRight)
            ->color('success')
            ->modalHeading(fn () => CheerfulNotification::getByKey('contact.reply_title'))
            ->modalDescription(fn () => CheerfulNotification::getByKey('contact.reply_desc'))
            ->schema([
                Textarea::make('reply_message')
                    ->label('Pesan Balasan')
                    ->placeholder(fn (Contact $record): string => "Halo {$record->name}, ...")
                    ->required()
                    ->rows(5)
                    ->autocomplete(false)
                    ->autofocus(),
            ])
            ->action(function (Contact $record, array $data): void {
                Mail::to($record->email)->send(new ContactReplyMail($record, $data['reply_message']));

                $record->update([
                    'reply_message' => $data['reply_message'],
                    'replied_at' => now(),
                    'replied_by' => auth()->id(),
                ]);

                CheerfulNotification::success(
                    CheerfulNotification::getByKey('contact.reply_success'),
                    CheerfulNotification::getByKey('contact.reply_success_desc')
                )->send();
            })
            ->visible(fn (Contact $record): bool => $record->replied_at === null);
    }
}
