<?php

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

use App\Enums\ApprovalStatus;
use App\Enums\RoleEnum;
use App\Filament\Resources\Manage\Cooperations\CooperationResource;
use App\Filament\Support\CheerfulNotification;
use App\Models\Cooperation;
use App\Models\User;
use App\Notifications\BroadcastNotification;
use Asmit\FilamentUpload\Forms\Components\AdvancedFileUpload;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Storage;

class SendProposalAction extends Action
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Ajukan Proposal')
            ->icon(Heroicon::DocumentText)
            ->color('info')
            ->schema([
                TextInput::make('e_catalog')
                    ->label('E-Catalog')
                    ->placeholder('https://katalog.inaproc.id/purwakarta-kita-media-karya')
                    ->autocomplete(false)
                    ->autofocus()
                    ->nullable()
                    ->url()
                    ->required()
                    ->maxLength(200),

                Textarea::make('description')
                    ->label('Deskripsi')
                    ->autocomplete(false)
                    ->required()
                    ->rows(4)
                    ->placeholder('...'),

                AdvancedFileUpload::make('proposal_attachment')
                    ->label('Lampiran')
                    ->disk(config('filesystems.default'))
                    ->acceptedFileTypes(['application/pdf'])
                    ->maxSize(1024 * 10)
                    ->directory(fn (): string => 'cooperations/proposal-attachment/'.now()->toDateString())
                    ->required(),
            ])
            ->action(function (Cooperation $record, array $data): void {
                $cooperationMedia = $record->cooperationMedia()
                    ->whereHas('partnerMedia', function (Builder $query): void {
                        $query->whereHas('company', function (Builder $subQuery): void {
                            $subQuery->where('user_id', auth()->id());
                        });
                    })
                    ->first();

                if ($cooperationMedia) {
                    $existingProposal = $record->proposal()
                        ->where('partner_media_id', $cooperationMedia->partner_media_id)
                        ->first();

                    $isRevision = (bool) $existingProposal;

                    $proposal = $record->proposal()->create([
                        'partner_media_id' => $cooperationMedia->partner_media_id,
                        'description' => $data['description'],
                        'e_catalog' => $data['e_catalog'],
                        'status' => ApprovalStatus::PENDING->value,
                    ]);

                    if (! empty($data['proposal_attachment'])) {
                        $filePath = collect($data['proposal_attachment'])->first();
                        $fullPath = Storage::disk(config('filesystems.default'))->path($filePath);

                        if (file_exists($fullPath)) {
                            $proposal->addMediaFromDisk($filePath, config('filesystems.default'))
                                ->preservingOriginal()
                                ->withCustomProperties([
                                    'feature' => 'cooperations',
                                    'date' => now()->toDateString(),
                                    'doc_type' => 'proposal-attachment',
                                ])
                                ->toMediaCollection('cooperations');
                        }
                    }

                    CheerfulNotification::success(
                        'Berhasil Diajukan! 🚀',
                        'Yeay! Proposal kerja sama Anda sudah terkirim ke Admin. Mohon ditunggu ya, semoga hasilnya memuaskan! ✨'
                    )->send();

                    // Notify Admin
                    User::superAdmin()
                        ->get()
                        ->each(function ($admin) use ($isRevision, $record, $cooperationMedia): void {
                            $user = auth()->user();

                            $admin->notify(new BroadcastNotification([
                                'title' => $isRevision ? 'Pembaruan Proposal Kerja Sama ✨' : 'Ada Proposal Kerja Sama Baru! 🚀',
                                'body' => $isRevision
                                    ? "Cihuy! {$user->name} baru saja memperbarui proposal kerja sama untuk media {$cooperationMedia->partnerMedia->name} pada kampanye {$record->title}. Yuk, cek perubahannya!"
                                    : "Halo Admin! {$user->name} baru saja mengajukan proposal kerja sama baru untuk media {$cooperationMedia->partnerMedia->name} pada kampanye {$record->title}. Segera diproses ya! 😊",
                                'action' => [
                                    Action::make('view')
                                        ->label('Lihat')
                                        ->url(CooperationResource::getUrl('view', ['record' => $record->id, 'relation' => 1])),
                                ],
                            ]));
                        });
                }
            })
            ->modalHeading('Proposal Kerja Sama')
            ->modalSubmitActionLabel('Kirim Proposal')
            ->visible(function (Cooperation $record): bool {
                $user = auth()->user();

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

                $cooperationMedia = $record->cooperationMedia()
                    ->whereHas('partnerMedia', function (Builder $query): void {
                        $query->whereHas('company', function (Builder $subQuery): void {
                            $subQuery->where('user_id', auth()->id());
                        });
                    })
                    ->first();

                return $cooperationMedia
                    && $cooperationMedia->status === ApprovalStatus::ACCEPTED
                    && ! $record->proposal()
                        ->where('partner_media_id', $cooperationMedia->partner_media_id)
                        ->where(fn (Builder $q): Builder => $q->accepted()->orWhere(fn (Builder $q): Builder => $q->pending()))
                        ->exists();
            })
            ->modalWidth(Width::Large);
    }
}
