<?php

namespace App\Filament\Agent\Resources;

use App\Filament\Agent\Resources\InquiryResource\Pages;
use App\Models\Inquiry;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

/**
 * Inquiry Resource for Agent Panel
 * 
 * This resource provides a limited view of insurance inquiries for agents.
 * Agents can only view inquiries that belong to them, with restricted
 * editing capabilities compared to the admin panel.
 * 
 * Navigation: My Inquiries → Inquiries
 */
class InquiryResource extends Resource
{
    /**
     * The model associated with this resource
     */
    protected static ?string $model = Inquiry::class;

    /**
     * Navigation icon (Heroicons)
     */
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    /**
     * Navigation group for sidebar organization
     */
    protected static ?string $navigationGroup = 'My Inquiries';

    /**
     * Navigation sort order in sidebar
     */
    protected static ?int $navigationSort = 1;

    /**
     * Form configuration for view/edit (limited for agents)
     * 
     * Agents have read-only access to most fields, with limited editing
     * capabilities for specific fields like status notes.
     */
    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                // Section 1: Basic Information (Read-only for agents)
                Forms\Components\Section::make('Inquiry Information')
                    ->description('Basic details of your insurance inquiry')
                    ->schema([
                        Forms\Components\TextInput::make('reference_number')
                            ->label('Reference Number')
                            ->disabled()
                            ->dehydrated(false)
                            ->helperText('Your unique inquiry reference number'),
                        
                        Forms\Components\Select::make('status')
                            ->label('Status')
                            ->options([
                                'pending' => 'Pending',
                                'under_review' => 'Under Review',
                                'approved' => 'Approved',
                                'rejected' => 'Rejected',
                                'completed' => 'Completed',
                            ])
                            ->disabled() // Agents cannot change status
                            ->helperText('Current status of your inquiry'),
                        
                        Forms\Components\Toggle::make('is_entry')
                            ->label('Insurance Type')
                            ->disabled()
                            ->onColor('success')
                            ->offColor('warning')
                            ->onLabel('Entry to Canada')
                            ->offLabel('Exit from Canada')
                            ->helperText('Type of insurance requested'),
                    ])
                    ->columns(2),
                
                // Section 2: Coverage Details (Read-only)
                Forms\Components\Section::make('Coverage Details')
                    ->description('Insurance coverage information')
                    ->schema([
                        Forms\Components\TextInput::make('insurance_cover')
                            ->label('Coverage Amount ($)')
                            ->disabled()
                            ->suffix('CAD')
                            ->helperText('Total coverage amount'),
                        
                        Forms\Components\TextInput::make('total_premium')
                            ->label('Total Premium ($)')
                            ->disabled()
                            ->prefix('$')
                            ->helperText('Calculated premium amount'),
                        
                        Forms\Components\TextInput::make('number_of_people')
                            ->label('Number of People')
                            ->disabled()
                            ->helperText('Number of insured persons'),
                        
                        Forms\Components\DatePicker::make('started_at')
                            ->label('Start Date')
                            ->disabled()
                            ->helperText('Coverage start date'),
                        
                        Forms\Components\DatePicker::make('ended_at')
                            ->label('End Date')
                            ->disabled()
                            ->helperText('Coverage end date'),
                    ])
                    ->columns(3),
                
                // Section 3: Contact Information (Read-only)
                Forms\Components\Section::make('Contact Information')
                    ->description('Your contact details')
                    ->schema([
                        Forms\Components\TextInput::make('email')
                            ->label('Email')
                            ->disabled()
                            ->helperText('Email address on file'),
                        
                        Forms\Components\TextInput::make('phone')
                            ->label('Phone')
                            ->disabled()
                            ->helperText('Phone number on file'),
                        
                        Forms\Components\Textarea::make('address')
                            ->label('Address')
                            ->disabled()
                            ->rows(2)
                            ->helperText('Mailing address'),
                        
                        Forms\Components\TextInput::make('postal_code')
                            ->label('Postal Code')
                            ->disabled()
                            ->helperText('Canadian postal code'),
                    ])
                    ->columns(2),
                
                // Section 4: Agent Notes (Editable by agent)
                Forms\Components\Section::make('Agent Notes')
                    ->description('Add your notes or comments about this inquiry')
                    ->schema([
                        Forms\Components\Textarea::make('message')
                            ->label('Your Notes')
                            ->rows(3)
                            ->maxLength(1000)
                            ->placeholder('Add any notes or follow-up information...')
                            ->helperText('These notes are visible to you and administrators'),
                    ])
                    ->collapsible(),
            ]);
    }

    /**
     * Table configuration for agent view
     * 
     * Agents only see their own inquiries with limited columns
     * and no editing/deleting capabilities.
     */
    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn (Builder $query) => 
                $query->where('agent_id', auth()->id()) // Only show agent's own inquiries
            )
            ->columns([
                // Column 1: Reference Number
                Tables\Columns\TextColumn::make('reference_number')
                    ->label('Reference')
                    ->searchable()
                    ->sortable()
                    ->copyable()
                    ->tooltip('Your inquiry reference number'),
                
                // Column 2: Status
                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'pending' => 'warning',
                        'under_review' => 'info',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        'completed' => 'primary',
                        default => 'gray',
                    })
                    ->searchable()
                    ->sortable()
                    ->tooltip('Current status'),
                
                // Column 3: Insurance Type
                Tables\Columns\IconColumn::make('is_entry')
                    ->label('Type')
                    ->boolean()
                    ->trueIcon('heroicon-o-arrow-right')
                    ->falseIcon('heroicon-o-arrow-left')
                    ->trueColor('success')
                    ->falseColor('warning')
                    ->trueTooltip('Entry to Canada')
                    ->falseTooltip('Exit from Canada'),
                
                // Column 4: Number of People
                Tables\Columns\TextColumn::make('number_of_people')
                    ->label('People')
                    ->sortable()
                    ->alignCenter()
                    ->tooltip('Number of insured persons'),
                
                // Column 5: Total Premium
                Tables\Columns\TextColumn::make('total_premium')
                    ->label('Premium')
                    ->money('CAD')
                    ->sortable()
                    ->alignRight()
                    ->tooltip('Total premium amount'),
                
                // Column 6: Submission Date
                Tables\Columns\TextColumn::make('inquired_at')
                    ->label('Submitted')
                    ->dateTime('Y-m-d H:i')
                    ->sortable()
                    ->tooltip('Date and time of submission'),
                
                // Column 7: Last Updated
                Tables\Columns\TextColumn::make('local_submitted_at')
                    ->label('Last Updated')
                    ->dateTime('Y-m-d H:i')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->tooltip('Last update time'),
            ])
            ->filters([
                // Status filter (agents can filter their own inquiries)
                Tables\Filters\SelectFilter::make('status')
                    ->label('Filter by Status')
                    ->options([
                        'pending' => 'Pending',
                        'under_review' => 'Under Review',
                        'approved' => 'Approved',
                        'rejected' => 'Rejected',
                        'completed' => 'Completed',
                    ])
                    ->multiple()
                    ->preload(),
                
                // Insurance type filter
                Tables\Filters\SelectFilter::make('is_entry')
                    ->label('Insurance Type')
                    ->options([
                        '1' => 'Entry to Canada',
                        '0' => 'Exit from Canada',
                    ])
                    ->multiple()
                    ->preload(),
                
                // Date range filter
                Tables\Filters\Filter::make('inquired_at')
                    ->form([
                        Forms\Components\DatePicker::make('from')
                            ->label('From Date'),
                        Forms\Components\DatePicker::make('until')
                            ->label('Until Date'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['from'],
                                fn (Builder $query, $date): Builder => $query->whereDate('inquired_at', '>=', $date),
                            )
                            ->when(
                                $data['until'],
                                fn (Builder $query, $date): Builder => $query->whereDate('inquired_at', '<=', $date),
                            );
                    }),
            ])
            ->actions([
                // Agents can only view (no edit/delete)
                Tables\Actions\ViewAction::make()
                    ->label('View Details')
                    ->icon('heroicon-o-eye')
                    ->tooltip('View inquiry details'),
                
                // Optional: Allow agents to add notes via a quick action
                Tables\Actions\Action::make('addNote')
                    ->label('Add Note')
                    ->icon('heroicon-o-chat-bubble-left-ellipsis')
                    ->color('gray')
                    ->form([
                        Forms\Components\Textarea::make('note')
                            ->label('Add a Note')
                            ->required()
                            ->maxLength(500)
                            ->placeholder('Type your note here...'),
                    ])
                    ->action(function (Inquiry $record, array $data): void {
                        // Append note to existing message
                        $currentMessage = $record->message ?? '';
                        $newNote = "\n\n[Agent Note - " . now()->format('Y-m-d H:i') . "]: " . $data['note'];
                        $record->message = $currentMessage . $newNote;
                        $record->save();
                    })
                    ->tooltip('Add a note to this inquiry'),
            ])
            ->bulkActions([
                // Limited bulk actions for agents
                Tables\Actions\BulkActionGroup::make([
                    // Export to CSV (if needed)
                    Tables\Actions\BulkAction::make('export')
                        ->label('Export Selected')
                        ->icon('heroicon-o-arrow-down-tray')
                        ->action(function ($records) {
                            // Export logic here
                        })
                        ->requiresConfirmation(),
                ]),
            ])
            ->defaultSort('inquired_at', 'desc')
            ->emptyStateActions([
                // Agents cannot create inquiries through panel (done via API)
                // So no create action here
            ])
            ->emptyStateHeading('No inquiries yet')
            ->emptyStateDescription('Your submitted insurance inquiries will appear here.')
            ->emptyStateIcon('heroicon-o-document-text')
            ->deferLoading()
            ->striped();
    }

    /**
     * Define pages for agent resource
     * 
     * Agents only have list and view pages - no create/edit
     */
    public static function getPages(): array
    {
        return [
            'index' => Pages\ListInquiries::route('/'),
            'view' => Pages\ViewInquiry::route('/{record}'),
            // No create or edit pages for agents
        ];
    }

    /**
     * Get the navigation label for agents
     */
    public static function getNavigationLabel(): string
    {
        return 'My Inquiries';
    }

    /**
     * Get the plural label for agents
     */
    public static function getPluralLabel(): ?string
    {
        return 'My Insurance Inquiries';
    }

    /**
     * Get the model label for agents
     */
    public static function getModelLabel(): string
    {
        return 'Inquiry';
    }

    /**
     * Check if agent can create inquiries
     * 
     * Agents create inquiries via API, not through panel
     */
    public static function canCreate(): bool
    {
        return false;
    }

    /**
     * Check if agent can edit inquiries
     * 
     * Agents have limited editing capabilities
     */
    public static function canEdit($record): bool
    {
        // Agents can only edit their own inquiries
        return $record->agent_id === auth()->id();
    }

    /**
     * Check if agent can delete inquiries
     * 
     * Agents cannot delete inquiries
     */
    public static function canDelete($record): bool
    {
        return false;
    }

    /**
     * Check if agent can view inquiries
     * 
     * Agents can only view their own inquiries
     */
    public static function canView($record): bool
    {
        return $record->agent_id === auth()->id();
    }
}