<?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
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Selesaikan Kerjasama')
            ->icon(Heroicon::CheckBadge)
            ->color('success')
            ->requiresConfirmation()
            ->modalHeading('Selesaikan Kerja Sama')
            ->modalDescription('Apakah Anda yakin ingin menyelesaikan kerja sama ini? Pastikan semua pembayaran kepada media yang bekerja sama telah lunas.')
            ->action(function (Cooperation $record): void {
                // Verify all accepted media are paid
                $acceptedMedia = $record->cooperationMedia()->accepted()->get();

                if ($acceptedMedia->isEmpty()) {
                    CheerfulNotification::danger(
                        'Tidak Ada Media! ❌',
                        'Tidak ada media yang menerima kerja sama ini. Tidak dapat diselesaikan.'
                    )->send();

                    return;
                }

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

                if ($unpaidMedia->isNotEmpty()) {
                    CheerfulNotification::danger(
                        'Pembayaran Belum Lunas! ⚠️',
                        'Masih ada media yang belum dibayar. Harap selesaikan pembayaran untuk semua media yang menerima kerja sama.'
                    )->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(
                    'Kerja Sama Selesai! 🎉✨',
                    'Alhamdulillah! Kerja sama ini telah resmi diselesaikan. Terima kasih atas kerja samanya! 🙌😊'
                )->send();
            })
            ->visible(function (Cooperation $record): bool {
                $user = auth()->user();

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