<?php

namespace App\Filament\Resources\Payments\Schemas;

use App\Models\Consignment;
use App\Models\Invoice;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;

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

            // ── Step 1: Find the consignment ──────────────────────
            Section::make('Find Consignment')
                ->description('Search by client name, phone or waybill/container number')
                ->schema([
                    Select::make('consignment_id')
                        ->label('Consignment')
                        ->searchable()
                        ->required()
                        ->live()
                        ->getSearchResultsUsing(function (string $search) {
                            return Consignment::query()
                                ->select([
                                    'id', 'customer_name', 'phone',
                                    'house_waybill_no', 'container_no',
                                ])
                                ->where(function ($q) use ($search) {
                                    $q->where('customer_name', 'like', "%{$search}%")
                                      ->orWhere('phone', 'like', "%{$search}%")
                                      ->orWhere('house_waybill_no', 'like', "%{$search}%")
                                      ->orWhere('container_no', 'like', "%{$search}%");
                                })
                                ->whereHas('invoice', fn ($q) =>
                                    $q->whereIn('payment_status', ['unpaid', 'partial'])
                                )
                                ->limit(20)
                                ->get()
                                ->mapWithKeys(fn ($c) => [
                                    $c->id => "{$c->customer_name} — {$c->phone} " .
                                              ($c->house_waybill_no ?? $c->container_no ?? ''),
                                ]);
                        })
                        ->getOptionLabelUsing(function ($value) {
                            $c = Consignment::select([
                                'id', 'customer_name', 'phone',
                                'house_waybill_no', 'container_no',
                            ])->find($value);

                            return $c
                                ? "{$c->customer_name} — {$c->phone}"
                                : $value;
                        })
                        ->afterStateUpdated(function ($state, $set) {
                            if (! $state) return;

                            $invoice = Invoice::where('consignment_id', $state)
                                ->select([
                                    'id', 'invoice_number',
                                    'amount_kes', 'amount_usd',
                                    'amount_paid_kes', 'outstanding_kes',
                                    'payment_status',
                                ])
                                ->first();

                            if ($invoice) {
                                $set('invoice_id',   $invoice->id);
                                $set('_inv_no',      $invoice->invoice_number);
                                $set('_total',       'KES ' . number_format($invoice->amount_kes, 2));
                                $set('_usd',         $invoice->amount_usd > 0
                                    ? '$ ' . number_format($invoice->amount_usd, 2)
                                    : '—');
                                $set('_paid',        'KES ' . number_format($invoice->amount_paid_kes, 2));
                                $set('_outstanding', 'KES ' . number_format($invoice->outstanding_kes, 2));
                                $set('_status',      ucfirst($invoice->payment_status));
                                // Pre-fill with outstanding amount
                                $set('amount_kes',   $invoice->outstanding_kes);
                            } else {
                                $set('invoice_id',   null);
                                $set('_inv_no',      'No invoice found — generate one first from Consignments');
                                $set('_outstanding', '—');
                                $set('amount_kes',   null);
                            }
                        }),
                ]),

            // ── Invoice summary ───────────────────────────────────
            Section::make('Invoice Summary')
                ->schema([
                    Grid::make(3)->schema([
                        Placeholder::make('_inv_no')
                            ->label('Invoice No.'),
                        Placeholder::make('_usd')
                            ->label('USD Amount'),
                        Placeholder::make('_total')
                            ->label('Total (KES)'),
                        Placeholder::make('_paid')
                            ->label('Already Paid'),
                        Placeholder::make('_outstanding')
                            ->label('Outstanding'),
                        Placeholder::make('_status')
                            ->label('Status'),
                    ]),
                ])
                ->visible(fn ($get) => (bool) $get('consignment_id')),

            // ── Step 2: Payment details ───────────────────────────
            Section::make('Payment Details')
                ->schema([
                    Hidden::make('invoice_id'),

                    Grid::make(2)->schema([

                        TextInput::make('amount_kes')
                            ->label('Amount Received (KES)')
                            ->numeric()
                            ->required()
                            ->prefix('KES')
                            ->minValue(0.01)
                            ->helperText('Partial payments allowed'),

                        Select::make('method')
                            ->label('Payment Method')
                            ->options([
                                'cash'   => 'Cash',
                                'mpesa'  => 'M-Pesa',
                                'bank'   => 'Bank Transfer',
                                'cheque' => 'Cheque',
                            ])
                            ->required()
                            ->native(false)
                            ->live(),

                        TextInput::make('reference')
                            ->label(fn ($get) => match ($get('method')) {
                                'mpesa'  => 'M-Pesa Transaction Code',
                                'bank'   => 'Bank Reference Number',
                                'cheque' => 'Cheque Number',
                                default  => 'Reference (optional)',
                            })
                            ->nullable()
                            ->placeholder(fn ($get) => match ($get('method')) {
                                'mpesa'  => 'e.g. QHX7ABCDEF',
                                'cheque' => 'e.g. 001234',
                                default  => '',
                            }),

                        Textarea::make('notes')
                            ->label('Notes (optional)')
                            ->rows(2)
                            ->nullable()
                            ->columnSpanFull(),
                    ]),
                ])
                ->visible(fn ($get) => (bool) $get('invoice_id')),
        ]);
    }
}