<?php

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

use App\Filament\Agent\Resources\InquiryResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;

/**
 * List Inquiries Page for Agent Panel
 * 
 * This page displays all insurance inquiries belonging to the logged-in agent.
 * Agents can view their own inquiries, filter them, and access detailed views.
 * Creation of new inquiries is done via API, not through this panel.
 */
class ListInquiries extends ListRecords
{
    /**
     * The resource class associated with this page
     */
    protected static string $resource = InquiryResource::class;

    /**
     * Header actions available to agents
     * 
     * Agents have limited actions - they cannot create inquiries through the panel
     * as inquiries are created via API integration with their websites.
     */
    protected function getHeaderActions(): array
    {
        return [
            // Action: Refresh the table
            Actions\Action::make('refresh')
                ->label('Refresh')
                ->icon('heroicon-o-arrow-path')
                ->color('gray')
                ->tooltip('Refresh the table data')
                ->action(fn () => $this->refreshTableData())
                ->outlined(),
            
            // Action: Export inquiries (if needed)
            Actions\Action::make('export')
                ->label('Export to CSV')
                ->icon('heroicon-o-arrow-down-tray')
                ->color('success')
                ->tooltip('Export your inquiries to CSV format')
                ->action(function () {
                    $this->notify('success', 'Export feature will be implemented soon.');
                })
                ->requiresConfirmation()
                ->modalHeading('Export Inquiries')
                ->modalDescription('This will export your visible inquiries to a CSV file.')
                ->modalSubmitActionLabel('Export')
                ->modalCancelActionLabel('Cancel'),
            
            // Action: View API documentation
            Actions\Action::make('apiDocs')
                ->label('API Docs')
                ->icon('heroicon-o-code-bracket')
                ->color('info')
                ->url(route('api.documentation'))
                ->openUrlInNewTab()
                ->tooltip('View API documentation for integration'),
        ];
    }

    /**
     * Get the table query scoped to the agent's inquiries
     * 
     * Automatically filters inquiries to only show those belonging to
     * the currently logged-in agent.
     */
    protected function getTableQuery(): Builder
    {
        return parent::getTableQuery()
            ->where('agent_id', auth()->id()) // Scope to agent's own inquiries
            ->with(['agent']) // Eager load agent relationship
            ->orderBy('inquired_at', 'desc'); // Show newest first
    }

    /**
     * Get the table query for export purposes
     * 
     * Includes additional relationships needed for exporting.
     */
    protected function getTableQueryForExport(): Builder
    {
        return $this->getTableQuery()
            ->with([
                'people', // Include insured persons
                'city', // Include city information
            ]);
    }

    /**
     * Refresh table data and notify the agent
     */
    protected function refreshTableData(): void
    {
        $this->resetTable();
        $this->notify('success', 'Table refreshed successfully.');
    }

    /**
     * Get empty state information when no inquiries exist
     */
    protected function getEmptyStateIcon(): string
    {
        return 'heroicon-o-document-text';
    }

    protected function getEmptyStateHeading(): string
    {
        return 'No inquiries yet';
    }

    protected function getEmptyStateDescription(): string
    {
        return 'Your insurance inquiries will appear here once submitted via your website integration.';
    }

    protected function getEmptyStateActions(): array
    {
        return [
            // Action to view integration guide
            Actions\Action::make('viewIntegrationGuide')
                ->label('View Integration Guide')
                ->icon('heroicon-o-book-open')
                ->url(route('integration.guide'))
                ->openUrlInNewTab()
                ->button(),
            
            // Action to contact support
            Actions\Action::make('contactSupport')
                ->label('Contact Support')
                ->icon('heroicon-o-lifebuoy')
                ->url('mailto:support@insuranceplatform.com')
                ->button()
                ->color('gray'),
        ];
    }

    /**
     * Get table records per page options
     */
    protected function getTableRecordsPerPageSelectOptions(): array
    {
        return [10, 25, 50, 100];
    }

    /**
     * Get default table records per page
     */
    protected function getDefaultTableRecordsPerPage(): int
    {
        return 25;
    }

    /**
     * Get page heading
     */
    public function getHeading(): string
    {
        return 'My Insurance Inquiries';
    }

    /**
     * Get page subheading
     */
    public function getSubheading(): ?string
    {
        $count = $this->getTableQuery()->count();
        return "You have {$count} insurance inquiry" . ($count !== 1 ? 'ies' : '') . " in total.";
    }

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

    /**
     * Get footer widgets for additional information
     */
    protected function getFooterWidgets(): array
    {
        return [
            // Widget showing inquiry statistics
            InquiryResource\Widgets\InquiryStats::class,
        ];
    }

    /**
     * Get view data for the page
     */
    public function getViewData(): array
    {
        return [
            'total_inquiries' => $this->getTableQuery()->count(),
            'pending_inquiries' => $this->getTableQuery()->where('status', 'pending')->count(),
            'approved_inquiries' => $this->getTableQuery()->where('status', 'approved')->count(),
            'recent_inquiries' => $this->getTableQuery()->where('inquired_at', '>=', now()->subDays(7))->count(),
        ];
    }

    /**
     * Get additional table actions for specific rows
     * 
     * These actions appear as a dropdown on each table row.
     */
    protected function getTableActions(): array
    {
        return [
            // Quick status update (if allowed)
            \Filament\Tables\Actions\Action::make('quickStatus')
                ->label('Update Status')
                ->icon('heroicon-o-arrow-path')
                ->form([
                    \Filament\Forms\Components\Select::make('status')
                        ->options([
                            'pending' => 'Pending',
                            'under_review' => 'Under Review',
                        ])
                        ->required(),
                ])
                ->action(function ($record, $data) {
                    if (in_array($record->status, ['pending', 'under_review'])) {
                        $record->status = $data['status'];
                        $record->save();
                        $this->notify('success', 'Status updated successfully.');
                    }
                })
                ->visible(fn ($record) => in_array($record->status, ['pending', 'under_review'])),
            
            // Duplicate inquiry (create similar)
            \Filament\Tables\Actions\Action::make('duplicate')
                ->label('Duplicate')
                ->icon('heroicon-o-document-duplicate')
                ->action(function ($record) {
                    // Logic to duplicate inquiry
                    $this->notify('info', 'Duplicate feature coming soon.');
                })
                ->requiresConfirmation(),
        ];
    }

    /**
     * Get additional table bulk actions
     */
    protected function getTableBulkActions(): array
    {
        return [
            // Bulk update status (for pending inquiries only)
            \Filament\Tables\Actions\BulkAction::make('bulkStatusUpdate')
                ->label('Update Status')
                ->icon('heroicon-o-arrow-path')
                ->form([
                    \Filament\Forms\Components\Select::make('status')
                        ->label('New Status')
                        ->options([
                            'under_review' => 'Mark as Under Review',
                        ])
                        ->required(),
                ])
                ->action(function ($records, $data) {
                    $updated = 0;
                    foreach ($records as $record) {
                        if ($record->status === 'pending') {
                            $record->status = $data['status'];
                            $record->save();
                            $updated++;
                        }
                    }
                    $this->notify('success', "Updated {$updated} inquiry" . ($updated !== 1 ? 'ies' : '') . ".");
                })
                ->deselectRecordsAfterCompletion(),
            
            // Bulk export selected
            \Filament\Tables\Actions\BulkAction::make('bulkExport')
                ->label('Export Selected')
                ->icon('heroicon-o-arrow-down-tray')
                ->action(function ($records) {
                    $this->notify('info', 'Exporting ' . count($records) . ' inquiries...');
                })
                ->requiresConfirmation(),
        ];
    }

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

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