<?php

namespace App\Filament\Resources;

use App\Domain\Rent\Services\InvoiceGeneratorService;
use App\Domain\Rent\Services\PaymentAllocatorService;
use App\Filament\Resources\InvoiceResource\Pages;
use App\Models\Invoice;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Infolists\Infolist;
use Filament\Infolists\Components\Section;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Forms;
use Filament\Notifications\Notification;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use App\Models\AppSetting;
use Illuminate\Support\Str;
use App\Domain\Rent\Support\HandlesInvoicePayment;


class InvoiceResource extends Resource
{
     use HandlesInvoicePayment;
    protected static ?string $model = Invoice::class;

    protected static ?string $navigationGroup = 'Transaksi';
    protected static ?string $navigationIcon = 'heroicon-o-receipt-percent';
    protected static ?string $navigationLabel = 'Invoice';
    protected static ?int $navigationSort = 72;

    public static function form(Form $form): Form
    {
        // invoice readonly (dibuat generator)
        return $form->schema([]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('tenant.name')->label('Penyewa')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('period_type')->label('Type')->badge()->sortable(),
                Tables\Columns\TextColumn::make('period_start')->label('Start')->date()->sortable(),
                Tables\Columns\TextColumn::make('period_end')->label('End')->date()->sortable(),
                Tables\Columns\TextColumn::make('due_date')->label('Due')->date()->sortable(),
                Tables\Columns\TextColumn::make('total_amount')->label('Total')->money('IDR', true)->sortable(),
                Tables\Columns\TextColumn::make('paid_amount')->label('Paid')->money('IDR', true)->sortable(),
                Tables\Columns\TextColumn::make('status')->label('Status')->badge()->sortable(),
            ])

            ->defaultSort('created_at', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('status')->options([
                    'unpaid'=>'Unpaid','partial'=>'Partial','paid'=>'Paid','void'=>'Void'
                ]),
                Tables\Filters\SelectFilter::make('period_type')->options([
                    'monthly'=>'Monthly','yearly'=>'Yearly'
                ]),
            ])
            ->actions([
                // BAYAR
                Tables\Actions\Action::make('pay')
                    ->label('Bayar')
                    ->icon('heroicon-o-banknotes')
                    ->color('success')
                    ->visible(fn (Invoice $record) =>
                        in_array($record->status, ['unpaid', 'partial'], true)
                        && $record->status !== 'void'
                    )
                    ->modalHeading('Pembayaran Invoice')
                    ->modalSubmitActionLabel('Simpan')
                    ->form(function (Invoice $record) {
                        $need = max(0, (int) round((float)$record->total_amount - (float)$record->paid_amount));

                        return [
                            Forms\Components\Placeholder::make('need_info')
                                ->label('Sisa Tagihan')
                                ->content('Rp ' . number_format($need, 0, ',', '.')),

                            Forms\Components\DateTimePicker::make('paid_at')
                                ->label('Tanggal Bayar')
                                ->default(now())
                                ->required(),

                            Forms\Components\Select::make('method')
                                ->label('Metode')
                                ->options([
                                    'cash' => 'Cash',
                                    'transfer' => 'Transfer',
                                    'qris' => 'QRIS',
                                    'other' => 'Other',
                                ])
                                ->default('cash')
                                ->required(),

                            Forms\Components\TextInput::make('reference_no')
                                ->label('No Referensi (opsional)')
                                ->maxLength(60),

                            Forms\Components\FileUpload::make('proof_image')
                                ->label('Bukti Bayar (opsional)')
                                ->disk('public')
                                ->directory('payments/proofs')
                                ->image()
                                ->maxSize(2048)
                                ->helperText('Upload JPG/PNG/WebP max 2MB.')
                                ->columnSpanFull(),

                            Forms\Components\TextInput::make('total_amount')
                                ->label('Nominal Dibayar (Rp)')
                                ->numeric()
                                ->default($need)
                                ->required()
                                ->helperText('Bisa partial. Maksimal sampai sisa tagihan invoice ini.'),

                            Forms\Components\Textarea::make('notes')
                                ->label('Catatan (opsional)')
                                ->rows(2),

                            // ✅ toggle kirim WA
                            Forms\Components\Toggle::make('send_wa')
                                ->label('Kirim WhatsApp setelah simpan')
                                ->default(true)
                                ->helperText('Jika aktif, setelah tersimpan akan diarahkan ke WhatsApp.'),
                        ];
                    })
                    ->action(function (array $data, Invoice $record, $livewire) {
                        $sendWa = (bool)($data['send_wa'] ?? false);
                        $livewire->handleInvoicePayment($record, $data, $sendWa);
                    }),




                // VOID + REGENERATE (aman hanya jika belum bayar)
                Tables\Actions\Action::make('voidRegenerate')
                    ->label('Hapus (Void) + Regenerate')
                    ->icon('heroicon-o-arrow-path')
                    ->color('warning')
                    ->requiresConfirmation()
                    ->modalHeading('Void invoice lalu generate ulang?')
                    ->modalDescription('Aman hanya jika invoice belum ada pembayaran. Invoice akan di-void lalu dibuat ulang berdasarkan lease terbaru.')
                    ->visible(fn (Invoice $record) =>
                        in_array($record->status, ['unpaid'], true) && (float)$record->paid_amount <= 0
                    )
                    ->action(function (Invoice $record) {
                        DB::transaction(function () use ($record) {
                            $record->status = 'void';
                            $record->save();

                            app(InvoiceGeneratorService::class)->generateForTenantForDate(
                                (int) $record->tenant_id,
                                Carbon::parse($record->period_start)
                            );
                        });

                        Notification::make()
                            ->title('Invoice berhasil di-void & digenerate ulang')
                            ->success()
                            ->send();
                    }),

                Tables\Actions\ViewAction::make(),
            ])
            ->bulkActions([]);
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist->schema([
            Section::make('Invoice')
                ->columns(2)
                ->schema([
                    TextEntry::make('tenant.name')->label('Penyewa'),
                    TextEntry::make('status')->badge(),
                    TextEntry::make('period_type')->label('Tipe')->badge(),
                    TextEntry::make('period_start')->date()->label('Mulai'),
                    TextEntry::make('period_end')->date()->label('Selesai'),
                    TextEntry::make('due_date')->date()->label('Jatuh Tempo'),
                    TextEntry::make('total_amount')->money('IDR', true)->label('Total'),
                    TextEntry::make('paid_amount')->money('IDR', true)->label('Dibayar'),
                ]),

            Section::make('Detail Ruko')
                ->schema([
                    RepeatableEntry::make('items')
                        ->schema([
                            TextEntry::make('unit.code')->label('Kode'),
                            TextEntry::make('unit.name')->label('Ruko'),
                            TextEntry::make('description')->label('Deskripsi'),
                            TextEntry::make('amount')->label('Nominal')->money('IDR', true),
                        ])
                        ->columns(4),
                ]),
        ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListInvoices::route('/'),
            'view'  => Pages\ViewInvoice::route('/{record}'),
        ];
    }
}
