<?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
{
    public static function getDefaultName(): ?string
    {
        return 'sendProposal';
    }

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

        $this->label('Ajukan Proposal')
            ->icon(Heroicon::OutlinedDocumentText)
            ->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())
                    ->helperText('Format yang diterima: PDF. Ukuran maksimum: 10 MB.')
                    ->required(),
            ])
            ->action(function (Cooperation $record, array $data): void {
                $cooperationMedia = $record->cooperationMedia()
                    ->whereHas('partnerMedia.company', function (Builder $query): void {
                        $query->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(
                        CheerfulNotification::getByKey('cooperation.proposal_sent_success'),
                        CheerfulNotification::getByKey('cooperation.proposal_approved_desc')
                    )->send();

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

                            $admin->notify(new BroadcastNotification([
                                'title' => $isRevision
                                    ? CheerfulNotification::getByKey('cooperation.proposal_update')
                                    : CheerfulNotification::getByKey('cooperation.new_proposal'),
                                'body' => $isRevision
                                    ? CheerfulNotification::getByKey('notification.user_updated_proposal', ['user__name' => $user->name, 'cooperationMedia__partnerMedia__name' => $cooperationMedia->partnerMedia->name, 'record__title' => $record->title])
                                    : CheerfulNotification::getByKey('notification.user_submitted_proposal', ['user__name' => $user->name, 'cooperationMedia__partnerMedia__name' => $cooperationMedia->partnerMedia->name, 'record__title' => $record->title]),
                                'action' => [
                                    Action::make('view')
                                        ->label('Lihat')
                                        ->url(CooperationResource::getUrl('view', ['record' => $record->id, 'relation' => 1])),
                                ],
                            ]));
                        });
                }
            })
            ->modalHeading(fn () => CheerfulNotification::getByKey('cooperation.submit_proposal_title'))
            ->modalDescription(fn () => CheerfulNotification::getByKey('cooperation.submit_proposal_desc'))
            ->modalSubmitActionLabel('Kirim Proposal')
            ->visible(function (Cooperation $record): bool {
                $user = auth()->user();

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

                $cooperationMedia = $record->cooperationMedia()
                    ->whereHas('partnerMedia.company', function (Builder $query): void {
                        $query->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);
    }
}
