<?php

namespace App\Filament\Admin\Resources\OrderProducts\Schemas;

use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Forms\Components\Hidden;
use Illuminate\Support\Facades\Http;

class OrderProductForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([

                /*
                |--------------------------------------------------------------------------
                | ORDER ACTIVE
                |--------------------------------------------------------------------------
                */
                Section::make('Order Active')
                    ->schema([
                        Toggle::make('is_paid')
                            ->label('Paid')
                            ->required(),
                    ])
                    ->columnSpanFull(),

                /*
                |--------------------------------------------------------------------------
                | ORDER SETTINGS
                |--------------------------------------------------------------------------
                */
                Section::make('Order Settings')
                    ->description('Configure payment method, quantity, and price.')
                    ->extraAttributes([
                        'style' =>
                            'background-color:#ffffff;padding:15px;border-radius:8px;border:1px solid #e5e7eb;box-shadow:0 1px 3px rgba(0,0,0,0.05);',
                    ])
                    ->schema([

                        Select::make('pm_type')
                            ->label('Payment Method')
                            ->options([
                                'wallet' => 'Wallet',
                            ])
                            ->required(),

                        TextInput::make('quantity')
                            ->label('Quantity')
                            ->numeric()
                            ->required()
                            ->reactive()
                            ->afterStateUpdated(function ($state, $set, $get) {
                                $price = $get('product_price') ?? 0;
                                $set('total_price', $state * $price);
                            }),

                        TextInput::make('total_price')
                            ->label('Total Price')
                            ->numeric()
                            ->required()
                            ->disabled(),

                        Select::make('status')
                            ->label('Status')
                            ->options([
                                'pending' => 'Pending',
                                'completed' => 'Completed',
                                'failed' => 'Failed',
                            ])
                            ->required(),

                    ])
                    ->columns(2)
                    ->columnSpanFull(),

                /*
                |--------------------------------------------------------------------------
                | RELATIONS
                |--------------------------------------------------------------------------
                */
                Section::make('Relations')
                    ->description('Product, user and coupon selection.')
                    ->extraAttributes([
                        'style' =>
                            'background-color:#ffffff;padding:12px;border-radius:6px;border:1px solid #e5e7eb;',
                    ])
                    ->schema([

                        /*
                        |--------------------------------------------------------------------------
                        | PRODUCT
                        |--------------------------------------------------------------------------
                        */
                        Select::make('product_id')
                            ->label('Product')
                            ->relationship('product', 'en_name')
                            ->searchable()
                            ->preload()
                            ->native(false)
                            ->required()
                            ->afterStateUpdated(function ($state, $set, $get) {
                                if (! $state) {
                                    $set('product_price', null);
                                    return;
                                }

                                $product = \App\Models\Product::find($state);

                                $set('product_price', $product->price ?? 0);

                                $quantity = $get('quantity') ?? 1;
                                $set('total_price', $quantity * ($product->price ?? 0));
                            }),

                        /*
                        |--------------------------------------------------------------------------
                        | PRODUCT PRICE (Preview Only)
                        |--------------------------------------------------------------------------
                        */
                        TextInput::make('product_price')
                            ->label('Product Price')
                            ->disabled(),

                        /*
                        |--------------------------------------------------------------------------
                        | USER
                        |--------------------------------------------------------------------------
                        */
                        Select::make('user_id')
                            ->label('User')
                            ->relationship('user', 'name')
                            ->searchable()
                            ->preload()
                            ->native(false)
                            ->required(),

                        /*
                        |--------------------------------------------------------------------------
                        | COUPON
                        |--------------------------------------------------------------------------
                        */
                        TextInput::make('coupon_code')
                            ->label('Coupon Code')
                            ->placeholder('Enter coupon code')
                            ->live(onBlur: true)
                            ->afterStateUpdated(function ($state, $set) {

                                if (! $state) {
                                    $set('coupon_id', null);
                                    return;
                                }

                                $response = Http::post(url('/api/coupon/validate'), [
                                    'coupon_code' => $state,
                                ]);

                                if ($response->failed()) {
                                    $set('coupon_id', null);

                                    $json = $response->json() ?? [];

                                    \Filament\Notifications\Notification::make()
                                        ->title('Invalid Coupon')
                                        ->body($json['message'] ?? 'Coupon validation failed.')
                                        ->danger()
                                        ->send();

                                    return;
                                }

                                $data = $response->json();
                                $set('coupon_id', $data['id']);

                                \Filament\Notifications\Notification::make()
                                    ->title('Coupon applied!')
                                    ->body($data['message'])
                                    ->success()
                                    ->send();
                            }),

                        Hidden::make('coupon_id'),

                    ])
                    ->columns(3)
                    ->columnSpanFull(),
            ]);
    }
}
