<?php

namespace App\Filament\Admin\Resources\WorkflowTemplates\RelationManagers;

use App\Workflows\Services\StepTemplateService;
use Exception;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

class StepTemplatesRelationManager extends RelationManager
{
    protected static string $relationship = 'stepTemplates';

    protected static ?string $recordTitleAttribute = 'label';

    public static function getTitle(Model $ownerRecord, string $pageClass): string
    {
        return __('workflow.templates.step_templates.tab_label');
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('label')
                    ->label(__('workflow.templates.step_templates.name'))
                    ->helperText(__('workflow.templates.step_templates.name_help'))
                    ->required()
                    ->maxLength(255),

                Select::make('system_key')
                    ->label(__('workflow.templates.step_templates.system_key'))
                    ->helperText(__('workflow.templates.step_templates.system_key_help'))
                    ->options(function () {
                        $workflowTemplate = $this->getOwnerRecord();

                        return StepTemplateService::getSystemKeyOptions($workflowTemplate->subject_type);
                    })
                    ->helperText(function () {
                        $workflowTemplate = $this->getOwnerRecord();
                        $requiredKeys = StepTemplateService::getRequiredSystemKeys($workflowTemplate->subject_type);
                        if (! empty($requiredKeys)) {
                            return __('workflow.templates.step_templates.required_keys_help', ['keys' => implode(', ', $requiredKeys)]);
                        }

                        return __('workflow.templates.step_templates.choose_key_help');
                    })
                    ->required()
                    ->searchable()
                    ->disabled(fn ($record) => $record && $record->is_locked),

                TextInput::make('position')
                    ->label(__('workflow.templates.step_templates.position'))
                    ->numeric()
                    ->required()
                    ->disabled(fn ($record) => $record && $record->is_locked),

                Select::make('step_template_key')
                    ->label(__('workflow.templates.step_templates.step_template'))
                    ->options(fn () => StepTemplateService::getSelectOptions())
                    ->helperText(__('workflow.templates.step_templates.step_template_help'))
                    ->default('none')
                    ->disabled(fn ($record) => $record && $record->is_locked)
                    ->afterStateUpdated(function ($state, $set, $get) {
                        if ($state && $state !== 'none') {
                            $template = StepTemplateService::getTemplate($state);
                            if ($template) {
                                $set('validation', $template['validation']);
                                $set('data_bindings', $template['data_bindings']);
                                $set('form_definition', $template['form_definition'] ?? []);

                                // Suggest system key if not already set
                                if (! $get('system_key')) {
                                    $suggestedKeys = StepTemplateService::getSuggestedSystemKeys($state);
                                    if (! empty($suggestedKeys)) {
                                        $set('system_key', $suggestedKeys[0]);
                                    }
                                }
                            }
                        } else {
                            $set('validation', []);
                            $set('data_bindings', []);
                            $set('form_definition', []);
                        }
                    })
                    ->live(),

                // Hidden fields that are auto-populated based on step template selection
                Hidden::make('type')
                    ->default('approval'),

                Hidden::make('form_definition')
                    ->default([]),

                Hidden::make('validation')
                    ->default([]),

                Hidden::make('data_bindings')
                    ->default([]),

                Hidden::make('handler'),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('label')
            ->columns([
                TextColumn::make('position')
                    ->label(__('workflow.templates.step_templates.position'))
                    ->sortable(),

                TextColumn::make('label')
                    ->label(__('workflow.templates.step_templates.name'))
                    ->searchable(),

                BadgeColumn::make('system_key')
                    ->label(__('workflow.templates.step_templates.system_key'))
                    ->colors([
                        'danger' => function ($state, $record) {
                            // Red for required system keys
                            $workflowTemplate = $this->getOwnerRecord();

                            return StepTemplateService::isSystemKeyRequired($state, $workflowTemplate->subject_type);
                        },
                        'primary' => fn ($state) => $state === 'launched',
                        'secondary' => fn ($state) => $state !== null,
                    ])
                    ->placeholder(__('workflow.templates.step_templates.system_key_none'))
                    ->tooltip(function ($state, $record) {
                        if (! $state) {
                            return __('workflow.templates.step_templates.no_key_assigned');
                        }

                        $workflowTemplate = $this->getOwnerRecord();
                        $isRequired = StepTemplateService::isSystemKeyRequired($state, $workflowTemplate->subject_type);

                        return $isRequired ? __('workflow.templates.step_templates.system_key_required') : __('workflow.templates.step_templates.system_key_optional');
                    }),

                BadgeColumn::make('type')
                    ->label(__('workflow.templates.step_templates.type'))
                    ->colors([
                        'success' => 'approval',
                        'info' => 'input',
                        'warning' => 'auto',
                    ])
                    ->default('approval'),

                IconColumn::make('is_locked')
                    ->boolean()
                    ->label(__('workflow.templates.step_templates.locked')),

                TextColumn::make('formDefinition.name')
                    ->label(__('workflow.templates.step_templates.form'))
                    ->placeholder(__('workflow.templates.step_templates.none_placeholder')),

                TextColumn::make('step_template')
                    ->label(__('workflow.templates.step_templates.template'))
                    ->getStateUsing(function ($record) {
                        $templateKey = StepTemplateService::detectTemplateKey($record);

                        return StepTemplateService::getTemplateLabel($templateKey);
                    })
                    ->badge()
                    ->color(fn ($state) => $state === __('workflow.templates.step_templates.basic_step') ? 'gray' : 'primary'),
            ])
            ->filters([
                SelectFilter::make('type')
                    ->label(__('workflow.templates.step_templates.type'))
                    ->options([
                        'approval' => __('workflow.templates.step_templates.type_approval'),
                        'input' => __('workflow.templates.step_templates.type_input'),
                        'auto' => __('workflow.templates.step_templates.type_auto'),
                    ]),

                TernaryFilter::make('is_locked')
                    ->label(__('workflow.templates.step_templates.locked')),
            ])
            ->headerActions([
                CreateAction::make()
                    ->visible(fn () => $this->getOwnerRecord()->isDraft())
                    ->mutateDataUsing(function (array $data) {
                        $data['workflow_template_id'] = $this->getOwnerRecord()->id;

                        // Handle step template selection
                        if (isset($data['step_template_key']) && $data['step_template_key'] !== 'none') {
                            $template = StepTemplateService::getTemplate($data['step_template_key']);
                            if ($template) {
                                $data['validation'] = $template['validation'];
                                $data['data_bindings'] = $template['data_bindings'];
                                $data['form_definition'] = $template['form_definition'] ?? [];
                            }
                        }

                        // Remove the temporary field
                        unset($data['step_template_key']);

                        // Ensure type defaults to approval
                        if (! isset($data['type']) || empty($data['type'])) {
                            $data['type'] = 'approval';
                        }

                        return $data;
                    }),
            ])
            ->recordActions([
                EditAction::make()
                    ->visible(fn ($record) => ! $record->is_locked)
                    ->fillForm(function ($record) {
                        $data = $record->toArray();

                        // Try to determine which template this step matches
                        $data['step_template_key'] = StepTemplateService::detectTemplateKey($record);

                        return $data;
                    })
                    ->mutateDataUsing(function (array $data) {
                        // Handle step template selection for updates
                        if (isset($data['step_template_key']) && $data['step_template_key'] !== 'none') {
                            $template = StepTemplateService::getTemplate($data['step_template_key']);
                            if ($template) {
                                $data['validation'] = $template['validation'];
                                $data['data_bindings'] = $template['data_bindings'];
                                $data['form_definition'] = $template['form_definition'] ?? [];
                            }
                        }

                        // Remove the temporary field
                        unset($data['step_template_key']);

                        // Ensure type defaults to approval
                        if (! isset($data['type']) || empty($data['type'])) {
                            $data['type'] = 'approval';
                        }

                        return $data;
                    }),

                DeleteAction::make()
                    ->visible(fn ($record) => ! $record->is_locked && ! $record->system_key)
                    ->before(function ($record) {
                        if ($record->system_key) {
                            throw new Exception('Cannot delete system steps');
                        }
                    }),
            ])
            ->toolbarActions([
                // Tables\Actions\BulkActionGroup::make([
                //     Tables\Actions\DeleteBulkAction::make()
                //         ->visible(fn ($records) => $records->every(fn ($record) => ! $record->is_locked && ! $record->system_key)),
                // ]),
            ])
            ->reorderable('position')
            ->defaultSort('position');
    }
}
