<?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\Support\Icons\Heroicon;

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

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

        $this->label('Terima')
            ->icon(Heroicon::OutlinedCheck)
            ->color('success')
            ->requiresConfirmation()
            ->modalHeading(fn () => CheerfulNotification::getByKey('cooperation.accept_proposal_title'))
            ->modalDescription(fn () => CheerfulNotification::getByKey('cooperation.accept_proposal_desc'))
            ->action(function (CooperationProposal $record): void {
                $record->update([
                    'status' => ApprovalStatus::ACCEPTED,
                    'responded_at' => now(),
                ]);

                CheerfulNotification::success(
                    CheerfulNotification::getByKey('cooperation.proposal_approved_success'),
                    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_approved'),
                        'body' => CheerfulNotification::getByKey('cooperation.proposal_approved_desc'),
                        '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);
    }
}
