<?php

namespace App\Filament\RealEstate\Resources;

use App\Enums\CrmModule;
use App\Filament\RealEstate\Resources\ReceiptResource\Pages;
use App\Models\Receipt;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class ReceiptResource extends Resource
{
    protected static ?string $model = Receipt::class;

    protected static ?string $navigationIcon = 'heroicon-o-receipt-percent';

    protected static ?string $navigationGroup = 'Finance';

    protected static ?int $navigationSort = 2;

    public static function canViewAny(): bool
    {
        return auth()->user()?->can('re_view_finance') ?? false;
    }

    public static function canCreate(): bool
    {
        return auth()->user()?->can('re_manage_finance') ?? false;
    }

    public static function canEdit($record): bool
    {
        return auth()->user()?->can('re_manage_finance') ?? false;
    }

    public static function canDelete($record): bool
    {
        return auth()->user()?->can('re_manage_finance') ?? false;
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->with(['invoice', 'installment', 'client'])
            ->where('module', CrmModule::RealEstate);
    }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make()->schema([
                Forms\Components\TextInput::make('receipt_number')->required()->unique(ignoreRecord: true)->maxLength(255),
                Forms\Components\Select::make('client_id')
                    ->relationship(
                        'client',
                        'name',
                        fn (Builder $query) => $query->whereIn('module', [CrmModule::RealEstate, CrmModule::Shared])
                    )
                    ->searchable()
                    ->preload()
                    ->required(),
                Forms\Components\Select::make('invoice_id')
                    ->relationship(
                        'invoice',
                        'invoice_number',
                        fn (Builder $query) => $query->where('module', CrmModule::RealEstate)
                    )
                    ->searchable()
                    ->preload(),
                Forms\Components\Select::make('installment_id')
                    ->relationship('installment', 'id')
                    ->getOptionLabelFromRecordUsing(fn ($record) => "Installment #{$record->id} — PKR {$record->amount}")
                    ->searchable()
                    ->preload(),
                Forms\Components\TextInput::make('amount')
                    ->numeric()
                    ->prefix('PKR')
                    ->required(),
                Forms\Components\Select::make('payment_method')
                    ->options([
                        'cash' => 'Cash',
                        'bank_transfer' => 'Bank Transfer',
                        'cheque' => 'Cheque',
                        'card' => 'Card',
                    ])
                    ->required()
                    ->default('cash'),
                Forms\Components\DateTimePicker::make('paid_at')->required()->default(now()),
                Forms\Components\Hidden::make('module')->default(CrmModule::RealEstate->value),
            ])->columns(2),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('receipt_number')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('client.name')->label('Client')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('invoice.invoice_number')->label('Invoice')->toggleable(),
                Tables\Columns\TextColumn::make('amount')->money('PKR')->sortable(),
                Tables\Columns\TextColumn::make('payment_method')->badge()->toggleable(),
                Tables\Columns\TextColumn::make('paid_at')->dateTime()->sortable(),
                Tables\Columns\TextColumn::make('created_at')->dateTime()->sortable()->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('payment_method')
                    ->options([
                        'cash' => 'Cash',
                        'bank_transfer' => 'Bank Transfer',
                        'cheque' => 'Cheque',
                        'card' => 'Card',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListReceipts::route('/'),
            'create' => Pages\CreateReceipt::route('/create'),
            'edit' => Pages\EditReceipt::route('/{record}/edit'),
        ];
    }
}
