<?php

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

use App\Filament\Admin\Resources\InquiryResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Str;

/**
 * Create Inquiry Page
 * 
 * This page handles the creation of new insurance inquiries in the admin panel.
 * It extends the standard CreateRecord page with custom logic for setting
 * default values, generating reference numbers, and initializing inquiry status.
 */
class CreateInquiry extends CreateRecord
{
    /**
     * The resource class associated with this page
     */
    protected static string $resource = InquiryResource::class;

    /**
     * Mutate form data before creating the record
     * 
     * This method is called before the record is created. We can use it to:
     * 1. Generate a unique reference number
     * 2. Set default values for fields
     * 3. Initialize timestamps
     * 4. Prepare any calculated fields
     * 
     * @param array $data The form data
     * @return array Mutated form data
     */
    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // Generate a unique reference number if not provided
        if (empty($data['reference_number'])) {
            $data['reference_number'] = 'INQ-' . strtoupper(Str::random(8));
        }

        // Set local submission time to current time
        $data['local_submitted_at'] = now();

        // Set inquiry date to current time if not provided
        if (empty($data['inquired_at'])) {
            $data['inquired_at'] = now();
        }

        // Initialize status as pending if not set
        if (empty($data['status'])) {
            $data['status'] = 'pending';
        }

        // Set default number of people to 1 if not specified
        if (empty($data['number_of_people'])) {
            $data['number_of_people'] = 1;
        }

        // Initialize is_deal as false if not set
        if (!isset($data['is_deal'])) {
            $data['is_deal'] = false;
        }

        // Format card expiration date if provided
        if (!empty($data['card_expiration'])) {
            // Assume format is MM/YY and convert to YYMM for storage
            $data['card_expiration'] = $this->formatCardExpiration($data['card_expiration']);
        }

        // Ensure required dates are set
        $dateFields = ['started_at', 'ended_at', 'arrived_at'];
        foreach ($dateFields as $field) {
            if (empty($data[$field])) {
                $data[$field] = now();
            }
        }

        return $data;
    }

    /**
     * Format card expiration date from MM/YY to YYMM
     * 
     * @param string $expiration The expiration date in MM/YY format
     * @return string Formatted expiration date in YYMM format
     */
    protected function formatCardExpiration(string $expiration): string
    {
        // Remove any non-numeric characters
        $clean = preg_replace('/[^0-9]/', '', $expiration);
        
        // If we have 4 digits, assume MMYY and convert to YYMM
        if (strlen($clean) === 4) {
            $month = substr($clean, 0, 2);
            $year = substr($clean, 2, 2);
            return $year . $month;
        }
        
        // Return original if we can't parse it
        return $expiration;
    }

    /**
     * Header actions available on the create page
     * 
     * These actions provide navigation and additional functionality
     * while creating a new inquiry.
     */
    protected function getHeaderActions(): array
    {
        return [
            // Action: Go 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(),
        ];
    }

    /**
     * Get the form actions for the create page
     * 
     * These actions appear at the bottom of the form.
     * We can customize the create button and add additional buttons.
     */
    protected function getFormActions(): array
    {
        return [
            // Create button with custom label and icon
            Actions\CreateAction::make()
                ->label('Create Inquiry')
                ->icon('heroicon-o-check')
                ->color('primary'),
            
            // Cancel button
            Actions\Action::make('cancel')
                ->label('Cancel')
                ->icon('heroicon-o-x-mark')
                ->color('gray')
                ->url(static::getResource()::getUrl('index'))
                ->outlined(),
            
            // Save and create another button
            Actions\Action::make('saveAndCreateAnother')
                ->label('Save & Create Another')
                ->icon('heroicon-o-plus')
                ->color('success')
                ->action('createAnother')
                ->outlined(),
        ];
    }

    /**
     * Create another record after successful creation
     * 
     * This method is called when the "Save & Create Another" button is clicked.
     * It redirects back to the create page with a fresh form.
     */
    public function createAnother(): void
    {
        // First, create the current record
        $this->create();
        
        // Then redirect to a fresh create page
        $this->redirect(static::getResource()::getUrl('create'));
    }

    /**
     * Get the redirect URL after creation
     * 
     * Determines where the user is redirected after successfully creating an inquiry.
     * 
     * @return string Redirect URL
     */
    protected function getRedirectUrl(): string
    {
        // Redirect to the view page of the newly created record
        return static::getResource()::getUrl('view', ['record' => $this->record]);
    }

    /**
     * Get the creation notification message
     * 
     * @return string Notification message
     */
    protected function getCreatedNotificationMessage(): ?string
    {
        $reference = $this->record->reference_number ?? 'new inquiry';
        return "Insurance inquiry #{$reference} has been created successfully.";
    }

    /**
     * Get the creation notification title
     * 
     * @return string Notification title
     */
    protected function getCreatedNotificationTitle(): ?string
    {
        return 'Inquiry Created';
    }

    /**
     * Get the page heading
     * 
     * @return string Page heading
     */
    public function getHeading(): string
    {
        return 'Create New Insurance Inquiry';
    }

    /**
     * Get the page subheading
     * 
     * @return string|null Page subheading
     */
    public function getSubheading(): ?string
    {
        return 'Fill in the details below to create a new insurance inquiry. All fields marked with * are required.';
    }

    /**
     * Get the breadcrumbs for the page
     * 
     * @return array Breadcrumb trail
     */
    public function getBreadcrumbs(): array
    {
        return [
            route('filament.admin.pages.dashboard') => 'Dashboard',
            InquiryResource::getUrl('index') => 'Inquiries',
            '' => 'Create New',
        ];
    }

    /**
     * Get the form schema for the create page
     * 
     * We can override the form schema here if we want a different layout
     * for the create page compared to the edit page.
     * 
     * @return array Form schema
     */
    protected function getFormSchema(): array
    {
        // Use the same form schema as the resource
        // If we need different fields for creation, we can customize here
        return parent::getFormSchema();
    }

    /**
     * Initialize form state with default values
     * 
     * This method is called when the form is first loaded.
     * We can use it to set default values for form fields.
     */
    protected function initializeForm(): void
    {
        parent::initializeForm();
        
        // Set default values for certain fields
        $this->form->fill([
            'is_entry' => true, // Default to entry insurance
            'status' => 'pending',
            'number_of_people' => 1,
            'is_deal' => false,
            'inquired_at' => now(),
            'local_submitted_at' => now(),
        ]);
    }

    /**
     * Handle record creation with additional logic
     * 
     * This method is called when the form is submitted.
     * We can add additional logic here, such as creating related records.
     * 
     * @param array $data The form data
     * @return mixed The created record
     */
    protected function handleRecordCreation(array $data): mixed
    {
        // Call parent to create the main record
        $record = parent::handleRecordCreation($data);
        
        // Additional logic after creation can go here
        // For example, create a default person record if needed
        // Or send notifications
        
        return $record;
    }

    /**
     * Get the form widget schema for the create page
     * 
     * Widgets can be added to provide additional information or functionality
     * alongside the form.
     * 
     * @return array Form widget schema
     */
    protected function getFormWidgets(): array
    {
        return [
            // Example widget: Information panel
            // \Filament\Widgets\AccountWidget::class,
        ];
    }

    /**
     * Get the footer widget schema for the create page
     * 
     * Footer widgets appear at the bottom of the page.
     * 
     * @return array Footer widget schema
     */
    protected function getFooterWidgets(): array
    {
        return [
            // Example: Statistics or helpful tips
        ];
    }
}