<?php

namespace App\Filament\Resources\Panel;

use App\Filament\Resources\Panel\PurchaseResource\Pages;
use App\Filament\Resources\Panel\PurchaseResource\RelationManagers;
use App\Models\Product;
use App\Models\Purchase;
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\Support\Facades\Auth;

class PurchaseResource extends Resource
{
    protected static ?string $model = Purchase::class;

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

    protected static ?int $navigationSort = 11;

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

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

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

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

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

                    Select::make('customer_id')
                        // ->required()
                        ->nullable()
                        ->relationship('customer', 'name')
                        ->searchable()
                        ->preload()
                        ->native(false),

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

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

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

                    // Select::make('land_id')
                    //     // ->required()
                    //     ->nullable()
                    //     ->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('productPurchase') // ✅ Repeater allows adding multiple products dynamically
                    ->relationship('productPurchase')
                    ->schema([
                        Grid::make(2)->schema([ // Grid layout for better UI
                            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); // ✅ Auto-set price based on product
                                }),

                            TextInput::make('quantity')
                                ->label('الكمية')
                                ->required()
                                ->numeric()
                                ->default(1)
                                ->live()
                                ->afterStateUpdated(fn (Set $set, Get $get) => self::calculateTotals($get, $set))
                                ->afterStateUpdated(fn (Set $set, Get $get) => self::updateTotalImport($get, $set)),

                            TextInput::make('price')
                                ->label('السعر')
                                ->required()
                                ->numeric()
                                ->default(0)
                                ->live()
                                ->afterStateUpdated(fn (Set $set, Get $get) => self::calculateTotals($get, $set))
                                ->afterStateUpdated(fn (Set $set, Get $get) => self::updateTotalImport($get, $set)),

                            TextInput::make('total')
                                ->label('الإجمالي')
                                ->required()
                                ->numeric()
                                ->readOnly(),
                        ])->columns(4),
                    ])
                    ->createItemButtonLabel('إضافة منتج') // ✅ Custom button label
                    
                // ->orderable()
                    ->collapsible(),

            ]),
        ]);
    }
    
    public static function updateTotalImport(Get $get, Set $set)
    {
        $totals = collect($get('productPurchase'))->pluck('total')->sum();
        $set('tot_imp', $totals);
    }
        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 table(Table $table): Table
    {
        return $table
            ->poll('60s')
            ->columns([
                TextColumn::make('supplier.name')->badge()
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('customer.name')->badge()
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('tot_imp')->badge()
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('date')->date('D-d-M-Y')->badge()
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('notes')->limit(255)->badge()
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                // TextColumn::make('lands.name')->badge()
                //     ->searchable()
                //     ->sortable()
                //     ->toggleable(),

                // TextColumn::make('user.name')->badge()
                // ->searchable()
                // ->sortable()
                // ->toggleable(),
            ])
            ->filters([])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\ViewAction::make(),

            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('date', 'desc');
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPurchases::route('/'),
            'create' => Pages\CreatePurchase::route('/create'),
            'view' => Pages\ViewPurchase::route('/{record}'),
            'edit' => Pages\EditPurchase::route('/{record}/edit'),
        ];
    }
}
