<?php

namespace App\Filament\Resources\ExchangeRequestResource\Components;

use App\Filament\Resources\ExchangeRequestResource;
use App\Models\ExchangeRequest;
use Filament\Actions;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ExchangeRequestApprovalFlow
{
    public static function getApprovalFlowActions(ExchangeRequest $record): array
    {
        $actions = [];

        $requiredPermission = self::getStepPermission($record->status) ?? null;

        // log the required permission for debugging
        Log::debug('Required permission for next status: '.$requiredPermission.' for status: '.$record->status.' canApprove: '.(Auth::user()->can($requiredPermission) ? 'yes' : 'no'));

        if ($requiredPermission && Auth::user()->can($requiredPermission)) {
            $actions[] = Actions\Action::make('approve')
                ->label(__('exchange_request.approve'))
                ->icon('heroicon-o-check-circle')
                ->color('success')
                ->form(self::getApprovalForm($record))
                ->action(function (array $data) use ($record) {
                    return self::handleApproval($data, $record);
                })
                ->requiresConfirmation()
                ->modalHeading(__('exchange_request.approve_confirm_title'))
                ->modalDescription(__('exchange_request.approve_confirm_description'));

            $actions[] = Actions\Action::make('reject')
                ->label(__('exchange_request.reject'))
                ->icon('heroicon-o-x-circle')
                ->color('danger')
                ->form([
                    Textarea::make('notes')
                        ->label(__('exchange_request.rejection_notes'))
                        ->required()
                        ->rows(3)
                        ->placeholder(__('exchange_request.rejection_notes_placeholder')),
                ])
                ->action(function (array $data) use ($record) {
                    $record->reject($data['notes']);
                    Notification::make()
                        ->title(__('exchange_request.exchange_request_rejected'))
                        ->success()
                        ->send();
                })
                ->requiresConfirmation()
                ->modalHeading(__('exchange_request.reject_confirm_title'))
                ->modalDescription(__('exchange_request.reject_confirm_description'));

            // Add send back action if exchange request can be sent back
            if ($record->canSendBackToPreviousStage()) {
                $actions[] = Actions\Action::make('send_back')
                    ->label(__('exchange_request.send_back'))
                    ->icon('heroicon-o-arrow-uturn-left')
                    ->color('warning')
                    ->requiresConfirmation()
                    ->modalHeading(__('exchange_request.send_back_confirmation'))
                    ->modalDescription(__('exchange_request.send_back_description'))
                    ->form([
                        Textarea::make('notes')
                            ->label(__('exchange_request.send_back_notes'))
                            ->required()
                            ->rows(3)
                            ->helperText(__('exchange_request.send_back_notes_helper')),
                    ])
                    ->action(function (array $data) use ($record) {
                        if ($record->sendBackToPreviousStage($data['notes'])) {
                            Notification::make()
                                ->title(__('exchange_request.exchange_request_sent_back_successfully'))
                                ->success()
                                ->send();

                            return redirect(ExchangeRequestResource::getUrl('view', ['record' => $record]));
                        } else {
                            Notification::make()
                                ->title(__('exchange_request.send_back_failed'))
                                ->danger()
                                ->send();
                        }
                    });
            }
        }

        return $actions;
    }

    private static function getApprovalForm(ExchangeRequest $record): array
    {
        $forms = [];

        // For Transaction approval stage, require transaction file upload
        if ($record->status === ExchangeRequest::STATUS_TRANSACTION_APPROVED) {
            $forms[] = Forms\Components\Section::make(__('exchange_request.transaction_file_upload'))
                ->description(__('exchange_request.transaction_file_upload_description'))
                ->schema([
                    SpatieMediaLibraryFileUpload::make('transaction_file')
                        ->label(__('exchange_request.transaction_file'))
                        ->collection('transaction_file')
                        ->visibility('private')
                        ->acceptedFileTypes([
                            'application/pdf',
                            'image/jpeg',
                            'image/png',
                            'image/jpg',
                        ])
                        ->maxSize(10240) // 10MB
                        ->downloadable()
                        ->required()
                        ->helperText(__('exchange_request.transaction_file_helper')),

                    Forms\Components\DatePicker::make('transaction_date')
                        ->label(__('exchange_request.transaction_date'))
                        ->required()
                        ->maxDate(now())
                        ->default(now())
                        ->helperText(__('exchange_request.transaction_date_helper')),
                ]);
        }

        // Optional approval notes for all stages
        $forms[] = Forms\Components\Section::make(__('exchange_request.approval_notes'))
            ->description(__('exchange_request.approval_notes_description'))
            ->schema([
                Textarea::make('notes')
                    ->label(__('exchange_request.approval_notes'))
                    ->rows(3)
                    ->placeholder(__('exchange_request.approval_notes_description')),
            ]);

        return $forms;
    }

    private static function handleApproval(array $data, ExchangeRequest $record): void
    {
        // Handle transaction file upload for Transaction approval stage
        if ($record->status === ExchangeRequest::STATUS_TRANSACTION_APPROVED && isset($data['transaction_file'])) {
            // The file will be automatically attached by Filament's SpatieMediaLibraryFileUpload
        }

        // Handle transaction date for Transaction approval stage
        if ($record->status === ExchangeRequest::STATUS_TRANSACTION_APPROVED && isset($data['transaction_date'])) {
            $record->transaction_date = $data['transaction_date'];
            $record->save();
        }

        // Approve to next stage with optional notes
        $notes = $data['notes'] ?? '';
        $record->approveToNextStage($notes);

        // Show success notification
        $statusName = ExchangeRequest::getStatuses()[$record->fresh()->status] ?? $record->fresh()->status;
        Notification::make()
            ->title(__('exchange_request.exchange_request_approved'))
            ->body(__('exchange_request.status_updated_to', ['status' => $statusName]))
            ->success()
            ->send();
    }

    public static function getStepPermission(string $status): ?string
    {
        $permissionMap = [
            ExchangeRequest::STATUS_CREATED => 'approve_created_er_exchange::request',
            ExchangeRequest::STATUS_FINANCIAL_APPROVED => 'approve_financial_er_exchange::request',
            ExchangeRequest::STATUS_SHARED_SERVICES_APPROVED => 'approve_shared_services_er_exchange::request',
            ExchangeRequest::STATUS_CEO_APPROVED => 'approve_ceo_er_exchange::request',
            ExchangeRequest::STATUS_TRANSACTION_APPROVED => 'approve_final_er_exchange::request',
        ];

        return $permissionMap[$status] ?? null;
    }

    public static function canUserApproveStep(string $status): bool
    {
        $permission = self::getStepPermission($status);

        return $permission ? Auth::user()->can($permission) : false;
    }
}
