<?php

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

use App\Enums\CooperationStatus;
use App\Enums\RoleEnum;
use App\Filament\Support\CheerfulNotification;
use App\Models\Cooperation;
use Filament\Actions\Action;
use Filament\Support\Icons\Heroicon;

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

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

        $this->label('Selesaikan Kerjasama')
            ->icon(Heroicon::OutlinedCheckBadge)
            ->color('success')
            ->requiresConfirmation()
            ->modalHeading(fn () => CheerfulNotification::getByKey('cooperation.complete_title'))
            ->modalDescription(fn () => CheerfulNotification::getByKey('cooperation.complete_desc'))
            ->action(function (Cooperation $record): void {
                // Verify all accepted media are paid
                $acceptedMedia = $record->cooperationMedia()->accepted()->get();

                if ($acceptedMedia->isEmpty()) {
                    CheerfulNotification::danger(
                        CheerfulNotification::getByKey('cooperation.media_empty'),
                        CheerfulNotification::getByKey('cooperation.media_empty_desc')
                    )->send();

                    return;
                }

                $unpaidMedia = $acceptedMedia->filter(function ($media) {
                    return ! $media->payment()->exists();
                });

                if ($unpaidMedia->isNotEmpty()) {
                    CheerfulNotification::danger(
                        CheerfulNotification::getByKey('cooperation.payment_unfulfilled'),
                        CheerfulNotification::getByKey('cooperation.payment_unfulfilled_desc')
                    )->send();

                    $this->halt();

                    return;
                }

                // Calculate total payment from media payments
                $totalPayment = $acceptedMedia->sum(fn ($media) => $media->payment->amount);

                $record->update([
                    'payment_amount' => $totalPayment,
                    'completed_at' => now(),
                    'status' => CooperationStatus::COMPLETED,
                ]);

                CheerfulNotification::success(
                    CheerfulNotification::getByKey('cooperation.completed_success'),
                    CheerfulNotification::getByKey('cooperation.completed_desc')
                )->send();
            })
            ->visible(function (Cooperation $record): bool {
                $user = auth()->user();

                return $user && ! $user->hasRole(RoleEnum::PERUSAHAAN->value)
                    && $record->status === CooperationStatus::PAYMENT;
            });
    }
}
