<?php

namespace App\Filament\Resources\Sales\Schemas;

use App\Filament\Resources\Expenses\ExpenseResource;
use App\Models\Account;
use App\Models\Branch;
use App\Models\Client;
use App\Models\Discount;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Icetalker\FilamentTableRepeater\Forms\Components\TableRepeater;

class CreateSaleSchema
{
    /**
     * Create a new class instance.
     */
    public function configure(Schema $schema): Schema
    {
        return $schema
            ->components([
                Select::make('client')
                    ->default(fn () => request()->integer('client_id'))
                    ->options(Client::query()->get()->pluck('company', 'id'))
                    ->afterStateUpdated(function ($set, $get) {
                        $set('branch_id', '');
                    })
                    ->required()
                    ->live(),
                Select::make('branch_id')
                    ->relationship('branch', 'code')
                    ->options(fn ($get) => Branch::query()->where('client_id', $get('client'))->get()->pluck('code', 'id'))
                    ->required()
                    ->afterStateUpdated(function ($set, $get) {
                        $set('current_series', $this->getSeries($get));
                        $set('transactions.*.branch_id', $get('branch_id'));
                    })
                    ->live(),
                TextInput::make('current_series')
                    ->label('Series')
                    ->readOnly(),
                DatePicker::make('happened_on')->label('Date')
                    ->required()
                    ->afterStateUpdated(function ($set, $get) {
                        $set('transactions.*.happened_on', $get('happened_on'));
                    })
                    ->native(false),
                Checkbox::make('with_discount')->label('With Discount?')->default(false)->live(),

                TableRepeater::make('transactions')
                    ->relationship('transactions')
                    ->schema([
                        Select::make('account_id')->options(fn (Get $get) => $this->getAccountOptions($get)),
                        TextInput::make('description')->label('Description'),

                        TextInput::make('gross_amount')
                            ->numeric()
                            ->live(false, 500)
                            ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {
                                $this->setDefaultFormValues($get, $set, $old, $state);
                            })->default(0),

                        TextInput::make('vatable_amount')
                            ->numeric()
                            ->required(),
                        TextInput::make('vatable_amount')
                            ->numeric()
                            ->required(),

                        TextInput::make('output_tax')
                            ->numeric()
                            ->live()
                            ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {

                                $this->setDefaultFormValues($get, $set, $old, $state);
                            })->default(0),
                        TextInput::make('payable_withholding_tax')
                            ->numeric()
                            ->live()
                            ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {
                                $this->setDefaultFormValues($get, $set, $old, $state);
                            })->default(0),
                        TextInput::make('discount')
                            ->numeric()
                            ->disabled(fn (Get $get) => !$get('../../with_discount'))
                            ->live(),
                        Select::make('discount_type')
                            ->options(fn (Get $get) => $this->getDiscountOptions($get))
                            ->disabled(fn (Get $get) => !$get('../../with_discount'))
                            ->required(fn (Get $get) => $get('../../with_discount')),
                        TextInput::make('net_amount')->numeric()->default(0),
                        Hidden::make('branch_id')->default(fn (Get $get) => $get('../../branch_id')),
                        Hidden::make('happened_on')->default(fn (Get $get) => $get('../../happened_on')),
                        Hidden::make('with_discount')->default(fn (Get $get) => $get('../../with_discount')),
                        Hidden::make('exempt')->default(0),
                    ])
                    ->visible(fn (Get $get) => $get('branch_id') != null)
                    ->reorderable()
                    ->cloneable()
                    ->collapsible()
                    ->minItems(1)
                    ->columnSpan('full'),
            ]);
    }

    public function getSeries(Get $get): string
    {
        $branch = Branch::find($get('branch_id'));

        if ($branch) {
            $currentSeries = $branch->current_series;

            return str_pad($currentSeries + 1, 6, '0', STR_PAD_LEFT);
        }

        return '';

    }

    public function getTableComponents(Get $get): array
    {
        return [

        ];
    }

    private function setDefaultFormValues(Get $get, Set $set, ?string $old, ?string $state)
    {
        $exempt = (float) $get('exempt');
        $withHoldingTax = (float) $get('payable_withholding_tax');
        $vatableSales = $get('gross_amount');
        $vatableAmount = 0;
        if ($vatableSales) {
            $vatableAmount = $vatableSales / 1.12;
        }

        $discount = $exempt * .20;
        $outputTax = $vatableAmount * 0.12;

        // default net amount
        $netAmount = (int) $vatableSales - $get('payable_withholding_tax');

        // net amount if vatable
        if (ExpenseResource::getIsVatable($get)) {
            $netAmount = ($vatableAmount + $exempt) - $withHoldingTax;
        }

        // if discounted
        if ($get('../../with_discount')) {
            $netAmount = $netAmount - $discount;
        }

        $set('output_tax', number_format($outputTax, 2, '.', ''));
        // $set('discount', number_format($discount, 2, '.', ''));
        $set('vatable_amount', number_format($vatableAmount, 2, '.', ''));
        $set('net_amount', number_format($netAmount, 2, '.', ''));
    }

    private function getDiscountOptions(Get $get)
    {
        $query = Discount::query()->where('client_id', $get('../../client'));

        return $query->pluck('discount', 'id');
    }

    private function getAccountOptions($get)
    {
        $query = Account::query();

        $query->where([
            'client_id' => $get('../../client'),
        ]);

        // if ($get('../../branch_id')) {
        //     $query->whereHas('balances', function ($query) use ($get) {
        //         return $query->where('branch_id', $get('../../branch_id'));
        //     });
        // }

        $query->whereHas('accountType', function ($query) {
            return $query->where('type', 'Revenue');
        });

        return $query->get()->pluck('account', 'id');
    }
}
