<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PosSaleResource\Pages;
use App\Models\PosSale;
use App\Models\PosTerminal;
use App\Models\User;
use Filament\Actions;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class PosSaleResource extends Resource
{
    protected static ?string $model = PosSale::class;

    protected static ?string $recordTitleAttribute = 'receipt_number';

    public static function getNavigationIcon(): string { return 'heroicon-o-receipt-percent'; }
    public static function getNavigationGroup(): string { return 'POS'; }
    public static function getNavigationSort(): int { return 2; }
    public static function getNavigationLabel(): string { return 'POS Sales'; }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make('Sale')
                ->schema([
                    Select::make('pos_terminal_id')
                        ->label('POS System')
                        ->options(fn () => PosTerminal::where('status', 'active')->orderBy('name')->pluck('name', 'id'))
                        ->required()
                        ->searchable()
                        ->preload(),
                    Select::make('agent_id')
                        ->label('Agent')
                        ->options(fn () => User::role('agent')->orderBy('name')->pluck('name', 'id'))
                        ->searchable()
                        ->preload(),
                    Select::make('customer_user_id')
                        ->label('Customer')
                        ->options(fn () => User::query()->orderBy('username')->pluck('username', 'id'))
                        ->required()
                        ->searchable()
                        ->preload(),
                    TextInput::make('amount')->numeric()->prefix('$')->step(0.01)->required()->minValue(1),
                    TextInput::make('tendered_amount')->numeric()->prefix('$')->step(0.01),
                    Textarea::make('notes')->rows(3)->columnSpanFull(),
                ])
                ->columns(2),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('receipt_number')->searchable()->copyable()->sortable(),
                Tables\Columns\TextColumn::make('terminal.code')->label('POS')->searchable(),
                Tables\Columns\TextColumn::make('agent.name')->label('Agent')->searchable(),
                Tables\Columns\TextColumn::make('customer.username')->label('Customer')->searchable(),
                Tables\Columns\TextColumn::make('amount')->money('USD')->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->color(fn ($state) => match ($state) {
                        'completed' => 'success',
                        'voided' => 'danger',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('sold_at')->dateTime()->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options(['completed' => 'Completed', 'voided' => 'Voided']),
                Tables\Filters\SelectFilter::make('pos_terminal_id')
                    ->label('POS System')
                    ->relationship('terminal', 'name'),
                Tables\Filters\SelectFilter::make('agent_id')
                    ->label('Agent')
                    ->relationship('agent', 'name', fn (Builder $query): Builder => $query->role('agent')),
            ])
            ->recordActions([
                Actions\Action::make('print')
                    ->label('Print')
                    ->icon('heroicon-o-printer')
                    ->url(fn (PosSale $record): string => route('pos.receipts.print', $record))
                    ->openUrlInNewTab(),
                Actions\ViewAction::make(),
            ])
            ->toolbarActions([
                Actions\CreateAction::make(),
            ])
            ->defaultSort('sold_at', 'desc');
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPosSales::route('/'),
            'create' => Pages\CreatePosSale::route('/create'),
            'view' => Pages\ViewPosSale::route('/{record}'),
        ];
    }
}
