<?php

namespace App\Filament\Resources\Expenses;

use Filament\Schemas\Schema;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Tables\Columns\TextColumn;
use App\Filament\Resources\Expenses\Pages\ListExpenses;
use App\Filament\Resources\Expenses\Pages\CreateExpense;
use App\Filament\Resources\Expenses\Pages\EditExpense;
use App\Commands\Expenses\GenerateVoucher;
use App\Filament\Resources\ExpenseResource\Pages;
use App\Models\Account;
use App\Models\Branch;
use App\Models\Client;
use App\Models\Expense;
use Awcodes\TableRepeater\Components\TableRepeater;
use Awcodes\TableRepeater\Header;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use JetBrains\PhpStorm\NoReturn;

class ExpenseResource extends Resource
{
    protected static ?string $model = Expense::class;

    protected static bool $isVatable;

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-banknotes';

    protected static bool $shouldRegisterNavigation = false;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components(static::getExpenseFormFields());
    }

    public static function getExpenseFormFields(): array
    {
        return [
            Select::make('client')
                ->default(request()->query('client_id'))
                ->options(Client::query()->get()->pluck('company', 'id'))
                ->afterStateUpdated(function ($set, $get) {
                    $set('branch_id', '');
                    $set('voucher_number', static::getVoucherNumber($get));
                })
                ->required()
                ->live(),
            Select::make('branch_id')
                ->relationship('branch', 'code')
                ->options(fn ($get) => Branch::query()->where('client_id', $get('client'))->get()->pluck('code', 'id'))
                ->afterStateUpdated(function ($set, $get) {
                    $set('voucher_number', static::getVoucherNumber($get));
                    $set('transactions.*.branch_id', $get('branch_id'));
                })
                ->required()
                ->live(),
            TextInput::make('supplier')->label('Supplier Name')->required(),
            TextInput::make('reference_number')->label('Reference Number'),
            TextInput::make('voucher_number')->label('Voucher Number')
                ->default(fn ($get) => static::getVoucherNumber($get))
                ->readOnly(),
            DatePicker::make('happened_on')->label('Date')
                ->required()
                ->afterStateUpdated(function ($set, $get) {
                    $set('transactions.*.happened_on', $get('happened_on'));
                })
                ->live()
                ->native(false),

            TableRepeater::make('transactions')
                ->headers(fn (Get $get): array => static::getTransactionTableHeader($get))
                ->relationship('transactions')
                ->schema(fn (Get $get): array => static::getTransactionTableFormSchema($get))
                ->visible(fn (Get $get) => $get('branch_id') != null)
                ->columnSpan('full'),
        ];
    }

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

        if ($branch) {
            return GenerateVoucher::execute($branch);
        }

        return '';
    }

    public static function getTransactionTableHeader(Get $get): array
    {

        //        if (! static::getIsVatable($get)) {
        //            return [
        //                Header::make('Charge Account'),
        //                Header::make('Description'),
        //                Header::make('Gross Amount'),
        //                Header::make('Withholding Tax'),
        //                Header::make('Net Amount'),
        //            ];
        //        }

        return [
            Header::make('Charge Account'),
            Header::make('Description'),
            //            Header::make('Branch'),
            Header::make('Gross Amount'),
            Header::make('Exempt'),
            Header::make('Zero Rated'),
            Header::make('Vatable Amount'),
            Header::make('Input Tax'),
            Header::make('Withholding Tax'),
            Header::make('Net Amount'),
        ];
    }

    public static function getTransactionTableFormSchema(Get $get): array
    {
        //        if (! static::getIsVatable($get)) {
        //            return [
        //                Select::make('account_id')->options(fn ($get) => static::getAccountOptions($get)),
        //                TextInput::make('description')->label('Description'),
        //                TextInput::make('gross_amount')->numeric()
        //                    ->live()
        //                    ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {
        //                        static::setDefaultFormValues($get, $set, $old, $state);
        //                    })->default(0),
        //                TextInput::make('payable_withholding_tax')->numeric()->live()
        //                    ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {
        //                        static::setDefaultFormValues($get, $set, $old, $state);
        //                    })->default(0),
        //                TextInput::make('net_amount')->numeric()->default(0),
        //            ];
        //        }

        return [
            Select::make('account_id')->options(fn ($get) => static::getAccountOptions($get)),
            TextInput::make('description')->label('Description'),
            Hidden::make('branch_id')->default(fn (Get $get) => $get('../../branch_id')),
            TextInput::make('gross_amount')
                ->numeric()
                ->live(false, 500)
                ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {
                    static::setDefaultFormValues($get, $set, $old, $state);
                })->default(0),
            TextInput::make('exempt')
                ->numeric()
                ->live()
                ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {
                    static::setDefaultFormValues($get, $set, $old, $state);
                })->default(0),
            TextInput::make('zero_rated')
                ->numeric()
                ->live()
                ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {

                    static::setDefaultFormValues($get, $set, $old, $state);
                })->default(0),
            TextInput::make('vatable_amount')
                ->numeric()
                ->nullable()
                ->live()
                ->readOnly()
                ->default(0),
            Hidden::make('happened_on')->default(fn (Get $get) => $get('../../happened_on')),
            TextInput::make('input_tax')
                ->numeric()
                ->live()
                ->afterStateUpdated(function (Get $get, Set $set, ?string $old, ?string $state) {

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

                    static::setDefaultFormValues($get, $set, $old, $state);
                })->default(0),
            TextInput::make('net_amount')->numeric()->default(0),
        ];
    }

    public static function getAccountOptions(Get $get): Collection
    {
        $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', 'Expenses');
        });

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

    public static function setDefaultFormValues(Get $get, Set $set, ?string $old, ?string $state): void
    {

        $exempt = (float) $get('exempt');
        $withHoldingTax = (float) $get('payable_withholding_tax');
        $vatableSales = $get('gross_amount');
        $vatableAmount = 0;
        if ($vatableSales) {
            $vatableAmount = $vatableSales / 1.12;
        }

        $inputTax = $vatableAmount * 0.12;

        $netAmount = (int) $vatableSales - $get('payable_withholding_tax');

        if (static::getIsVatable($get)) {
            $netAmount = ($vatableAmount + $exempt) - $withHoldingTax;
        }

        $set('input_tax', number_format($inputTax, 2, '.', ''));
        $set('vatable_amount', number_format($vatableAmount, 2, '.', ''));
        $set('net_amount', number_format($netAmount, 2, '.', ''));
    }

    public static function getIsVatable(Get $get): bool
    {
        $client = Client::find($get('client'));

        return $client && $client->vatable;

    }

    public static function isVatable(bool $value): void
    {
        static::$isVatable = $value;
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns(static::getTableColumns())
            ->filters([
                //
            ])
            ->recordActions([
                DeleteAction::make(),
                EditAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getTableColumns(): array
    {
        return [
            TextColumn::make('supplier'),
            TextColumn::make('reference_number'),
            TextColumn::make('voucher_number'),
            TextColumn::make('branch.client.company'),
            TextColumn::make('branch.code'),
            TextColumn::make('happened_on'),
            TextColumn::make('accounts_list')->label('Accounts'),
        ];
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => ListExpenses::route('/'),
            'create' => CreateExpense::route('/create'),
            'edit' => EditExpense::route('/{record}/edit'),
        ];
    }
}
