<?php

namespace App\Filament\Resources\Manage\DataChanges\Actions\DataChangeRequest;

use App\Enums\DataChangeDecision;
use App\Enums\DataChangeStatus;
use App\Enums\RoleEnum;
use App\Filament\Support\CheerfulNotification;
use App\Models\DataChangeRequest;
use App\Models\DataChangeReview;
use App\Notifications\BroadcastNotification;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;

class RejectAction extends Action
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Tolak')
            ->icon(Heroicon::XMark)
            ->color('danger')
            ->schema([
                Textarea::make('rejection_reason')
                    ->label('Alasan Penolakan')
                    ->placeholder('Berikan alasan mengapa permohonan ini ditolak...')
                    ->required(),
            ])
            ->modalHeading('Tolak Perubahan Data')
            ->action(function (DataChangeRequest $record, array $data): void {
                $record->update([
                    'status' => DataChangeStatus::REJECTED,
                ]);

                DataChangeReview::create([
                    'data_change_request_id' => $record->id,
                    'reviewer_id' => auth()->id(),
                    'decision' => DataChangeDecision::REJECTED,
                    'note' => $data['rejection_reason'],
                ]);

                // If it was a new addition (empty old_data), delete the entity
                $entity = $record->entity;
                if (empty($record->old_data) && $entity) {
                    $entity->forceDelete();
                }

                CheerfulNotification::info(
                    'Permohonan Ditolak 🛑',
                    'Permohonan perubahan data telah ditolak. 😔'
                )->send();

                // Notify User
                $record->user?->notify(new BroadcastNotification([
                    'title' => 'Permohonan Perubahan Ditolak 🛑',
                    'body' => "Halo! Mohon maaf, permohonan perubahan data Anda untuk {$record->change_reason} ditolak oleh admin. Alasan: {$data['rejection_reason']} 😔",
                ]));
            })
            ->visible(fn (DataChangeRequest $record): bool => $record->status === DataChangeStatus::PENDING && ! auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value))
            ->modalWidth(Width::Large);
    }
}
