<?php

namespace App\Filament\AssociationAdmin\Resources\AssociationProjectCharterResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\HtmlString;

class AssociationDeliverablesRelationManager extends RelationManager
{
    protected static string $relationship = 'deliverables';

    public static function getTitle(Model $ownerRecord, string $pageClass): string
    {
        return __('project_charter_deliverable.deliverables');
    }

    public static function getModelLabel(): string
    {
        return __('project_charter_deliverable.deliverable');
    }

    public static function getPluralModelLabel(): string
    {
        return __('project_charter_deliverable.deliverables');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                // Read-only fields for association admin
                Forms\Components\TextInput::make('name')
                    ->label(__('project_charter_deliverable.name'))
                    ->disabled()
                    ->dehydrated(false),

                Forms\Components\DatePicker::make('expected_delivery_date')
                    ->label(__('project_charter_deliverable.expected_delivery_date'))
                    ->disabled()
                    ->dehydrated(false),

                Forms\Components\TextInput::make('estimated_cost')
                    ->label(__('project_charter_deliverable.estimated_cost'))
                    ->numeric()
                    ->disabled()
                    ->dehydrated(false)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>')),

                // File upload - only enabled if canOverwriteFile returns true
                SpatieMediaLibraryFileUpload::make('deliverable_files')
                    ->label(__('project_charter_deliverable.file'))
                    ->visibility('private')
                    ->collection('deliverable_files')
                    ->acceptedFileTypes(['application/pdf'])
                    ->maxSize(10240) // 10MB
                    ->helperText(__('project_charter_deliverable.file_helper'))
                    ->disabled(fn ($record) => $record && ! $record->canOverwriteFile())
                    ->downloadable()
                    ->reactive(),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('name')
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label(__('project_charter_deliverable.name'))
                    ->searchable()
                    ->sortable()
                    ->weight('medium'),

                Tables\Columns\TextColumn::make('expected_delivery_date')
                    ->label(__('project_charter_deliverable.expected_delivery_date'))
                    ->date()
                    ->sortable()
                    ->icon('heroicon-o-calendar'),

                Tables\Columns\TextColumn::make('estimated_cost')
                    ->label(__('project_charter_deliverable.estimated_cost'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->icon('heroicon-o-banknotes')
                    ->color('primary'),

                Tables\Columns\TextColumn::make('file_status')
                    ->label(__('project_charter_deliverable.file_status'))
                    ->badge()
                    ->color(fn ($state) => match ($state) {
                        'pending' => 'warning',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => $state ? __('project_charter_deliverable.file_status_'.$state) : __('project_charter_deliverable.no_file'))
                    ->sortable(),

                Tables\Columns\IconColumn::make('has_file')
                    ->label(__('project_charter_deliverable.has_file'))
                    ->boolean()
                    ->state(fn ($record) => $record->hasFile())
                    ->toggleable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('project_charter_deliverable.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('file_status')
                    ->label(__('project_charter_deliverable.file_status'))
                    ->options([
                        'pending' => __('project_charter_deliverable.file_status_pending'),
                        'approved' => __('project_charter_deliverable.file_status_approved'),
                        'rejected' => __('project_charter_deliverable.file_status_rejected'),
                    ])
                    ->placeholder(__('All Statuses')),
            ])
            ->headerActions([
                // No create action for association admin
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make()
                        ->visible(fn ($record) => $record->canOverwriteFile())
                        ->modalHeading(__('project_charter_deliverable.edit_deliverable_file')),
                ]),
            ])
            ->bulkActions([
                // No bulk actions for association admin
            ])
            ->emptyStateIcon('heroicon-o-document-check')
            ->emptyStateHeading(__('project_charter_deliverable.no_deliverables'))
            ->defaultSort('expected_delivery_date', 'asc');
    }

    public function isReadOnly(): bool
    {
        return false; // Allow editing of files when canOverwriteFile() returns true
    }
}
