<?php

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

use App\Enums\DataChangeStatus;
use App\Enums\RoleEnum;
use App\Enums\VerificationStatus;
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\Actions\DeleteAction;
use Filament\Forms\Components\Textarea;

class DeleteJournalistAction extends DeleteAction
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->successNotification(null);

        $this->modalHeading(fn () => auth()->user()->company?->verificationRequest?->status === VerificationStatus::APPROVED ? 'Ajukan Penghapusan Jurnalis' : 'Hapus Jurnalis');

        $this->schema(fn () => auth()->user()->company?->verificationRequest?->status === VerificationStatus::APPROVED ? [
            Textarea::make('deletion_reason')
                ->label('Alasan Penghapusan')
                ->placeholder('Jelaskan alasan mengapa jurnalis ini dihapus...')
                ->required(),
        ] : []);

        $this->action(function (Journalist $record, array $data): void {
            $user = auth()->user();

            if ($user->company?->verificationRequest !== null) {
                $existingRequest = DataChangeRequest::where('entity_type', Journalist::class)
                    ->where('entity_id', $record->id)
                    ->where('status', DataChangeStatus::PENDING)
                    ->exists();

                if ($existingRequest) {
                    CheerfulNotification::warning(
                        'Pengajuan Sudah Ada ⏳',
                        'Masih ada pengajuan penghapusan jurnalis yang sedang menunggu verifikasi.'
                    )->send();

                    return;
                }

                $dataChangeRequest = DataChangeRequest::create([
                    'user_id' => $user->id,
                    'entity_type' => Journalist::class,
                    'entity_id' => $record->id,
                    'old_data' => $record->toArray(),
                    'new_data' => ['__delete_request__' => true],
                    'change_reason' => $data['deletion_reason'] ?? 'Penghapusan jurnalis',
                ]);

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

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

                return;
            }

            $record->delete();

            CheerfulNotification::delete()->send();
        });

        $this->visible(function (): bool {
            $user = auth()->user();

            if (! $user->hasRole(RoleEnum::PERUSAHAAN->value)) {
                return true;
            }

            if (! $user->company?->partnerMedia) {
                return false;
            }

            return true;
        });
    }
}
