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

        $this->label('Buat Penugasan')
            ->icon(Heroicon::Plus)
            ->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 Laporan')
                        ->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' => 'Tugas Baru Telah Menanti! 📝✨',
                            'body' => "Halo! Admin sudah menetapkan tugas untuk kerja sama \"{$record->title}\". Yuk, cek detail tugasnya dan mulai buat laporannya! Semangat! 💪😊",
                            'action' => [
                                Action::make('view')
                                    ->label('Lihat')
                                    ->url(CooperationResource::getUrl('view', ['record' => $record->id, 'relation' => 2])),
                            ],
                        ]));
                    }
                }

                CheerfulNotification::success(
                    'Penugasan Berhasil Dibuat! 🚀✨',
                    'Mantap! Penugasan telah dibuat dan semua media terkait sudah diberi tahu. Mari kita pantau progresnya! 💪'
                )->send();
            })
            ->modalHeading('Buat Penugasan')
            ->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);
    }
}
