<?php

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

use App\Enums\ApprovalStatus;
use App\Enums\RoleEnum;
use App\Filament\Resources\Manage\Cooperations\CooperationResource;
use App\Filament\Support\CheerfulNotification;
use App\Models\CooperationProposal;
use App\Models\User;
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
{
    public static function getDefaultName(): ?string
    {
        return 'reject';
    }

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

        $this->label('Tolak')
            ->icon(Heroicon::OutlinedXMark)
            ->color('danger')
            ->modalHeading(fn () => CheerfulNotification::getByKey('cooperation.reject_proposal_title'))
            ->modalDescription(fn () => CheerfulNotification::getByKey('cooperation.reject_proposal_desc'))
            ->schema([
                Textarea::make('reason')
                    ->label('Alasan Penolakan')
                    ->placeholder('Jelaskan alasan pengajuan ditolak...')
                    ->required(),
            ])
            ->action(function (CooperationProposal $record, array $data): void {
                $record->update([
                    'status' => ApprovalStatus::REJECTED,
                    'responded_at' => now(),
                ]);

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

                CheerfulNotification::warning(
                    CheerfulNotification::getByKey('cooperation.proposal_rejected'),
                    CheerfulNotification::getByKey('notification.proposal_from_rejected', ['record__partnerMedia__name' => $record->partnerMedia->name])
                )->send();

                // Notify User (Partner)
                $partnerUser = $record->partnerMedia?->company?->user;
                if ($partnerUser) {
                    $partnerUser->notify(new BroadcastNotification([
                        'title' => CheerfulNotification::getByKey('cooperation.proposal_rejection_notice'),
                        'body' => CheerfulNotification::getByKey('notification.proposal_rejected_reason', ['data__reason' => $data['reason']]),
                        'action' => [
                            Action::make('view')
                                ->label('Lihat')
                                ->url(CooperationResource::getUrl('view', ['record' => $record->cooperation_id])),
                        ],
                    ]));
                }
            })
            ->visible(fn (CooperationProposal $record): bool => ! auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value) && $record->status === ApprovalStatus::PENDING)
            ->modalWidth(Width::Large);
    }
}
