<?php

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

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

/**
 * View Inquiry Page
 * 
 * This page displays detailed information about a specific insurance inquiry.
 * It provides a read-only view of all inquiry data and allows administrators
 * to perform actions like approving, rejecting, or editing the inquiry.
 */
class ViewInquiry extends ViewRecord
{
    /**
     * The resource class associated with this page
     */
    protected static string $resource = InquiryResource::class;

    /**
     * Header actions available on the view page
     * 
     * These actions allow administrators to manage the inquiry status
     * and perform other operations without leaving the view page.
     */
    protected function getHeaderActions(): array
    {
        return [
            // Action 1: Edit this inquiry
            Actions\EditAction::make()
                ->label('Edit Inquiry')
                ->icon('heroicon-o-pencil-square')
                ->color('primary')
                ->tooltip('Edit this insurance inquiry')
                ->modalHeading('Edit Inquiry')
                ->modalSubmitActionLabel('Save Changes')
                ->modalCancelActionLabel('Cancel'),
            
            // Action 2: Approve the inquiry
            Actions\Action::make('approve')
                ->label('Approve')
                ->icon('heroicon-o-check-circle')
                ->color('success')
                ->action(function (Inquiry $record) {
                    $record->status = 'approved';
                    $record->reviewed_at = now();
                    $record->save();
                    
                    $this->refreshFormData(['status', 'reviewed_at']);
                    $this->notify('success', 'Inquiry has been approved successfully.');
                })
                ->requiresConfirmation()
                ->modalHeading('Approve Inquiry')
                ->modalDescription('Are you sure you want to approve this insurance inquiry?')
                ->modalSubmitActionLabel('Yes, Approve')
                ->modalCancelActionLabel('Cancel')
                ->visible(fn (Inquiry $record): bool => $record->status === 'pending' || $record->status === 'under_review'),
            
            // Action 3: Reject the inquiry
            Actions\Action::make('reject')
                ->label('Reject')
                ->icon('heroicon-o-x-circle')
                ->color('danger')
                ->action(function (Inquiry $record) {
                    $record->status = 'rejected';
                    $record->reviewed_at = now();
                    $record->save();
                    
                    $this->refreshFormData(['status', 'reviewed_at']);
                    $this->notify('success', 'Inquiry has been rejected.');
                })
                ->requiresConfirmation()
                ->modalHeading('Reject Inquiry')
                ->modalDescription('Are you sure you want to reject this insurance inquiry?')
                ->modalSubmitActionLabel('Yes, Reject')
                ->modalCancelActionLabel('Cancel')
                ->visible(fn (Inquiry $record): bool => $record->status === 'pending' || $record->status === 'under_review'),
            
            // Action 4: Mark as under review
            Actions\Action::make('markUnderReview')
                ->label('Mark as Under Review')
                ->icon('heroicon-o-clock')
                ->color('warning')
                ->action(function (Inquiry $record) {
                    $record->status = 'under_review';
                    $record->save();
                    
                    $this->refreshFormData(['status']);
                    $this->notify('success', 'Inquiry has been marked as under review.');
                })
                ->requiresConfirmation()
                ->modalHeading('Mark as Under Review')
                ->modalDescription('Mark this inquiry as under review for further processing.')
                ->modalSubmitActionLabel('Confirm')
                ->modalCancelActionLabel('Cancel')
                ->visible(fn (Inquiry $record): bool => $record->status === 'pending'),
            
            // Action 5: Send email to customer
            Actions\Action::make('sendEmail')
                ->label('Send Email')
                ->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 send message to customer'),
            
            // Action 6: Print inquiry details
            Actions\Action::make('print')
                ->label('Print')
                ->icon('heroicon-o-printer')
                ->color('gray')
                ->action(function () {
                    $this->js('window.print()');
                })
                ->tooltip('Print this inquiry details'),
            
            // Action 7: Back to list
            Actions\Action::make('backToList')
                ->label('Back to List')
                ->icon('heroicon-o-arrow-left')
                ->color('secondary')
                ->url(static::getResource()::getUrl('index'))
                ->outlined(),
        ];
    }

    /**
     * Mutate form data before it fills the form
     * 
     * This method is called before the form is filled with record data.
     * We can use it to generate a reference number if one doesn't exist,
     * or format dates for better display.
     */
    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])) {
                $data[$field . '_formatted'] = Carbon::parse($data[$field])->format('Y-m-d H:i:s');
            }
        }
        
        // Calculate insurance duration in days
        if (!empty($data['started_at']) && !empty($data['ended_at'])) {
            $start = Carbon::parse($data['started_at']);
            $end = Carbon::parse($data['ended_at']);
            $data['duration_days'] = $start->diffInDays($end) + 1;
        }
        
        // Format premium amount with currency
        if (!empty($data['total_premium'])) {
            $data['total_premium_formatted'] = number_format($data['total_premium'], 2) . ' CAD';
        }
        
        // Format insurance cover amount
        if (!empty($data['insurance_cover'])) {
            $data['insurance_cover_formatted'] = number_format($data['insurance_cover']) . ' CAD';
        }
        
        return $data;
    }

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

    /**
     * Get the page subheading
     * 
     * @return string|null
     */
    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 the page
     * 
     * @return array
     */
    public function getBreadcrumbs(): array
    {
        return [
            route('filament.admin.pages.dashboard') => 'Dashboard',
            InquiryResource::getUrl('index') => 'Inquiries',
            '' => 'View Inquiry',
        ];
    }

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

    /**
     * Get the form schema for the view page
     * 
     * Override this method if you want a different form layout
     * for the view page compared to the edit page.
     */
    protected function getFormSchema(): array
    {
        // Use the same form schema as the resource, 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();
            }
        }
        
        return $schema;
    }

    /**
     * Get the view data for the page
     * 
     * @return array
     */
    public function getViewData(): array
    {
        return [
            'inquiry' => $this->record,
            'people' => $this->record->people ?? [],
            'agent' => $this->record->agent ?? null,
            'city' => $this->record->city ?? null,
        ];
    }

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

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

    /**
     * Get the notification message for successful actions
     */
    public function getNotificationMessage(): ?string
    {
        return 'The inquiry has been updated successfully.';
    }
}