<?php

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

use App\Enums\ApprovalStatus;
use App\Models\Report;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;

class ReportRelationManager extends RelationManager
{
    protected static string $relationship = 'reports';

    protected static ?string $title = 'Laporan';

    public function isReadOnly(): bool
    {
        return false;
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('title')
                    ->placeholder('Dirgahayu Purwakarta')
                    ->required()
                    ->maxLength(200),

                DatePicker::make('publication_date')
                    ->label('Tanggal Publikasi')
                    ->placeholder(fn () => now()->format('l, d F Y'))
                    ->native(false)
                    ->displayFormat('l, d F Y')
                    ->required(),

                TextInput::make('link')
                    ->label('Tautan')
                    ->placeholder('https://example.com')
                    ->maxLength(50)
                    ->url()
                    ->required(),

                Textarea::make('description')
                    ->label('Deskripsi')
                    ->placeholder('....')
                    ->required(),

                SpatieMediaLibraryFileUpload::make('image')
                    ->label('Gambar')
                    ->disk(config('filesystems.default'))
                    ->acceptedFileTypes(['image/*'])
                    ->maxSize(1024 * 3)
                    ->collection('reports')
                    ->image()
                    ->required(),
            ])
            ->columns(1);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('title')
            ->columns([
                TextColumn::make('title')
                    ->label('Judul')
                    ->searchable(),

                TextColumn::make('publication_date')
                    ->label('Tanggal Publikasi')
                    ->date('l, d F Y'),

                TextColumn::make('link')
                    ->label('Link')
                    ->limit(30)
                    ->url(fn ($record) => $record->link)
                    ->openUrlInNewTab(),

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

                TextColumn::make('rejectionReasons.reason')
                    ->label('Alasan Penolakan')
                    ->searchable(),
            ])
            ->filters([])
            ->recordActions([
                Action::make('accept')
                    ->label('Terima')
                    ->icon(Heroicon::OutlinedCheck)
                    ->color('success')
                    ->action(function (Report $record) {
                        $record->update([
                            'status' => ApprovalStatus::ACCEPTED,
                        ]);

                        Notification::make()
                            ->title('Laporan Diterima')
                            ->body("Laporan '{$record->title}' telah diterima.")
                            ->success()
                            ->send();
                    })
                    ->visible(fn (Report $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 (Report $record, array $data) {
                        $record->update([
                            'status' => ApprovalStatus::REJECTED,
                        ]);

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

                        Notification::make()
                            ->title('Laporan Ditolak')
                            ->body("Laporan '{$record->title}' telah ditolak.")
                            ->warning()
                            ->send();
                    })
                    ->visible(fn (Report $record) => ! auth()->user()->hasRole('Perusahaan') && $record->status === ApprovalStatus::PENDING)
                    ->modalWidth(Width::Large),
            ])
            ->headerActions([
                CreateAction::make()
                    ->label('Buat Laporan')
                    ->modalWidth(Width::Large)
                    ->modalHeading('Buat Laporan')
                    ->mutateDataUsing(function (array $data): array {
                        $data['task_assignment_id'] = $this->getOwnerRecord()->taskAssignments()->first()?->id;

                        return $data;
                    }),
            ])
            ->toolbarActions([]);
    }
}
