<?php

namespace App\Filament\Resources\DelayedGoods\Schemas;

use App\Models\EggPrice;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Schema;

class DelayedGoodForm
{
    public static function configure(Schema $schema): Schema
    {
        $recalculateTotal = function (callable $get, callable $set): void {
            $quantity = (int) str()->replace('.', '', (string) ($get('quantity') ?? 0));
            $unitPrice = (int) str()->replace('.', '', (string) ($get('unit_price') ?? 0));
            $totalAmount = $quantity * $unitPrice;
            $set('total_amount', number_format($totalAmount, 0, ',', '.'));
        };

        return $schema->components([
            Hidden::make('unit_id')
                ->required(),

            Grid::make(2)
                ->schema([
                    Select::make('egg_price_id')
                        ->label('Harga Telur')
                        ->options(EggPrice::query()->with('unit')->get()->mapWithKeys(function ($item) {
                            return [$item->id => $item->name.' ('.($item->unit?->alias ?? '-').')'];
                        }))
                        ->searchable()
                        ->preload()
                        ->native(false)
                        ->live()
                        ->afterStateHydrated(function ($state, callable $set, callable $get, $record): void {
                            if ($record && ! $state) {
                                $eggPrice = EggPrice::where('unit_id', $record->unit_id)
                                    ->where('price', $record->unit_price)
                                    ->first();

                                if ($eggPrice) {
                                    $set('egg_price_id', $eggPrice->id);
                                }
                            }
                        })
                        ->afterStateUpdated(function ($state, callable $set, callable $get) use ($recalculateTotal): void {
                            if (! $state) {
                                $set('unit_price', 0);
                                $set('unit_id', null);
                                $recalculateTotal($get, $set);

                                return;
                            }

                            $price = EggPrice::with('unit')->find($state);

                            $set('unit_price', number_format($price?->price ?? 0, 0, ',', '.'));
                            $set('unit_id', $price?->unit_id);

                            $recalculateTotal($get, $set);
                        })
                        ->dehydrated(false)
                        ->required(),

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

                    DatePicker::make('stored_date')
                        ->label('Tanggal Penyimpanan')
                        ->default(now())
                        ->required()
                        ->native(false)
                        ->displayFormat('l, d F Y'),

                    TextInput::make('quantity')
                        ->label('Jumlah Barang')
                        ->placeholder('0')
                        ->autocomplete(false)
                        ->required()
                        ->live()
                        ->afterStateUpdated(function ($state, callable $get, callable $set) use ($recalculateTotal): void {
                            $recalculateTotal($get, $set);
                        })
                        ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                        ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0))),
                ]),

            Grid::make(2)
                ->schema([
                    TextInput::make('unit_price')
                        ->label('Harga per Satuan')
                        ->placeholder('0')
                        ->readOnly()
                        ->prefix('Rp')
                        ->required()
                        ->formatStateUsing(
                            fn ($state) => number_format((int) ($state ?? 0), 0, ',', '.')
                        )
                        ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0)))
                        ->afterStateUpdated(function ($state, callable $get, callable $set) use ($recalculateTotal): void {
                            $recalculateTotal($get, $set);
                        }),

                    TextInput::make('total_amount')
                        ->label('Total')
                        ->placeholder('0')
                        ->readOnly()
                        ->prefix('Rp')
                        ->required()
                        ->live()
                        ->formatStateUsing(
                            fn ($state) => number_format((int) ($state ?? 0), 0, ',', '.')
                        )
                        ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0))),
                ]),

            Grid::make(3)
                ->schema([
                    TextInput::make('paid_amount')
                        ->label('Jumlah yang Sudah Dibayar (DP)')
                        ->placeholder('0')
                        ->default(0)
                        ->autocomplete(false)
                        ->required()
                        ->live()
                        ->prefix('Rp')
                        ->readOnly(fn (callable $get) => $get('is_paid'))
                        ->afterStateUpdated(function ($state, callable $get, callable $set): void {
                            $paidAmount = (int) str()->replace('.', '', (string) ($state ?? 0));
                            $totalAmount = (int) str()->replace('.', '', (string) ($get('total_amount') ?? 0));

                            if (! $get('is_paid')) {
                                $set('is_paid', $paidAmount >= $totalAmount && $totalAmount > 0);
                            }

                            if ($paidAmount >= $totalAmount && $totalAmount > 0 && ! $get('payment_date')) {
                                $set('payment_date', now());
                            }

                            if ($paidAmount < $totalAmount) {
                                $set('payment_date', null);
                            }
                        })
                        ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                        ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0))),

                    TextInput::make('remaining_amount')
                        ->label('Sisa Pembayaran')
                        ->placeholder('0')
                        ->readOnly()
                        ->prefix('Rp')
                        ->default(0)
                        ->formatStateUsing(function ($state, callable $get) {
                            $paidAmount = (int) str()->replace('.', '', (string) ($get('paid_amount') ?? 0));
                            $totalAmount = (int) str()->replace('.', '', (string) ($get('total_amount') ?? 0));
                            $remaining = max(0, $totalAmount - $paidAmount);

                            return number_format($remaining, 0, ',', '.');
                        })
                        ->dehydrated(false)
                        ->live(),

                    Toggle::make('is_paid')
                        ->label('Lunas')
                        ->default(false)
                        ->live()
                        ->afterStateUpdated(function ($state, callable $get, callable $set): void {
                            $totalAmount = (int) str()->replace('.', '', (string) ($get('total_amount') ?? 0));

                            if ($state) {
                                $set('paid_amount', $totalAmount);

                                if (! $get('payment_date')) {
                                    $set('payment_date', now());
                                }
                            } else {
                                $set('paid_amount', 0);
                                $set('payment_date', null);
                            }
                        }),

                    DatePicker::make('payment_date')
                        ->label('Tanggal Pembayaran Lunas')
                        ->native(false)
                        ->displayFormat('l, d F Y')
                        ->visible(function (callable $get) {
                            $paidAmount = (int) str()->replace('.', '', (string) ($get('paid_amount') ?? 0));
                            $totalAmount = (int) str()->replace('.', '', (string) ($get('total_amount') ?? 0));

                            return $paidAmount >= $totalAmount && $totalAmount > 0;
                        }),
                ]),

            Textarea::make('notes')
                ->label('Catatan')
                ->placeholder('...')
                ->autocomplete(false)
                ->columnSpanFull(),
        ])
            ->columns(1);
    }
}
