<?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\Models\CooperationProposal;
use App\Models\User;
use App\Notifications\BroadcastNotification;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Support\Icons\Heroicon;

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

        $this->label('Terima')
            ->icon(Heroicon::OutlinedCheck)
            ->color('success')
            ->action(function (CooperationProposal $record): void {
                $record->update([
                    'status' => ApprovalStatus::ACCEPTED,
                    'responded_at' => now(),
                ]);

                Notification::make()
                    ->title('Berhasil Diproses! ✨')
                    ->body("Mantap! Proposal dari {$record->partnerMedia->name} telah diterima. Notifikasi sudah dikirim! 💪")
                    ->success()
                    ->send();

                // Notify User (Partner)
                $partnerUser = $record->partnerMedia?->company?->user;
                if ($partnerUser) {
                    $partnerUser->notify(new BroadcastNotification([
                        'title' => 'Horee! Proposal Disetujui 🎉',
                        'body' => 'Yeay! Proposal kerja sama Anda telah disetujui oleh Admin. Mari kita lanjut ke tahap berikutnya! 🎊',
                        '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);
    }
}
