<?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
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Balas')
            ->icon(Heroicon::ChatBubbleLeftRight)
            ->color('success')
            ->modalHeading('Balas Pesan Kontak')
            ->modalDescription('Pesan balasan tidak bisa diubah setelah dikirim.')
            ->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(
                    'Balasan Terkirim! 🚀✉️',
                    'Pesan balasan Anda sudah meluncur ke email pengirim. Semoga membantu mereka ya! 😊'
                )->send();
            })
            ->visible(fn (Contact $record): bool => $record->replied_at === null);
    }
}
