<?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\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\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 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 = 20;

    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 ($query) {
            $query->whereHas('partnerMedia', function ($partnerMediaQuery) {
                $partnerMediaQuery->whereHas('company', function ($companyQuery) {
                    $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) {
                if (auth()->user()->hasRole('Perusahaan')) {
                    $query->whereHas('cooperationMedia', function ($subQuery) {
                        $subQuery->whereHas('partnerMedia', function ($mediaQuery) {
                            $mediaQuery->whereHas('company', function ($companyQuery) {
                                $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 ($record) => $record->status->getLabel())
                            ->badge()
                            ->color(fn ($record) => $record->status->getColor())
                            ->disabled(),
                    ])
                    ->schema([
                        TextEntry::make('title')
                            ->label('Judul'),

                        Grid::make(4)
                            ->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('assignment_deadline')
                                    ->label('Deadline Penugasan')
                                    ->date('l, d F Y')
                                    ->placeholder('Belum ditentukan'),

                                TextEntry::make('verification_deadline')
                                    ->label('Deadline Verifikasi')
                                    ->date('l, d F Y')
                                    ->placeholder('Belum ditentukan'),
                            ]),

                        Section::make('Informasi Pembayaran')
                            ->schema([
                                Grid::make(2)
                                    ->schema([
                                        TextEntry::make('payment_amount')
                                            ->label('Jumlah Pembayaran')
                                            ->money('IDR')
                                            ->placeholder('Belum ditentukan'),

                                        TextEntry::make('payment_date')
                                            ->label('Tanggal Pembayaran')
                                            ->date('l, d F Y')
                                            ->placeholder('Belum dibayar'),
                                    ]),
                            ])
                            ->visible(fn ($record) => $record->payment_amount || $record->payment_date),

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

    public static function getRelations(): array
    {
        return [
            CooperationMediaRelationManager::class,
            CooperationProposalRelationManager::class,
            TaskAssignmentRelationManager::class,
            ReportRelationManager::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,
            ]);
    }
}
