<?php

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

use App\Enums\ApprovalStatus;
use App\Enums\CooperationStatus;
use App\Enums\RoleEnum;
use App\Filament\Resources\Manage\Cooperations\CooperationResource;
use App\Filament\Support\CheerfulNotification;
use App\Models\Cooperation;
use App\Notifications\BroadcastNotification;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;

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

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

        $this->label('Buat Media Order')
            ->icon(Heroicon::OutlinedPlus)
            ->color('primary')
            ->schema(function (Cooperation $record): array {
                return [
                    DatePicker::make('start_date')
                        ->label('Tanggal Mulai')
                        ->placeholder(fn (): string => now()->translatedFormat('l, d F Y'))
                        ->native(false)
                        ->displayFormat('l, d F Y')
                        ->required()
                        ->minDate($record->final_submission_date),

                    DatePicker::make('end_date')
                        ->label('Tanggal Selesai')
                        ->placeholder(fn (): string => now()->addDays(30)->translatedFormat('l, d F Y'))
                        ->native(false)
                        ->displayFormat('l, d F Y')
                        ->required()
                        ->after('start_date')
                        ->minDate($record->final_submission_date),

                    TextInput::make('report_amount')
                        ->label('Jumlah Bukti Tayang')
                        ->placeholder(10)
                        ->numeric()
                        ->minValue(1)
                        ->required()
                        ->autocomplete(false),

                    Textarea::make('task_description')
                        ->label('Deskripsi Tugas')
                        ->required()
                        ->rows(4)
                        ->placeholder('...')
                        ->autocomplete(false),
                ];
            })
            ->action(function (array $data, Cooperation $record): void {
                $taskAssignment = $record->taskAssignment()->create([
                    'start_date' => $data['start_date'],
                    'end_date' => $data['end_date'],
                    'task_description' => $data['task_description'],
                    'report_amount' => $data['report_amount'],
                ]);

                $partnerMedias = $record->partnerMedia()
                    ->wherePivot('status', ApprovalStatus::ACCEPTED)
                    ->get();

                foreach ($partnerMedias as $partnerMedia) {
                    $taskAssignment->mediaTaskAssignments()->create([
                        'partner_media_id' => $partnerMedia->id,
                        'status' => ApprovalStatus::PENDING,
                    ]);

                    // Notify Partner
                    $partnerUser = $partnerMedia->company?->user;
                    if ($partnerUser) {
                        $partnerUser->notify(new BroadcastNotification([
                            'title' => CheerfulNotification::getByKey('cooperation.new_assignment'),
                            'body' => CheerfulNotification::getByKey('notification.admin_assigned_task', ['record__title' => $record->title]),
                            'action' => [
                                Action::make('view')
                                    ->label('Lihat')
                                    ->url(CooperationResource::getUrl('view', ['record' => $record->id, 'relation' => 2])),
                            ],
                        ]));
                    }
                }

                CheerfulNotification::success(
                    CheerfulNotification::getByKey('cooperation.assignment_created_success'),
                    CheerfulNotification::getByKey('cooperation.assignment_created_desc')
                )->send();
            })
            ->modalHeading(fn () => CheerfulNotification::getByKey('cooperation.create_assignment_title'))
            ->modalDescription(fn () => CheerfulNotification::getByKey('cooperation.create_assignment_desc'))
            ->modalSubmitActionLabel('Simpan')
            ->visible(function (Cooperation $record): bool {
                $user = auth()->user();

                return $user && ! $user->hasRole(RoleEnum::PERUSAHAAN->value)
                    && ! $record->taskAssignment()->exists()
                    && $record->status === CooperationStatus::ASSIGNMENT;
            })
            ->modalWidth(Width::Large);
    }
}
