<?php

namespace App\Filament\Resources\ElevResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;

class ObservatiiRelationManager extends RelationManager
{
    protected static string $relationship = 'observatii';
    protected static ?string $title = 'Observații';

    public function isReadOnly(): bool
    {
        return Auth::user()?->hasAnyRole(['parinte', 'elev']) ?? true;
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('perioada_id')
                    ->label('Perioada')
                    ->options(fn() => \App\Models\Perioada::where('clasa_id', $this->getOwnerRecord()->clasa_id)
                        ->orderBy('ordine')
                        ->pluck('nume', 'id'))
                    ->searchable()
                    ->nullable(),
                Forms\Components\Select::make('tip')
                    ->label('Tip')
                    ->options([
                        'comportament' => 'Comportament',
                        'merit' => 'Merit / Recompensă',
                        'sanctiune' => 'Sancțiune',
                        'medical' => 'Medical',
                        'alta' => 'Altele',
                    ])
                    ->default('comportament')
                    ->required(),
                Forms\Components\Textarea::make('continut')
                    ->label('Observație')
                    ->required()
                    ->rows(3)
                    ->columnSpanFull(),
            ]);
    }

    public function table(Table $table): Table
    {
        $user = Auth::user();
        $elev = $this->getOwnerRecord();
        $isDiriginte = $user?->hasRole('diriginte') && $elev->clasa?->diriginte_user_id === $user?->id;
        $canCreate = $user?->hasAnyRole(['admin', 'director', 'secretariat']) || $isDiriginte;

        return $table
            ->recordTitleAttribute('continut')
            ->columns([
                Tables\Columns\TextColumn::make('data_ora')
                    ->label('Data')
                    ->dateTime('d.m.Y H:i')
                    ->sortable(),
                Tables\Columns\TextColumn::make('tip')
                    ->label('Tip')
                    ->badge()
                    ->color(fn (string $state) => match ($state) {
                        'merit' => 'success',
                        'sanctiune' => 'danger',
                        'comportament' => 'warning',
                        'medical' => 'info',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn (string $state) => match ($state) {
                        'comportament' => 'Comportament',
                        'merit' => 'Merit',
                        'sanctiune' => 'Sancțiune',
                        'medical' => 'Medical',
                        'alta' => 'Altele',
                        default => $state,
                    }),
                Tables\Columns\TextColumn::make('continut')
                    ->label('Observație')
                    ->wrap()
                    ->limit(100),
                Tables\Columns\TextColumn::make('adaugatDe.name')
                    ->label('Adăugat de'),
            ])
            ->defaultSort('data_ora', 'desc')
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label('Adaugă observație')
                    ->visible($canCreate)
                    ->mutateFormDataUsing(function (array $data): array {
                        $data['adaugat_de'] = Auth::id();
                        $data['data_ora'] = now();
                        return $data;
                    }),
            ])
            ->actions([
                Tables\Actions\DeleteAction::make()
                    ->visible(fn () => $user?->hasAnyRole(['admin', 'director'])),
            ])
            ->bulkActions([]);
    }
}
