<?php

namespace App\Filament\Agent\Resources\InquiryResource\Pages;

use App\Filament\Agent\Resources\InquiryResource;
use App\Models\Inquiry;
use Filament\Actions;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Support\Carbon;

/**
 * View Inquiry Page for Agent Panel
 * 
 * This page allows agents to view detailed information about their insurance inquiries.
 * Agents have read-only access to their own inquiries with the ability to add notes
 * and view insured persons.
 */
class ViewInquiry extends ViewRecord
{
    /**
     * The resource class associated with this page
     */
    protected static string $resource = InquiryResource::class;

    /**
     * Header actions available to agents
     * 
     * Agents have limited actions - they can view, add notes, and navigate back.
     * They cannot approve, reject, or edit most fields.
     */
    protected function getHeaderActions(): array
    {
        return [
            // Action: Back to inquiries list
            Actions\Action::make('backToList')
                ->label('Back to List')
                ->icon('heroicon-o-arrow-left')
                ->color('gray')
                ->url(static::getResource()::getUrl('index'))
                ->outlined()
                ->tooltip('Return to inquiries list'),
            
            // Action: Add a note to the inquiry
            Actions\Action::make('addNote')
                ->label('Add Note')
                ->icon('heroicon-o-chat-bubble-left')
                ->color('primary')
                ->form([
                    \Filament\Forms\Components\Textarea::make('note')
                        ->label('Your Note')
                        ->required()
                        ->maxLength(1000)
                        ->rows(3)
                        ->placeholder('Type your note here...')
                        ->helperText('This note will be visible to you and administrators'),
                ])
                ->action(function (Inquiry $record, array $data): void {
                    $currentMessage = $record->message ?? '';
                    $timestamp = Carbon::now()->format('Y-m-d H:i');
                    $newNote = "\n\n[Agent Note - {$timestamp}]: " . trim($data['note']);
                    
                    $record->message = $currentMessage . $newNote;
                    $record->save();
                    
                    $this->refreshFormData(['message']);
                    $this->notify('success', 'Note added successfully.');
                })
                ->modalHeading('Add Note to Inquiry')
                ->modalDescription('Add a note that will be attached to this inquiry.')
                ->modalSubmitActionLabel('Add Note')
                ->modalCancelActionLabel('Cancel')
                ->tooltip('Add a note to this inquiry'),
            
            // Action: Send email to customer (opens email client)
            Actions\Action::make('sendEmail')
                ->label('Email Customer')
                ->icon('heroicon-o-envelope')
                ->color('info')
                ->url(fn (Inquiry $record): string => 
                    'mailto:' . $record->email . 
                    '?subject=Regarding Your Insurance Inquiry ' . $record->reference_number
                )
                ->openUrlInNewTab()
                ->tooltip('Open email client to contact customer'),
            
            // Action: Print inquiry details
            Actions\Action::make('print')
                ->label('Print')
                ->icon('heroicon-o-printer')
                ->color('secondary')
                ->action(function () {
                    $this->js('window.print()');
                })
                ->tooltip('Print this inquiry'),
            
            // Action: View insured persons (if implemented as separate page)
            Actions\Action::make('viewPeople')
                ->label('View Insured Persons')
                ->icon('heroicon-o-user-group')
                ->url(fn (Inquiry $record): string => 
                    static::getResource()::getUrl('view', ['record' => $record]) . '#people'
                )
                ->tooltip('View insured persons for this inquiry'),
        ];
    }

    /**
     * Mutate form data before filling the form
     * 
     * Format dates and other data for better display in the read-only view.
     */
    protected function mutateFormDataBeforeFill(array $data): array
    {
        // Generate reference number if it doesn't exist
        if (empty($data['reference_number'])) {
            $data['reference_number'] = 'INQ-' . strtoupper(uniqid());
        }
        
        // Format dates for better readability
        $dateFields = ['started_at', 'ended_at', 'arrived_at', 'inquired_at', 'reviewed_at', 'local_submitted_at'];
        foreach ($dateFields as $field) {
            if (!empty($data[$field])) {
                try {
                    $data[$field . '_formatted'] = Carbon::parse($data[$field])->format('Y-m-d H:i:s');
                } catch (\Exception $e) {
                    $data[$field . '_formatted'] = $data[$field];
                }
            }
        }
        
        // Calculate insurance duration in days
        if (!empty($data['started_at']) && !empty($data['ended_at'])) {
            try {
                $start = Carbon::parse($data['started_at']);
                $end = Carbon::parse($data['ended_at']);
                $data['duration_days'] = $start->diffInDays($end) + 1;
            } catch (\Exception $e) {
                $data['duration_days'] = 'N/A';
            }
        }
        
        // Format monetary amounts
        if (!empty($data['total_premium'])) {
            $data['total_premium_formatted'] = number_format($data['total_premium'], 2) . ' CAD';
        }
        
        if (!empty($data['insurance_cover'])) {
            $data['insurance_cover_formatted'] = number_format($data['insurance_cover']) . ' CAD';
        }
        
        // Format card expiration for display
        if (!empty($data['card_expiration']) && strlen($data['card_expiration']) === 4) {
            $year = substr($data['card_expiration'], 0, 2);
            $month = substr($data['card_expiration'], 2, 2);
            $data['card_expiration_formatted'] = $month . '/' . $year;
        }
        
        // Parse and format beneficiary information
        if (!empty($data['beneficiary_born_at'])) {
            try {
                $data['beneficiary_born_at_formatted'] = Carbon::parse($data['beneficiary_born_at'])->format('Y-m-d');
                $data['beneficiary_age'] = Carbon::parse($data['beneficiary_born_at'])->age;
            } catch (\Exception $e) {
                $data['beneficiary_born_at_formatted'] = $data['beneficiary_born_at'];
                $data['beneficiary_age'] = 'N/A';
            }
        }
        
        // Format beneficiary gender
        if (isset($data['is_beneficiary_male'])) {
            $data['beneficiary_gender'] = $data['is_beneficiary_male'] ? 'Male' : 'Female';
        }
        
        // Format destination country and trip purpose
        if (!empty($data['destination_country'])) {
            $data['destination_country_formatted'] = ucwords(str_replace('_', ' ', $data['destination_country']));
        }
        
        if (!empty($data['trip_purpose'])) {
            $data['trip_purpose_formatted'] = ucfirst($data['trip_purpose']);
        }
        
        return $data;
    }

    /**
     * Get the page heading
     */
    public function getHeading(): string
    {
        $reference = $this->record->reference_number ?? 'N/A';
        return "Inquiry #{$reference}";
    }

    /**
     * Get the page subheading
     */
    public function getSubheading(): ?string
    {
        $type = $this->record->is_entry ? 'Entry to Canada' : 'Exit from Canada';
        $status = ucfirst(str_replace('_', ' ', $this->record->status));
        $date = $this->record->inquired_at?->format('M d, Y') ?? 'Unknown date';
        
        return "{$type} Insurance • Status: {$status} • Submitted: {$date}";
    }

    /**
     * Get the breadcrumbs for navigation
     */
    public function getBreadcrumbs(): array
    {
        return [
            route('filament.agent.pages.dashboard') => 'Dashboard',
            InquiryResource::getUrl('index') => 'My Inquiries',
            '' => 'View Inquiry',
        ];
    }

    /**
     * Get the form schema for the view page
     * 
     * Override to provide a read-only form layout optimized for viewing.
     */
    protected function getFormSchema(): array
    {
        // Start with the resource's form schema but make all fields disabled
        $schema = [];
        $resourceForm = (new InquiryResource())->form(new \Filament\Forms\Form());
        
        foreach ($resourceForm->getComponents() as $component) {
            if ($component instanceof \Filament\Forms\Components\Section) {
                $schema[] = $component->disabled();
            }
        }
        
        // Add a custom section for formatted/calculated fields
        $schema[] = \Filament\Forms\Components\Section::make('Calculated Information')
            ->description('Automatically calculated fields')
            ->schema([
                \Filament\Forms\Components\TextInput::make('duration_days')
                    ->label('Insurance Duration')
                    ->disabled()
                    ->suffix('days')
                    ->helperText('Total days of coverage'),
                
                \Filament\Forms\Components\TextInput::make('total_premium_formatted')
                    ->label('Total Premium')
                    ->disabled()
                    ->helperText('Formatted premium amount'),
                
                \Filament\Forms\Components\TextInput::make('insurance_cover_formatted')
                    ->label('Insurance Coverage')
                    ->disabled()
                    ->helperText('Formatted coverage amount'),
            ])
            ->columns(3)
            ->collapsible();
        
        return $schema;
    }

    /**
     * Get the view data for the page
     */
    public function getViewData(): array
    {
        return [
            'inquiry' => $this->record,
            'people_count' => $this->record->people->count(),
            'primary_person' => $this->record->people->where('is_primary', true)->first(),
            'agent' => $this->record->agent,
            'city' => $this->record->city,
        ];
    }

    /**
     * Refresh specific form data after actions
     */
    protected function refreshFormData(array $fields): void
    {
        $this->record->refresh();
        
        foreach ($fields as $field) {
            if (isset($this->form->getState()[$field])) {
                $this->form->getState()[$field] = $this->record->{$field};
            }
        }
        
        $this->form->fill();
    }

    /**
     * Get the footer widget content
     */
    protected function getFooterWidgetsContent(): ?string
    {
        return view('filament.agent.resources.inquiry-resource.pages.view-inquiry-footer', [
            'record' => $this->record,
        ])->render();
    }

    /**
     * Get notification title for actions
     */
    public function getNotificationTitle(): ?string
    {
        return 'Inquiry Updated';
    }

    /**
     * Get notification message for actions
     */
    public function getNotificationMessage(): ?string
    {
        return 'Your changes have been saved successfully.';
    }

    /**
     * Get additional relation managers for the view page
     * 
     * This allows agents to view insured persons directly on the inquiry page.
     */
    protected function getRelationManagers(): array
    {
        return [
            // People relation manager (insured persons)
            \App\Filament\Agent\Resources\InquiryResource\RelationManagers\PeopleRelationManager::class,
        ];
    }

    /**
     * Check if the agent can view this inquiry
     * 
     * Additional security check to ensure agents can only view their own inquiries.
     */
    public function mount($record): void
    {
        // First, call parent mount
        parent::mount($record);
        
        // Additional security check
        if ($this->record->agent_id !== auth()->id()) {
            abort(403, 'You are not authorized to view this inquiry.');
        }
    }

    /**
     * Get the tabs for the view page
     * 
     * Organize information into tabs for better user experience.
     */
    protected function getTabs(): array
    {
        return [
            'details' => \Filament\Resources\Pages\ViewRecord\Tab::make('Details')
                ->icon('heroicon-o-document-text')
                ->badge(fn () => $this->record->status === 'pending' ? '!' : null)
                ->badgeColor(fn () => $this->record->status === 'pending' ? 'warning' : null),
            
            'people' => \Filament\Resources\Pages\ViewRecord\Tab::make('Insured Persons')
                ->icon('heroicon-o-user-group')
                ->badge(fn () => $this->record->people->count())
                ->badgeColor('primary'),
            
            'notes' => \Filament\Resources\Pages\ViewRecord\Tab::make('Notes & Messages')
                ->icon('heroicon-o-chat-bubble-left-ellipsis')
                ->badge(fn () => !empty($this->record->message) ? count(explode('[Agent Note', $this->record->message)) - 1 : null)
                ->badgeColor('gray'),
            
            'documents' => \Filament\Resources\Pages\ViewRecord\Tab::make('Documents')
                ->icon('heroicon-o-paper-clip')
                ->badge(fn () => 0) // Placeholder for document count
                ->badgeColor('secondary'),
        ];
    }

    /**
     * Get the default active tab
     */
    protected function getDefaultActiveTab(): string
    {
        return 'details';
    }
}