<?php

namespace App\Filament\Resources\ElevResource\RelationManagers;

use Carbon\Carbon;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use App\Models\Materie;
use Illuminate\Support\Facades\Auth;

class AbsenteRelationManager extends RelationManager
{
    protected static string $relationship = 'absente';
    protected static ?string $title = 'Absențe';

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

    public function form(Form $form): Form
    {
        $user = Auth::user();
        $isProfesor = $user?->hasRole('profesor');

        return $form
            ->schema([
                Forms\Components\Select::make('materie_id')
                    ->label('Materia')
                    ->options(function () use ($user, $isProfesor) {
                        $query = Materie::where('clasa_id', $this->getOwnerRecord()->clasa_id);
                        if ($isProfesor && !$user?->hasAnyRole(['admin', 'director', 'diriginte'])) {
                            $query->where('user_id', $user->id);
                        }
                        return $query->pluck('nume', 'id');
                    })
                    ->required()
                    ->searchable(),
                Forms\Components\DatePicker::make('data')
                    ->label('Data')
                    ->required()
                    ->default(now()),
                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'))
                    ->required()
                    ->searchable(),
                Forms\Components\Toggle::make('motivata')
                    ->label('Motivată')
                    ->default(false)
                    ->disabled(function () {
                        $user = Auth::user();
                        if ($user?->hasAnyRole(['admin', 'director'])) {
                            return false;
                        }
                        if ($user?->hasRole('diriginte')) {
                            return $this->getOwnerRecord()->clasa?->diriginte_user_id !== $user->id;
                        }
                        return true;
                    })
                    ->helperText(function () {
                        $user = Auth::user();
                        if ($user?->hasRole('profesor') && !$user?->hasAnyRole(['diriginte', 'admin', 'director'])) {
                            return 'Doar dirigintele poate motiva absențele';
                        }
                        return null;
                    }),
                Forms\Components\Textarea::make('motiv')
                    ->label('Motiv')
                    ->nullable(),
            ]);
    }

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

        return $table
            ->recordTitleAttribute('data')
            ->columns([
                Tables\Columns\TextColumn::make('perioada.nume')
                    ->label('Perioada'),
                Tables\Columns\TextColumn::make('materie.nume')
                    ->label('Materia')
                    ->searchable(),
                Tables\Columns\TextColumn::make('data')
                    ->label('Data')
                    ->date()
                    ->sortable(),
                Tables\Columns\IconColumn::make('motivata')
                    ->label('Motivată')
                    ->boolean(),
                Tables\Columns\TextColumn::make('termen_motivare')
                    ->label('Termen')
                    ->state(function ($record) {
                        if ($record->motivata) return '✓';
                        $limita = self::dataLimita($record);
                        if (Carbon::today()->greaterThan($limita)) return 'Expirat';
                        return $limita->format('d.m.Y');
                    })
                    ->color(function ($record) {
                        if ($record->motivata) return 'success';
                        $limita = self::dataLimita($record);
                        $azi = Carbon::today();
                        if ($azi->greaterThan($limita)) return 'danger';
                        if ($azi->diffInDays($limita) <= 3) return 'warning';
                        return 'gray';
                    })
                    ->badge(),
            ])
            ->defaultSort('data', 'desc')
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label('Adaugă absență')
                    ->visible($canCreate)
                    ->mutateFormDataUsing(function (array $data): array {
                        $data['adaugat_de'] = Auth::id();
                        $data['adaugat_la'] = now();
                        return $data;
                    }),
            ])
            ->actions([
                Tables\Actions\Action::make('motiveaza')
                    ->label('Motivează')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->visible(fn($record) => $canEdit && !$record->motivata)
                    ->requiresConfirmation()
                    ->modalHeading('Motivează absența')
                    ->modalDescription(function ($record) {
                        $limita = self::dataLimita($record);
                        if (Carbon::today()->greaterThan($limita)) {
                            return "⚠️ ATENȚIE: Termenul de motivare ({$limita->format('d.m.Y')}) a expirat! Motivarea se va înregistra cu întârziere.";
                        }
                        return "Termen de motivare: {$limita->format('d.m.Y')}.";
                    })
                    ->form([
                        Forms\Components\Textarea::make('motiv')
                            ->label('Motiv motivare')
                            ->required(),
                    ])
                    ->action(function ($record, array $data) {
                        $limita = self::dataLimita($record);
                        $intarziere = Carbon::today()->greaterThan($limita);
                        $record->update([
                            'motivata' => true,
                            'motiv' => $data['motiv'] . ($intarziere ? ' [motivată cu întârziere]' : ''),
                            'modificat_de' => Auth::id(),
                            'modificat_la' => now(),
                            'motiv_modificare' => 'Absență motivată' . ($intarziere ? ' (după termenul ROFUIP)' : ''),
                        ]);
                    }),
                Tables\Actions\Action::make('demotiveaza')
                    ->label('Demotivează')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->visible(fn($record) => $canEdit && $record->motivata)
                    ->requiresConfirmation()
                    ->modalHeading('Demotivează absența')
                    ->form([
                        Forms\Components\Textarea::make('motiv_modificare')
                            ->label('Motiv demotivare')
                            ->required(),
                    ])
                    ->action(function ($record, array $data) {
                        $record->update([
                            'motivata' => false,
                            'motiv' => null,
                            'modificat_de' => Auth::id(),
                            'modificat_la' => now(),
                            'motiv_modificare' => $data['motiv_modificare'],
                        ]);
                    }),
                Tables\Actions\DeleteAction::make()
                    ->visible($user?->hasAnyRole(['admin', 'director'])),
            ])
            ->bulkActions([]);
    }

    protected static function dataLimita($record): Carbon
    {
        $scoala = $record->elev?->clasa?->scoala;
        $tip = $scoala?->termen_motivare_tip ?? 'zile_lucratoare';
        $dataAbsenta = Carbon::parse($record->data);

        if ($tip === 'data_fixa') {
            $zi = $scoala?->termen_motivare_zi ?? 10;
            $lunaUrmatoare = $dataAbsenta->copy()->addMonth();
            return Carbon::create($lunaUrmatoare->year, $lunaUrmatoare->month, min($zi, $lunaUrmatoare->daysInMonth));
        }

        $zile = $scoala?->termen_motivare_zile ?? 7;
        $limita = $dataAbsenta->copy();
        $zileLucratoare = 0;
        while ($zileLucratoare < $zile) {
            $limita->addDay();
            if ($limita->isWeekday()) {
                $zileLucratoare++;
            }
        }
        return $limita;
    }
}
