<?php

namespace App\Filament\Resources\ReturnRequestResource\Pages;

use App\Filament\Resources\ReturnRequestResource;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Notifications\Notification;
use App\Services\AuditLogger;

class EditReturnRequest extends EditRecord
{
    protected static string $resource = ReturnRequestResource::class;

    protected function getHeaderActions(): array
    {
        return [
            // Approve Request
            Action::make('approve')
                ->label('Approve Request')
                ->icon('heroicon-m-check-circle')
                ->color('info')
                ->visible(fn () => $this->record->status === 'pending')
                ->requiresConfirmation()
                ->action(function () {
                    $record = $this->record;
                    $record->update(['status' => 'approved']);
                    
                    $record->order->histories()->create([
                        'user_id' => auth()->id(),
                        'action' => 'return_approved',
                        'from_status' => $record->order->status,
                        'to_status' => $record->order->status,
                        'notes' => 'Return request #' . $record->id . ' approved by administrator.',
                    ]);

                    Notification::make()
                        ->title('Request Approved')
                        ->success()
                        ->send();

                    $this->refreshFormData(['status']);
                }),

            // Receive & Process
            Action::make('receive_process')
                ->label('Receive & Process')
                ->icon('heroicon-m-arrow-path')
                ->color('warning')
                ->visible(fn () => $this->record->status === 'approved')
                ->requiresConfirmation()
                ->action(function () {
                    $record = $this->record;
                    $record->update(['status' => 'processing']);
                    
                    $record->order->histories()->create([
                        'user_id' => auth()->id(),
                        'action' => 'return_processing',
                        'from_status' => $record->order->status,
                        'to_status' => $record->order->status,
                        'notes' => 'Return request #' . $record->id . ' marked as processing (returned items received).',
                    ]);

                    Notification::make()
                        ->title('Request Marked Processing')
                        ->success()
                        ->send();

                    $this->refreshFormData(['status']);
                }),

            // Reject Request
            Action::make('reject')
                ->label('Reject Request')
                ->icon('heroicon-m-x-circle')
                ->color('danger')
                ->visible(fn () => in_array($this->record->status, ['pending', 'approved', 'processing']))
                ->form([
                    Textarea::make('rejection_reason')
                        ->label('Rejection Reason')
                        ->required()
                        ->rows(3),
                ])
                ->action(function (array $data) {
                    $record = $this->record;
                    $reason = $data['rejection_reason'];
                    $adminNotes = trim(($record->admin_notes ?? '') . "\nRejected: " . $reason);
                    
                    $record->update([
                        'status' => 'rejected',
                        'admin_notes' => $adminNotes,
                    ]);

                    $record->order->histories()->create([
                        'user_id' => auth()->id(),
                        'action' => 'return_rejected',
                        'from_status' => $record->order->status,
                        'to_status' => $record->order->status,
                        'notes' => 'Return request #' . $record->id . ' rejected. Reason: ' . $reason,
                    ]);

                    Notification::make()
                        ->title('Request Rejected')
                        ->danger()
                        ->send();

                    $this->refreshFormData(['status', 'admin_notes']);
                }),

            // Complete Request
            Action::make('complete')
                ->label('Complete & Refund')
                ->icon('heroicon-m-check-badge')
                ->color('success')
                ->visible(fn () => $this->record->status === 'processing')
                ->form(fn () => [
                    TextInput::make('refund_amount')
                        ->label('Refund Amount')
                        ->numeric()
                        ->required()
                        ->default(fn () => $this->record->exchange_order_id !== null 
                            ? $this->record->refund_amount 
                            : ($this->record->refund_amount > 0 ? $this->record->refund_amount : $this->record->items->sum(fn ($item) => $item->price * $item->quantity))),
                    Select::make('refund_method')
                        ->label('Refund Method')
                        ->options([
                            'bkash' => 'bKash',
                            'nagad' => 'Nagad',
                            'bank' => 'Bank Transfer',
                            'cash' => 'Cash/Other',
                        ])
                        ->required()
                        ->default($this->record->type === 'refund' ? 'bkash' : 'cash'),
                ])
                ->action(function (array $data) {
                    $record = $this->record;
                    $refundAmount = (float) $data['refund_amount'];
                    $refundMethod = $data['refund_method'];
                    
                    $record->update([
                        'status' => 'completed',
                        'refund_amount' => $refundAmount,
                        'refund_method' => $refundMethod,
                    ]);
                    
                    $order = $record->order;
                    $oldPaymentStatus = $order->payment_status;
                    $oldStatus = $order->status;
                    
                    if ($record->type === 'refund') {
                        $isFullRefund = $refundAmount >= (float) $order->grand_total
                            || $refundAmount >= (float) $order->subtotal
                            || $refundAmount >= ((float) $order->grand_total - (float) $order->shipping_cost);

                        if ($isFullRefund) {
                            $newPaymentStatus = 'refunded';
                            $order->status = 'returned';
                        } else {
                            $newPaymentStatus = 'partially_refunded';
                        }
                        $order->payment_status = $newPaymentStatus;
                        $order->save();
                        
                        AuditLogger::log(
                            'return_completed',
                            'Return request #' . $record->id . ' marked completed. Refund amount: ৳' . $refundAmount,
                            ['payment_status' => $oldPaymentStatus],
                            ['payment_status' => $newPaymentStatus]
                        );
                    } else {
                        // Type is 'return' (Exchange Return)
                        // Update order status to 'returned' but keep payment_status unchanged
                        $order->status = 'returned';
                        $order->save();

                        AuditLogger::log(
                            'exchange_return_completed',
                            'Exchange return request #' . $record->id . ' marked completed. Return value processed.',
                            ['status' => $oldStatus],
                            ['status' => 'returned']
                        );
                    }
                    
                    $order->histories()->create([
                        'user_id' => auth()->id(),
                        'action' => 'return_completed',
                        'from_status' => $oldStatus,
                        'to_status' => $order->status,
                        'notes' => 'Return request #' . $record->id . ' completed. Refund: ৳' . number_format($refundAmount, 2) . ' via ' . $refundMethod,
                    ]);

                    // Send database notification to admins
                    try {
                        $dbNotification = Notification::make()
                            ->title('Refund Completed')
                            ->body("Refund of BDT " . number_format($refundAmount, 2) . " via " . ucfirst($refundMethod) . " completed for Order #{$order->order_number}.")
                            ->icon('heroicon-o-currency-bangladeshi')
                            ->iconColor('success')
                            ->actions([
                                \Filament\Actions\Action::make('view')
                                    ->label('View Order')
                                    ->button()
                                    ->color('primary')
                                    ->markAsRead()
                                    ->url(\App\Filament\Resources\Orders\OrderResource::getUrl('edit', ['record' => $order])),
                            ])
                            ->toDatabase();

                        $admins = \App\Models\User::whereIn('role', ['admin', 'staff'])->get();
                        foreach ($admins as $admin) {
                            $admin->notifyNow($dbNotification);
                        }
                    } catch (\Exception $e) {
                        \Illuminate\Support\Facades\Log::error('Failed to send database notification for refund completed: ' . $e->getMessage());
                    }
                    
                    Notification::make()
                        ->title('Request Completed')
                        ->success()
                        ->send();

                    $this->refreshFormData(['status', 'refund_amount', 'refund_method']);
                }),

            DeleteAction::make(),
        ];
    }
}
