<?php

namespace App\Filament\RealEstate\Resources;

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

class LeadResource extends Resource
{
    protected static ?string $model = Lead::class;

    protected static ?string $navigationIcon = 'heroicon-o-user-plus';

    protected static ?string $navigationGroup = 'Sales';

    protected static ?int $navigationSort = 1;

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

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

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

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

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

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make()->schema([
                Forms\Components\TextInput::make('name')->required()->maxLength(255),
                Forms\Components\TextInput::make('email')->email()->maxLength(255),
                Forms\Components\TextInput::make('phone')->tel()->maxLength(20),
                Forms\Components\Select::make('status')
                    ->options(collect(LeadStatus::cases())->mapWithKeys(fn (LeadStatus $status) => [$status->value => $status->label()]))
                    ->required()
                    ->default(LeadStatus::New->value),
                Forms\Components\TextInput::make('source')->default('manual')->maxLength(255),
                Forms\Components\Select::make('client_id')
                    ->relationship(
                        'client',
                        'name',
                        fn (Builder $query) => $query->whereIn('module', [CrmModule::RealEstate, CrmModule::Shared])
                    )
                    ->searchable()
                    ->preload(),
                Forms\Components\Select::make('assigned_to')
                    ->relationship('assignedTo', 'name')
                    ->searchable()
                    ->preload(),
                Forms\Components\DateTimePicker::make('follow_up_at'),
                Forms\Components\Textarea::make('notes')->columnSpanFull(),
                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('name')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('phone')->searchable(),
                Tables\Columns\TextColumn::make('email')->searchable()->toggleable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->formatStateUsing(fn (LeadStatus $state): string => $state->label())
                    ->sortable(),
                Tables\Columns\TextColumn::make('source')->toggleable(),
                Tables\Columns\TextColumn::make('client.name')->label('Client')->sortable(),
                Tables\Columns\TextColumn::make('assignedTo.name')->label('Assigned To')->sortable(),
                Tables\Columns\TextColumn::make('follow_up_at')->dateTime()->sortable(),
                Tables\Columns\TextColumn::make('created_at')->dateTime()->sortable()->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options(collect(LeadStatus::cases())->mapWithKeys(fn (LeadStatus $status) => [$status->value => $status->label()])),
                Tables\Filters\SelectFilter::make('assigned_to')
                    ->relationship('assignedTo', '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\ListLeads::route('/'),
            'create' => Pages\CreateLead::route('/create'),
            'edit' => Pages\EditLead::route('/{record}/edit'),
        ];
    }
}
