<?php

namespace App\Filament\Resources\Manage\Cooperations\RelationManagers;

use App\Enums\ApprovalStatus;
use App\Enums\RoleEnum;
use App\Filament\Resources\Manage\Cooperations\Actions\Proposal\AcceptAction;
use App\Filament\Resources\Manage\Cooperations\Actions\Proposal\RejectAction;
use App\Models\CooperationProposal;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\ViewAction;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use Joaopaulolndev\FilamentPdfViewer\Infolists\Components\PdfViewerEntry;

class CooperationProposalRelationManager extends RelationManager
{
    protected static ?string $recordTitleAttribute = 'e_catalog';

    protected static string $relationship = 'proposal';

    protected static ?string $title = 'Proposal';

    public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool
    {
        if (auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value)) {
            return $ownerRecord->cooperationMedia()
                ->whereHas('partnerMedia', function ($query) {
                    $query->whereHas('company', function ($query) {
                        $query->where('user_id', auth()->id());
                    });
                })
                ->where('status', ApprovalStatus::ACCEPTED)
                ->exists();
        }

        return true;
    }

    public static function getBadge(Model $ownerRecord, string $pageClass): ?string
    {
        if (auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value)) {
            return null;
        }

        return (string) $ownerRecord->proposal()->count();
    }

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('partnerMedia.name')
                    ->label('Media')
                    ->searchable()
                    ->visible(! auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value)),

                TextColumn::make('e_catalog')
                    ->label('E-Catalog')
                    ->url(fn (CooperationProposal $record): ?string => $record->e_catalog)
                    ->openUrlInNewTab()
                    ->color('primary'),

                TextColumn::make('description')
                    ->label('Deskripsi'),

                TextColumn::make('status')
                    ->label('Status')
                    ->badge(),

                TextColumn::make('submitted_at')
                    ->label('Diajukan')
                    ->dateTime('l, d F Y H:i:s')
                    ->sortable(),

                TextColumn::make('responded_at')
                    ->label('Ditanggapi')
                    ->dateTime('l, d F Y H:i:s')
                    ->sortable(),

                TextColumn::make('rejectionReasons.reason')
                    ->label('Alasan Penolakan')
                    ->searchable(),
            ])
            ->filters([])
            ->headerActions([])
            ->recordActions([
                ViewAction::make(),

                AcceptAction::make('accept'),

                RejectAction::make('reject'),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->successNotification(
                            Notification::make()
                                ->title('Proposal Dihapus! 🗑️')
                                ->body('Semua proposal yang dipilih telah berhasil dihapus. 👋')
                                ->success()
                        ),
                ]),
            ])
            ->emptyStateIcon(Heroicon::DocumentText)
            ->emptyStateDescription('Tidak ada proposal yang diajukan.')
            ->defaultSort('created_at', 'desc')
            ->modifyQueryUsing(function ($query) {
                $user = auth()->user();

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

                return $query->whereHas('partnerMedia.company', function ($q) use ($user) {
                    $q->where('user_id', $user->id);
                });
            });
    }

    public function infolist(Schema $infolist): Schema
    {
        return $infolist
            ->components([
                Grid::make(2)
                    ->schema([
                        TextEntry::make('partnerMedia.name')
                            ->label('Media')
                            ->visible(! auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value)),

                        TextEntry::make('status')
                            ->label('Status')
                            ->badge(),

                        TextEntry::make('submitted_at')
                            ->label('Diajukan')
                            ->dateTime('l, d F Y H:i:s'),

                        TextEntry::make('responded_at')
                            ->label('Ditanggapi')
                            ->dateTime('l, d F Y H:i:s'),
                    ]),

                TextEntry::make('e_catalog')
                    ->label('E-Catalog')
                    ->url(fn (CooperationProposal $record): ?string => $record->e_catalog)
                    ->openUrlInNewTab()
                    ->color('primary')
                    ->visible(fn (CooperationProposal $record): ?string => $record->e_catalog),

                TextEntry::make('description')
                    ->label('Deskripsi')
                    ->columnSpanFull(),

                PdfViewerEntry::make('proposal_attachment')
                    ->label('Lampiran Proposal')
                    ->getStateUsing(fn (CooperationProposal $record): ?string => optional($record->getMedia('cooperations')->where('custom_properties.doc_type', 'proposal-attachment')->sortByDesc('created_at')->first())->getPathRelativeToRoot())
                    ->disk(config('filesystems.default')),

                TextEntry::make('rejectionReasons.reason')
                    ->label('Alasan Penolakan')
                    ->listWithLineBreaks()
                    ->visible(fn (CooperationProposal $record): bool => $record->status === ApprovalStatus::REJECTED && $record->rejectionReasons->isNotEmpty())
                    ->columnSpanFull(),
            ])
            ->columns(1);
    }
}
