<?php

namespace App\Filament\Resources\Manage\Cooperations;

use App\Enums\RoleEnum;
use App\Filament\Resources\Manage\Cooperations\Pages\CreateCooperation;
use App\Filament\Resources\Manage\Cooperations\Pages\EditCooperation;
use App\Filament\Resources\Manage\Cooperations\Pages\ListCooperations;
use App\Filament\Resources\Manage\Cooperations\Pages\ViewCooperation;
use App\Filament\Resources\Manage\Cooperations\RelationManagers\CooperationMediaRelationManager;
use App\Filament\Resources\Manage\Cooperations\RelationManagers\CooperationPaymentRelationManager;
use App\Filament\Resources\Manage\Cooperations\RelationManagers\CooperationProposalRelationManager;
use App\Filament\Resources\Manage\Cooperations\RelationManagers\ReportRelationManager;
use App\Filament\Resources\Manage\Cooperations\RelationManagers\TaskAssignmentRelationManager;
use App\Filament\Resources\Manage\Cooperations\Schemas\CooperationForm;
use App\Filament\Resources\Manage\Cooperations\Tables\CooperationsTable;
use App\Models\Cooperation;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Infolists\Components\ImageEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Joaopaulolndev\FilamentPdfViewer\Infolists\Components\PdfViewerEntry;
use UnitEnum;

class CooperationResource extends Resource
{
    protected static ?string $model = Cooperation::class;

    protected static string|UnitEnum|null $navigationGroup = 'Kelola';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::HandRaised;

    protected static ?string $navigationLabel = 'Kerja Sama';

    protected static ?int $navigationSort = 7;

    protected static ?string $recordTitleAttribute = 'title';

    protected static ?string $slug = 'manage/cooperations';

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::when(auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value), function (Builder $query): void {
            $query->whereHas('partnerMedia', function (Builder $partnerMediaQuery): void {
                $partnerMediaQuery->whereHas('company', function (Builder $companyQuery): void {
                    $companyQuery->where('user_id', auth()->id());
                });
            });
        })
            ->count();
    }

    public static function form(Schema $schema): Schema
    {
        return CooperationForm::configure($schema);
    }

    public static function table(Table $table): Table
    {
        return CooperationsTable::configure($table)
            ->modifyQueryUsing(function (Builder $query): Builder {
                if (auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value)) {
                    $query->whereHas('cooperationMedia', function (Builder $subQuery): void {
                        $subQuery->whereHas('partnerMedia', function (Builder $mediaQuery): void {
                            $mediaQuery->whereHas('company', function (Builder $companyQuery): void {
                                $companyQuery->where('user_id', auth()->id());
                            });
                        });
                    });
                }

                return $query;
            });
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('Informasi Kerja Sama')
                    ->headerActions([
                        Action::make('status')
                            ->label(fn (Cooperation $record): ?string => $record->status->getLabel())
                            ->badge()
                            ->color(fn (Cooperation $record): string|array|null => $record->status->getColor())
                            ->disabled(),
                    ])
                    ->schema([
                        TextEntry::make('title')
                            ->label('Judul'),

                        Grid::make(3)
                            ->schema([
                                TextEntry::make('initial_submission_date')
                                    ->label('Tanggal Pengajuan Awal')
                                    ->date('l, d F Y'),

                                TextEntry::make('final_submission_date')
                                    ->label('Tanggal Pengajuan Akhir')
                                    ->date('l, d F Y'),

                                TextEntry::make('taskAssignment.start_date')
                                    ->label('Tanggal Mulai Penugasan')
                                    ->date('l, d F Y')
                                    ->placeholder('Belum ditentukan'),

                                TextEntry::make('taskAssignment.end_date')
                                    ->label('Tanggal Selesai Penugasan')
                                    ->date('l, d F Y')
                                    ->placeholder('Belum ditentukan'),

                                TextEntry::make('payment_date')
                                    ->label('Tanggal Pembayaran')
                                    ->date('l, d F Y')
                                    ->placeholder('Belum dibayar'),

                                TextEntry::make('completed_at')
                                    ->label('Tanggal Selesai')
                                    ->date('l, d F Y')
                                    ->placeholder('Masih berjalan'),
                            ]),

                        Grid::make(3)
                            ->schema([
                                PdfViewerEntry::make('proposal_template')
                                    ->label('Template Proposal')
                                    ->getStateUsing(fn (Cooperation $record): ?string => optional($record->getMedia('cooperations')->where('custom_properties.doc_type', 'proposal-template')->sortByDesc('created_at')->first())->getPathRelativeToRoot())
                                    ->disk(config('filesystems.default'))
                                    ->columnSpan(2)
                                    ->visible(fn (Cooperation $record): bool => $record->getMedia('cooperations')->where('custom_properties.doc_type', 'proposal-template')->isNotEmpty()),

                                ImageEntry::make('banner')
                                    ->label('Banner')
                                    ->getStateUsing(fn (Cooperation $record): ?string => optional($record->getMedia('banner')->sortByDesc('created_at')->first() ?? $record->getMedia('cooperations')->where('custom_properties.doc_type', 'banner')->sortByDesc('created_at')->first())->getPathRelativeToRoot())
                                    ->disk(config('filesystems.default'))
                                    ->visible(fn (Cooperation $record): bool => $record->getMedia('banner')->isNotEmpty() || $record->getMedia('cooperations')->where('custom_properties.doc_type', 'banner')->isNotEmpty()),
                            ])
                            ->visible(fn (Cooperation $record): bool => $record->getMedia('banner')->isNotEmpty() || $record->getMedia('cooperations')->where('custom_properties.doc_type', 'banner')->isNotEmpty() || $record->getMedia('cooperations')->where('custom_properties.doc_type', 'proposal-template')->isNotEmpty()),

                        TextEntry::make('description')
                            ->label('Deskripsi'),
                    ]),
            ])
            ->columns(1);
    }

    public static function getRelations(): array
    {
        return [
            CooperationMediaRelationManager::class,
            CooperationProposalRelationManager::class,
            TaskAssignmentRelationManager::class,
            ReportRelationManager::class,
            CooperationPaymentRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListCooperations::route('/'),
            'create' => CreateCooperation::route('/create'),
            'view' => ViewCooperation::route('/{record}'),
            'edit' => EditCooperation::route('/{record}/edit'),
        ];
    }

    public static function getRecordRouteBindingEloquentQuery(): Builder
    {
        return parent::getRecordRouteBindingEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
