<?php

namespace App\Filament\RealEstate\Resources;

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

class ExpenseResource extends Resource
{
    protected static ?string $model = Expense::class;

    protected static ?string $navigationIcon = 'heroicon-o-currency-dollar';

    protected static ?string $navigationGroup = 'Finance';

    protected static ?int $navigationSort = 3;

    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(['project', 'vendor', 'user'])
            ->where('module', CrmModule::RealEstate);
    }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make('Expense Details')
                ->description('What was the money spent on?')
                ->icon('heroicon-o-banknotes')
                ->schema([
                    Forms\Components\Select::make('category')
                        ->label('Expense Category')
                        ->options(\App\Enums\ExpenseCategory::options())
                        ->searchable()
                        ->required()
                        ->native(false)
                        ->placeholder('e.g. Labor, Office, Marketing'),
                    Forms\Components\TextInput::make('amount')
                        ->numeric()
                        ->prefix('PKR')
                        ->minValue(0)
                        ->required(),
                    Forms\Components\DatePicker::make('expense_date')
                        ->label('Date')
                        ->required()
                        ->default(now())
                        ->maxDate(now()),
                    Forms\Components\Select::make('payment_method')
                        ->label('Payment Method')
                        ->options([
                            'cash' => 'Cash',
                            'bank_transfer' => 'Bank Transfer',
                            'cheque' => 'Cheque',
                            'card' => 'Card',
                            'online' => 'Online / Mobile Wallet',
                        ])
                        ->default('cash')
                        ->native(false)
                        ->required(),
                    Forms\Components\TextInput::make('paid_to')
                        ->label('Paid To')
                        ->placeholder('Person or company name')
                        ->maxLength(255)
                        ->columnSpanFull(),
                    Forms\Components\Textarea::make('description')
                        ->label('Notes')
                        ->placeholder('Any extra detail about this expense')
                        ->rows(2)
                        ->columnSpanFull(),
                ])
                ->columns(2),
            Forms\Components\Section::make('Link (Optional)')
                ->description('Connect this expense to a project or vendor')
                ->icon('heroicon-o-link')
                ->schema([
                    Forms\Components\Select::make('project_id')
                        ->relationship('project', 'name')
                        ->searchable()
                        ->preload(),
                    Forms\Components\Select::make('vendor_id')
                        ->relationship('vendor', 'name')
                        ->searchable()
                        ->preload(),
                    Forms\Components\Hidden::make('module')->default(CrmModule::RealEstate->value),
                ])
                ->columns(2)
                ->collapsed(),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('category')
                    ->badge()
                    ->formatStateUsing(fn ($state) => \App\Enums\ExpenseCategory::tryFrom($state)?->label() ?? ucfirst($state))
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('amount')
                    ->money('PKR')
                    ->sortable()
                    ->summarize(\Filament\Tables\Columns\Summarizers\Sum::make()->label('Total')->money('PKR')),
                Tables\Columns\TextColumn::make('payment_method')
                    ->badge()
                    ->formatStateUsing(fn ($state) => ucwords(str_replace('_', ' ', (string) $state)))
                    ->toggleable(),
                Tables\Columns\TextColumn::make('paid_to')->label('Paid To')->searchable()->toggleable(),
                Tables\Columns\TextColumn::make('expense_date')->date()->sortable(),
                Tables\Columns\TextColumn::make('project.name')->label('Project')->sortable()->toggleable(),
                Tables\Columns\TextColumn::make('vendor.name')->label('Vendor')->sortable()->toggleable(),
                Tables\Columns\TextColumn::make('user.name')->label('Recorded By')->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_at')->dateTime()->sortable()->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('expense_date', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('category')
                    ->options(\App\Enums\ExpenseCategory::options()),
                Tables\Filters\SelectFilter::make('project_id')
                    ->relationship('project', 'name')
                    ->searchable()
                    ->preload(),
            ])
            ->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\ListExpenses::route('/'),
            'create' => Pages\CreateExpense::route('/create'),
            'edit' => Pages\EditExpense::route('/{record}/edit'),
        ];
    }
}
