<?php

namespace App\Filament\Resources\Panel;

use App\Filament\Resources\Panel\SaleResource\Pages;
use App\Filament\Resources\Panel\SaleResource\RelationManagers;
use App\Models\Product;
use App\Models\Sale;
use Carbon\Carbon;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Auth;

class SaleResource extends Resource
{
    protected static ?string $model = Sale::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static ?int $navigationSort = 12;

    protected static ?string $navigationGroup = 'العمل اليومي';

    public static function getModelLabel(): string
    {
        return __('crud.sales.itemTitle');
    }

    public static function getPluralModelLabel(): string
    {
        return __('crud.sales.collectionTitle');
    }

    public static function getNavigationLabel(): string
    {
        return __('crud.sales.collectionTitle');
    }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Section::make()->schema([
                Grid::make(['default' => 1])->schema([
                    Select::make('customer_id')
                        ->relationship('customer', 'name')
                        ->searchable()
                        ->preload()
                        ->native(false),

                    Select::make('supplier_id')
                        ->relationship('supplier', 'name')
                        ->searchable()
                        ->preload()
                        ->native(false),

                    TextInput::make('tot')
                        ->nullable()
                        ->numeric()
                        ->step(1),

                    DatePicker::make('date')
                        ->rules(['date'])
                        ->default(Carbon::today())
                        ->required()
                        ->native(false),

                    RichEditor::make('notes')
                        ->nullable()
                        ->string()
                        ->fileAttachmentsVisibility('public'),

                    Select::make('land_id')
                        ->relationship('lands', 'name')
                        ->searchable()
                        ->preload()
                        ->multiple()
                        ->native(false),

                    Select::make('user_id')
                        ->required()
                        ->default(Auth::user()->id)
                        ->disabled()
                        ->relationship('user', 'name')
                        ->searchable()
                        ->preload()
                        ->native(false),
                ])->columns(2),

                Repeater::make('ProductSale')
                    ->relationship('ProductSale')
                    ->schema([
                        Grid::make(2)->schema([
                            Select::make('product_id')
                                ->label('المنتج')
                                ->required()
                                ->searchable()
                                ->options(Product::pluck('name', 'id'))
                                ->reactive()
                                ->afterStateUpdated(function (Set $set, $state) {
                                    $product = Product::find($state);
                                    $set('price', $product?->purch_price ?? 0);
                                }),

                            TextInput::make('quantity')
                                ->label('الكمية')
                                ->required()
                                ->numeric()
                                ->default(1)
                                ->dehydrated()
                                ->afterStateUpdated(function (Set $set, Get $get) {
                                    $quantity = (int) $get('quantity');
                                    $price = (float) $get('price');
                                    $total = $quantity * $price;
                                    $set('total', $total);
                                }),

                            TextInput::make('price')
                                ->label('السعر')
                                ->required()
                                ->numeric()
                                ->default(0)
                                ->dehydrated()
                                ->afterStateUpdated(function (Set $set, Get $get) {
                                    $quantity = (int) $get('quantity');
                                    $price = (float) $get('price');
                                    $total = $quantity * $price;
                                    $set('total', $total);
                                }),

                            TextInput::make('total')
                                ->label('الإجمالي')
                                ->required()
                                ->numeric()
                                ->readOnly(),
                        ])->columns(4),
                    ])
                    ->createItemButtonLabel('إضافة منتج')
                    ->collapsible()
                    ->live()
                    ->afterStateUpdated(function (Get $get, Set $set) {
                        // إعادة حساب الإجمالي tot بعد أي تغيير
                        $tot = collect($get('ProductSale'))->pluck('total')->sum();
                        $set('tot', $tot);
                    })
                    ->createItemButtonLabel('إضافة منتج')
                    ->collapsible()
                    ->live(onBlur: true)
                    ->afterStateUpdated(function (Get $get, Set $set) {
                        $tot = collect($get('ProductSale'))->pluck('total')->sum();
                        $set('tot', $tot);
                    })
                    ->createItemButtonLabel('إضافة منتج')
                    ->collapsible(),
            ]),
        ]);
    }

    public static function calculateTotals(Get $get, Set $set): void
    {
        $quantity = (int) $get('quantity');
        $price = (float) $get('price');
        $total = $quantity * $price;
        $set('total', $total);
    }

    public static function updateTotal(Get $get, Set $set)
    {
        $totals = collect($get('ProductSale'))->pluck('total')->sum();
        $set('tot', $totals);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->poll('60s')
            ->columns([
                TextColumn::make('customer.name')->badge()->searchable()->sortable()->toggleable(),
                TextColumn::make('supplier.name')->badge()->searchable()->sortable()->toggleable(),
                TextColumn::make('tot')->badge()->searchable()->sortable()->toggleable(),
                TextColumn::make('date')->date('D-d-M-Y')->badge()->searchable()->sortable()->toggleable(),
                TextColumn::make('notes')->limit(255),
                TextColumn::make('lands.name')->badge()->searchable()->sortable()->toggleable(),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\ViewAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->defaultSort('date', 'desc');
    }

    public static function getRelations(): array
    {
        return [RelationManagers\ProductsRelationManager::class];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListSales::route('/'),
            'create' => Pages\CreateSale::route('/create'),
            'view' => Pages\ViewSale::route('/{record}'),
            'edit' => Pages\EditSale::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->withoutGlobalScopes([
            SoftDeletingScope::class,
        ]);
    }
}
