<?php

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

use App\Enums\ApprovalStatus;
use App\Models\CooperationProposal;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\Textarea;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Infolist;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

class CooperationProposalRelationManager extends RelationManager
{
    protected static string $relationship = 'proposals';

    protected static ?string $title = 'Proposal';

    public static function getBadge(Model $ownerRecord, string $pageClass): ?string
    {
        return $ownerRecord->proposals()->count();
    }

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

                TextColumn::make('e_catalog')
                    ->label('E-Catalog')
                    ->url(fn ($record) => $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(),

                Action::make('accept')
                    ->label('Terima')
                    ->icon(Heroicon::OutlinedCheck)
                    ->color('success')
                    ->action(function (CooperationProposal $record) {
                        $record->update([
                            'status' => ApprovalStatus::ACCEPTED,
                            'responded_at' => now(),
                        ]);

                        Notification::make()
                            ->title('Proposal Diterima')
                            ->body("Proposal dari {$record->partnerMedia->name} telah diterima.")
                            ->success()
                            ->send();
                    })
                    ->visible(fn (CooperationProposal $record) => ! auth()->user()->hasRole('Perusahaan') && $record->status === ApprovalStatus::PENDING),

                Action::make('reject')
                    ->label('Tolak')
                    ->icon(Heroicon::XMark)
                    ->color('danger')
                    ->schema([
                        Textarea::make('reason')
                            ->label('Alasan Penolakan')
                            ->placeholder('...')
                            ->required(),
                    ])
                    ->action(function (CooperationProposal $record, array $data) {
                        $record->update([
                            'status' => ApprovalStatus::REJECTED,
                            'responded_at' => now(),
                        ]);

                        $record->rejectionReasons()->create(['reason' => $data['reason']]);

                        Notification::make()
                            ->title('Proposal Ditolak')
                            ->body("Proposal dari {$record->partnerMedia->name} telah ditolak.")
                            ->warning()
                            ->send();
                    })
                    ->visible(fn (CooperationProposal $record) => ! auth()->user()->hasRole('Perusahaan') && $record->status === ApprovalStatus::PENDING)
                    ->modalWidth(Width::Large),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ])
            ->recordAction(null);
    }

    // public function infolist(Infolist $infolist): Infolist
    // {
    //     return $infolist
    //         ->schema([
    //             TextEntry::make('e_catalog')
    //                 ->label('File Proposal')
    //                 ->url(fn($record) => $record->e_catalog)
    //                 ->openUrlInNewTab()
    //                 ->columnSpanFull(),
    //         ]);
    // }
}
