<?php

namespace App\Filament\Resources\Approvals\Pages;

use App\Filament\Resources\Approvals\ApprovalResource;
use App\Models\Approval;
use App\Models\ApprovalItem;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;

class ViewApproval extends ViewRecord
{
    protected static string $resource = ApprovalResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('approve')
                ->label('Setujui')
                ->icon('heroicon-o-check-circle')
                ->color('success')
                ->requiresConfirmation()
                ->visible(fn () => $this->record->status === 'pending'
                    && ! $this->record->items()->where('user_id', auth()->id())->exists())
                ->form([Textarea::make('notes')->label('Catatan')->rows(2)])
                ->action(function (array $data): void {
                    ApprovalItem::create([
                        'approval_id' => $this->record->id,
                        'user_id'     => auth()->id(),
                        'decision'    => 'approve',
                        'notes'       => $data['notes'] ?? null,
                    ]);
                    $count = $this->record->items()->where('decision', 'approve')->count();
                    if ($count >= $this->record->required_approvals) {
                        $this->record->update(['status' => 'approved']);
                    }
                    $this->refreshFormData([]);
                }),

            Action::make('reject')
                ->label('Tolak')
                ->icon('heroicon-o-x-circle')
                ->color('danger')
                ->visible(fn () => $this->record->status === 'pending'
                    && ! $this->record->items()->where('user_id', auth()->id())->exists())
                ->form([Textarea::make('notes')->label('Alasan Penolakan')->required()->rows(2)])
                ->action(function (array $data): void {
                    ApprovalItem::create([
                        'approval_id' => $this->record->id,
                        'user_id'     => auth()->id(),
                        'decision'    => 'reject',
                        'notes'       => $data['notes'],
                    ]);
                    $this->record->update(['status' => 'rejected']);
                    $this->refreshFormData([]);
                }),
        ];
    }

    public function infolist(Schema $infolist): Schema
    {
        $record  = $this->record;
        $subject = $record->approvable;
        $label   = class_basename($record->model_type);

        return $infolist->schema([
            Section::make('Yang Dimintakan Persetujuan')->schema([
                TextEntry::make('model_type')->label('Tipe')
                    ->state($label),
                TextEntry::make('subject_title')->label('Judul / Deskripsi')
                    ->state(match (true) {
                        $subject instanceof \App\Models\CashRecord =>
                            "{$subject->description} — Rp " . number_format($subject->amount, 0, ',', '.'),
                        $subject instanceof \App\Models\Activity =>
                            $subject->title,
                        default => "#{$record->model_id}",
                    }),
                TextEntry::make('status')->badge()
                    ->color(fn ($state) => match ($state) {
                        'approved' => 'success',
                        'rejected' => 'danger',
                        default    => 'warning',
                    }),
                TextEntry::make('required_approvals')->label('Persetujuan Dibutuhkan'),
            ])->columns(2),

            Section::make('Riwayat Keputusan')->schema([
                TextEntry::make('decisions')
                    ->label('')
                    ->state(function () use ($record): string {
                        if ($record->items->isEmpty()) return 'Belum ada keputusan.';
                        return $record->items->map(fn ($item) =>
                            "• {$item->user->name}: " . ($item->decision === 'approve' ? '✓ Setuju' : '✗ Tolak') .
                            ($item->notes ? " — {$item->notes}" : '')
                        )->join("\n");
                    })
                    ->columnSpanFull(),
            ]),
        ]);
    }
}
