<?php

namespace App\Filament\Resources\Manage\Journalists\Actions;

use App\Filament\Actions\Cheerful\CreateAction;
use App\Filament\Resources\Manage\DataChanges\DataChangesResource;
use App\Filament\Support\CheerfulNotification;
use App\Models\DataChangeRequest;
use App\Models\Journalist;
use App\Models\User;
use App\Notifications\BroadcastNotification;
use Filament\Actions\Action;
use Filament\Support\Enums\Width;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class CreateJournalistAction extends CreateAction
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Tambah')
            ->modalHeading('Tambah Jurnalis')
            ->modalSubmitActionLabel('Simpan')
            ->modalCancelActionLabel('Batal')
            ->successNotification(null)
            ->extraModalFooterActions(fn (CreateAction $action): array => [
                $action->makeModalSubmitAction('createAnother', arguments: ['another' => true])
                    ->label('Simpan dan Tambah Lagi'),
            ])
            ->modalWidth(Width::Large)
            ->using(function (array $data, string $model): Model {
                $user = auth()->user();

                $data['partner_media_id'] = $user->company?->partnerMedia?->id;

                $journalist = $model::create($data);

                $documents = [
                    'press_card_docs',
                    'ukw_certificate_docs',
                ];

                foreach ($documents as $field) {
                    if (empty($data[$field])) {
                        continue;
                    }

                    foreach ((array) $data[$field] as $filePath) {
                        $fullPath = Storage::disk(config('filesystems.default'))->path($filePath);

                        if (! file_exists($fullPath)) {
                            continue;
                        }

                        $journalist
                            ->addMediaFromDisk($filePath, config('filesystems.default'))
                            ->preservingOriginal()
                            ->withCustomProperties([
                                'feature' => 'journalists',
                                'date' => now()->toDateString(),
                                'doc_type' => str($field)
                                    ->replace('_docs', '')
                                    ->slug('-'),
                            ])
                            ->toMediaCollection('journalists');
                    }
                }

                // If company is already approved, addition of new journalist needs permohonan/review
                if ($user->company?->verificationRequest !== null) {
                    $fieldLabels = Journalist::dataChangeEntryLabels();
                    $newFields = [];

                    foreach (['name', 'email', 'phone_number', 'press_card', 'ukw_certificate'] as $f) {
                        $label = $fieldLabels[$f] ?? $f;
                        $newFields[$label] = $data[$f] ?? '-';
                    }

                    foreach (['press_card_docs', 'ukw_certificate_docs'] as $df) {
                        $label = $fieldLabels[$df] ?? $df;
                        $newFields[$label] = $data[$df] ?? [];
                    }

                    $dataChangeRequest = DataChangeRequest::create([
                        'user_id' => auth()->id(),
                        'entity_type' => Journalist::class,
                        'entity_id' => $journalist->id,
                        'old_data' => [],
                        'new_data' => $newFields,
                        'change_reason' => 'Penambahan jurnalis baru',
                    ]);

                    CheerfulNotification::success(
                        'Permohonan Berhasil 🎉',
                        'Data jurnalis baru telah dikirim dan sedang menunggu verifikasi admin ⏳'
                    )->send();

                    User::superAdmin()
                        ->get()
                        ->each(function ($admin) use ($dataChangeRequest, $user): void {
                            $admin->notify(new BroadcastNotification([
                                'title' => 'Ada Penambahan Jurnalis Baru ✨',
                                'body' => 'Halooo Admin! 👋 '.$user->name.' baru saja menambahkan jurnalis baru. Yuk, cek detailnya! 🚀',
                                'action' => [
                                    Action::make('view')
                                        ->label('Lihat')
                                        ->url(DataChangesResource::getUrl('view', ['record' => $dataChangeRequest->id])),
                                ],
                            ]));
                        });
                } else {
                    CheerfulNotification::create()->send();
                }

                return $journalist;
            });
    }
}
