<?php

namespace App\Filament\Admin\Resources\WorkflowTemplates;

use App\Filament\Admin\Resources\WorkflowTemplates\Pages\CreateWorkflowTemplate;
use App\Filament\Admin\Resources\WorkflowTemplates\Pages\EditWorkflowTemplate;
use App\Filament\Admin\Resources\WorkflowTemplates\Pages\ListWorkflowTemplates;
use App\Filament\Admin\Resources\WorkflowTemplates\RelationManagers\StepTemplatesRelationManager;
use App\Workflows\Models\WorkflowTemplate;
use App\Workflows\Services\TemplateCloner;
use App\Workflows\Services\TemplatePublisher;
use Exception;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
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\Builder;

class WorkflowTemplateResource extends Resource
{
    protected static ?string $model = WorkflowTemplate::class;

    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-cog-6-tooth';

    protected static ?int $navigationSort = 10;

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

                Select::make('subject_type')
                    ->label(__('workflow.templates.subject_type'))
                    ->helperText(__('workflow.templates.subject_type_help'))
                    ->placeholder(__('workflow.templates.subject_type_placeholder'))
                    ->options(config('workflows.models', []))
                    ->required()
                    ->disabled(fn ($record) => $record && ! $record->isDraft()),

                Toggle::make('is_active')
                    ->label(__('workflow.templates.is_active'))
                    ->helperText(__('workflow.templates.is_active_help'))
                    ->disabled(fn ($record) => $record && ! $record->isDraft()),

                Placeholder::make('status')
                    ->label(__('workflow.templates.status'))
                    ->content(fn ($record) => $record ? ucfirst(__('workflow.templates.status_'.$record->status)) : __('workflow.templates.draft'))
                    ->visible(fn ($record) => $record !== null),

                Placeholder::make('version')
                    ->label(__('workflow.templates.version'))
                    ->content(fn ($record) => $record ? $record->version : 1)
                    ->visible(fn ($record) => $record !== null),

                Placeholder::make('published_at')
                    ->label(__('workflow.templates.published_at'))
                    ->content(fn ($record) => $record?->published_at?->format('M j, Y g:i A') ?? __('workflow.templates.not_published'))
                    ->visible(fn ($record) => $record !== null),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')
                    ->label(__('workflow.templates.table_name'))
                    ->searchable()
                    ->sortable(),

                BadgeColumn::make('status')
                    ->label(__('workflow.templates.table_status'))
                    ->colors([
                        'secondary' => 'draft',
                        'success' => 'published',
                        'warning' => 'archived',
                    ])
                    ->sortable(),

                TextColumn::make('version')
                    ->label(__('workflow.templates.version'))
                    ->sortable(),

                TextColumn::make('subject_type')
                    ->label(__('workflow.templates.table_subject_type'))
                    ->formatStateUsing(fn ($state) => class_basename($state))
                    ->searchable(),

                IconColumn::make('is_active')
                    ->label(__('workflow.templates.table_active'))
                    ->boolean()
                    ->sortable(),

                TextColumn::make('published_at')
                    ->label(__('workflow.templates.published_at'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('created_at')
                    ->label(__('workflow.templates.table_created'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('workflow.templates.filter_status'))
                    ->options([
                        'draft' => __('workflow.templates.status_draft'),
                        'published' => __('workflow.templates.status_published'),
                        'archived' => __('workflow.templates.status_archived'),
                    ]),

                TernaryFilter::make('is_active')
                    ->label(__('workflow.templates.filter_active')),
            ])
            ->recordActions([
                Action::make('publish')
                    ->label(__('workflow.templates.actions.publish'))
                    ->icon('heroicon-o-rocket-launch')
                    ->color('success')
                    ->visible(fn ($record) => $record->isDraft())
                    ->action(function ($record) {
                        try {
                            app(TemplatePublisher::class)->publish($record);
                            Notification::make()
                                ->title(__('workflow.templates.published'))
                                ->success()
                                ->send();
                        } catch (Exception $e) {
                            Notification::make()
                                ->title(__('workflow.templates.publish_failed'))
                                ->body($e->getMessage())
                                ->danger()
                                ->send();
                        }
                    })
                    ->requiresConfirmation(),

                Action::make('clone')
                    ->label(__('workflow.templates.actions.clone'))
                    ->icon('heroicon-o-document-duplicate')
                    ->color('secondary')
                    ->visible(fn ($record) => $record->isPublished())
                    ->action(function ($record) {
                        $newTemplate = app(TemplateCloner::class)->cloneToDraft($record);
                        Notification::make()
                            ->title(__('workflow.templates.cloned'))
                            ->body(__('workflow.templates.cloned_body', ['name' => $newTemplate->name]))
                            ->success()
                            ->send();
                    }),

                EditAction::make()
                    ->visible(fn ($record) => $record->isDraft()),

                ViewAction::make(),
            ])
            ->toolbarActions([
                // Tables\Actions\BulkActionGroup::make([
                //     Tables\Actions\DeleteBulkAction::make()
                //         ->visible(fn ($records) => $records->every(fn ($record) => $record->isDraft())),
                // ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            StepTemplatesRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListWorkflowTemplates::route('/'),
            'create' => CreateWorkflowTemplate::route('/create'),
            'edit' => EditWorkflowTemplate::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery();
    }

    public static function getNavigationGroup(): ?string
    {
        return __('common.navigation.group.management');
    }

    public static function getNavigationLabel(): string
    {
        return __('workflow.templates.navigation_label');
    }

    public static function getModelLabel(): string
    {
        return __('workflow.templates.singular_label');
    }

    public static function getPluralModelLabel(): string
    {
        return __('workflow.templates.plural_label');
    }
}
