<?php

namespace App\Filament\Resources\Manage\Cooperations\Actions\Report;

use App\Enums\ApprovalStatus;
use App\Enums\CooperationStatus;
use App\Enums\RoleEnum;
use App\Filament\Resources\Manage\Cooperations\CooperationResource;
use App\Models\Report;
use App\Notifications\BroadcastNotification;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
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('reason')
                    ->label('Alasan Penolakan')
                    ->placeholder('Jelaskan alasan pengajuan ditolak...')
                    ->required(),
            ])
            ->action(function (Report $record, array $data): void {
                $record->update([
                    'status' => ApprovalStatus::REJECTED,
                ]);

                $record->rejectionReasons()->create(['reason' => $data['reason']]);

                Notification::make()
                    ->title('Berhasil Diproses! ✨')
                    ->body("Laporan '{$record->title}' telah ditolak. Media terkait akan segera mendapatkan notifikasi perbaikan. 🙏")
                    ->warning()
                    ->send();

                $partnerUser = $record->mediaTaskAssignment?->partnerMedia?->company?->user;
                if ($partnerUser) {
                    $partnerUser->notify(new BroadcastNotification([
                        'title' => 'Yah, Laporan Ditolak 🙁',
                        'body' => "Halo! Laporan \"{$record->title}\" pada kerja sama \"{$record->mediaTaskAssignment->taskAssignment->cooperation->title}\" ditolak oleh Admin. 💪\n\nCatatan Admin: {$data['reason']}",
                        'action' => [
                            Action::make('view')
                                ->label('Lihat')
                                ->url(CooperationResource::getUrl('view', ['record' => $record->mediaTaskAssignment->taskAssignment->cooperation_id])),
                        ],
                    ]));
                }
            })
            ->visible(
                fn (Report $record): bool => $record->mediaTaskAssignment?->taskAssignment?->cooperation?->status === CooperationStatus::VERIFICATION &&
                    ! auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value) &&
                    $record->status === ApprovalStatus::PENDING
            )
            ->modalWidth(Width::Large);
    }
}
