<?php

namespace App\Filament\Resources\StationLicenseResource\Components;

use App\Enums\LicenseStatus;
use App\Filament\Resources\StationLicenseResource;
use App\Models\StationLicense;
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;

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

        if ($record->status === LicenseStatus::PENDING_REQUIREMENTS) {
            $actions[] = Actions\EditAction::make();
            $actions[] = Actions\DeleteAction::make();
        }

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

        // Add approval action
        if ($requiredPermission && Auth::user()->can($requiredPermission)) {
            $actions[] = Actions\Action::make('approve')
                ->label(__('station_license.approve_to_next_stage'))
                ->icon('heroicon-o-check-circle')
                ->color('success')
                ->form(self::getApprovalForms($record))
                ->modalHeading(__('station_license.approve_confirm_title'))
                ->modalDescription(__('station_license.approve_confirm_message'))
                ->modalSubmitActionLabel(__('station_license.approve_to_next_stage'))
                ->action(function (array $data) use ($record) {
                    return self::handleApproval($data, $record);
                })
                ->visible($record->canApproveToNextStage());

            // Add reject action (same permission as approval)
            $actions[] = Actions\Action::make('reject')
                ->label(__('station_license.reject_license'))
                ->icon('heroicon-o-x-circle')
                ->color('danger')
                ->form([
                    Textarea::make('notes')
                        ->label(__('station_license.rejection_notes'))
                        ->required()
                        ->rows(3),
                ])
                ->visible($record->canReject())
                ->modalHeading(__('station_license.reject_confirm_title'))
                ->modalDescription(__('station_license.reject_confirm_message'))
                ->modalSubmitActionLabel(__('station_license.reject_license'))
                ->action(function (array $data) use ($record) {
                    $record->reject($data['notes']);
                    Notification::make()
                        ->title(__('station_license.rejected_successfully'))
                        ->danger()
                        ->send();

                    return redirect(StationLicenseResource::getUrl('view', ['record' => $record]));
                });

            $actions[] = Actions\Action::make('send_back')
                ->label(__('station_license.send_back'))
                ->icon('heroicon-o-arrow-left-circle')
                ->color('warning')
                ->form([
                    Textarea::make('notes')
                        ->label(__('station_license.approval_notes'))
                        ->required()
                        ->rows(3),
                ])
                ->visible($record->canSendBackToPreviousStage())
                ->modalHeading(__('station_license.send_back_confirm_title'))
                ->modalDescription(__('station_license.send_back_confirm_message'))
                ->modalSubmitActionLabel(__('station_license.send_back'))
                ->action(function (array $data) use ($record) {
                    $record->sendBackToPreviousStage($data['notes']);
                    Notification::make()
                        ->title(__('station_license.sent_back_successfully'))
                        ->warning()
                        ->send();

                    return redirect(StationLicenseResource::getUrl('view', ['record' => $record]));
                });
        }

        return $actions;
    }

    private static function getApprovalForms(StationLicense $record): array
    {
        $forms = [];

        switch ($record->status) {
            case LicenseStatus::FINAL_APPROVAL:
                $forms[] = Forms\Components\Section::make(__('station_license.ministry_license_information'))
                    ->schema([
                        Forms\Components\TextInput::make('ministry_license_number')
                            ->label(__('station_license.ministry_license_number'))
                            ->required()
                            ->maxLength(255)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('station_license.ministry_license_number_helper')),

                        Forms\Components\DatePicker::make('ministry_license_start_date')
                            ->label(__('station_license.ministry_license_start_date'))
                            ->required()
                            ->default(now())
                            ->maxDate(fn (Forms\Get $get) => $get('ministry_license_end_date')),

                        Forms\Components\DatePicker::make('ministry_license_end_date')
                            ->label(__('station_license.ministry_license_end_date'))
                            ->required()
                            ->default(now()->addYear())
                            ->minDate(fn (Forms\Get $get) => $get('ministry_license_start_date'))
                            ->after('ministry_license_start_date'),

                        Forms\Components\DatePicker::make('delegation_start_date')
                            ->label(__('station_license.delegation_start_date'))
                            ->required()
                            ->default(now())
                            ->maxDate(fn (Forms\Get $get) => $get('delegation_end_date')),

                        Forms\Components\DatePicker::make('delegation_end_date')
                            ->label(__('station_license.delegation_end_date'))
                            ->required()
                            ->default(now()->addYear())
                            ->minDate(fn (Forms\Get $get) => $get('delegation_start_date'))
                            ->after('delegation_start_date'),

                        SpatieMediaLibraryFileUpload::make('ministry_license_file')
                            ->label(__('station_license.ministry_license_file'))
                            ->customProperties([
                                'file_title' => __('well_license.ministry_license_file'),
                            ])
                            ->required()
                            ->collection('ministry_license')
                            ->visibility('private')
                            ->acceptedFileTypes(['application/pdf'])
                            ->downloadable()
                            ->maxSize(10240)
                            ->helperText(__('station_license.ministry_license_file_helper'))
                            ->columnSpanFull(),
                    ])
                    ->columns(2);
                break;
        }

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

        return $forms;
    }

    private static function handleApproval(array $data, StationLicense $record)
    {
        switch ($record->status) {
            case LicenseStatus::FINAL_APPROVAL:
                // Save ministry license information
                $record->ministry_license_number = $data['ministry_license_number'];
                $record->ministry_license_start_date = $data['ministry_license_start_date'];
                $record->ministry_license_end_date = $data['ministry_license_end_date'];
                $record->delegation_start_date = $data['delegation_start_date'];
                $record->delegation_end_date = $data['delegation_end_date'];
                $record->save();

                // Handle file upload
                if (! empty($data['ministry_license_file'])) {
                    // The file will be handled by SpatieMediaLibrary automatically
                    // when we call approveToNextStage
                }
                break;

            default:
                break;
        }

        // Approve to next stage
        if ($record->approveToNextStage($data['notes'] ?? '')) {
            Notification::make()
                ->title(__('station_license.approved_successfully'))
                ->success()
                ->send();

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

        return null;
    }

    public static function getStepPermission(LicenseStatus $status): ?string
    {
        $permissionMap = [
            LicenseStatus::PENDING_REQUIREMENTS->value => 'approve_pending_requirements_station::license',
            LicenseStatus::INITIAL_APPROVAL->value => 'approve_initial_station::license',
            LicenseStatus::FINAL_APPROVAL->value => 'approve_final_station::license',
        ];

        return $permissionMap[$status->value] ?? null;
    }

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

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