<?php

namespace App\Filament\Resources\QuotaTransactions;

use App\Filament\Resources\QuotaTransactions\Pages\ManageQuotaTransactions;
use App\Models\QuotaTransaction;
use App\Models\FinancialLedger;
use BackedEnum;
use Filament\Support\Icons\Heroicon;
use Filament\Resources\Resource;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

// Import Schema & Components untuk Form
use Filament\Schemas\Schema;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\DateTimePicker;

// Import Columns & Actions untuk Table
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\ActionGroup;
use Filament\Actions\ViewAction;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Forms\Components\Textarea;

class QuotaTransactionResource extends Resource
{
    protected static ?string $model = QuotaTransaction::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBanknotes;

    protected static ?string $navigationLabel = 'Riwayat Kuota';

    protected static ?string $pluralModelLabel = 'Transaksi Kuota';

    public static function getNavigationGroup(): ?string
    {
        return auth()->user()->hasRole(['super_admin', 'Admin']) ? 'Manajemen Kuota Mitra' : 'Manajemen Kuota';
    }

    public static function getNavigationSort(): ?int
    {
        return 1; // Ganti angkanya (1, 2, 3, dst) sesuai urutan yang diinginkan
    }

    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery();

        if (auth()->user()->hasRole('Owner')) {
            $query->where('user_id', auth()->id());
        }

        return $query->latest();
    }


    // FORM DETAIL (READ-ONLY)
    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('Detail Transaksi Keuangan')
                    ->schema([
                        TextInput::make('reference_code')
                            ->label('Kode Referensi'),

                        // MENGUBAH TAMPILAN MENJADI BAHASA INDONESIA
                        TextInput::make('type')
                            ->label('Jenis Arus Kas')
                            ->formatStateUsing(fn($state) => match ($state) {
                                'in' => 'UANG MASUK',
                                'out' => 'UANG KELUAR',
                                default => strtoupper($state),
                            }),

                        // MENGUBAH TAMPILAN KATEGORI MENJADI BAHASA INDONESIA
                        TextInput::make('category')
                            ->label('Kategori')
                            ->formatStateUsing(fn($state) => match ($state) {
                                'quota_purchase' => 'Pembelian Kuota Posting',
                                'booking_fee' => 'Pembayaran Booking Fee',
                                'refund_tenant' => 'Pengembalian Dana (Refund)',
                                default => ucfirst(str_replace('_', ' ', $state)),
                            }),

                        TextInput::make('amount')
                            ->label('Nominal')
                            ->prefix('Rp')
                            ->numeric(),

                        DateTimePicker::make('transaction_date')
                            ->label('Waktu Transaksi'),

                        Textarea::make('description')
                            ->label('Keterangan Detail')
                            ->columnSpanFull(),
                    ])
                    ->columns(2)
                    ->columnSpanFull(), // <--- KUNCI UTAMA 1: Memaksa blok ini rata penuh ke kanan
            ])
            ->columns(1) // <--- KUNCI UTAMA 2: Memastikan wadah utamanya hanya 1 kolom penuh
            ->disabled(); // Kunci form agar tidak bisa diedit
    }

    // BLOK TABLE
    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('invoice_code')
                    ->label('No. Invoice')
                    ->searchable()
                    ->weight('bold'),

                TextColumn::make('user.name')
                    ->label('Nama Mitra')
                    ->visible(fn() => auth()->user()->hasRole(['super_admin', 'Admin'])),

                TextColumn::make('package_name')
                    ->label('Paket Dipilih'),

                TextColumn::make('price')
                    ->label('Total Bayar')
                    ->money('IDR', locale: 'id')
                    ->weight('bold')
                    ->color('warning'),

                TextColumn::make('status')
                    ->badge()
                    ->color(fn(string $state): string => match ($state) {
                        'pending' => 'warning',
                        'menunggu_konfirmasi' => 'info',
                        'lunas' => 'success',
                        'batal' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn(string $state): string => strtoupper(str_replace('_', ' ', $state))),

                TextColumn::make('created_at')
                    ->label('Tanggal')
                    ->dateTime('d M Y, H:i'),
            ])
            ->filters([
                //
            ])
            ->actions([
                ActionGroup::make([

                    // Aksi untuk Admin: Buka Modal Detail Form
                    ViewAction::make()
                        ->label('Lihat Detail')
                        ->icon('heroicon-o-document-magnifying-glass')
                        ->color('gray')
                        ->visible(fn() => auth()->user()->hasRole(['super_admin', 'Admin'])),

                    // Aksi untuk Owner: Kembali ke Halaman Invoice Frontend
                    Action::make('lihat_invoice')
                        ->label('Lanjutkan Pembayaran')
                        ->icon('heroicon-o-credit-card')
                        ->color('warning')
                        ->url(fn(QuotaTransaction $record) => route('owner.quota.invoice', $record->invoice_code))
                        ->visible(fn() => auth()->user()->hasRole('Owner')),

                    // Cek Bukti Transfer (Khusus Admin) dengan Fancybox
                    Action::make('lihat_bukti')
                        ->label('Cek Bukti Transfer')
                        ->icon('heroicon-o-photo')
                        ->color('info')
                        ->url(fn(QuotaTransaction $record) => asset('storage/' . $record->payment_proof))
                        ->extraAttributes([
                            'data-fancybox' => 'gallery', // <--- INI KUNCINYA
                        ])
                        // ->openUrlInNewTab() // <--- HAPUS ATAU KOMENTARI BARIS INI
                        ->visible(fn(QuotaTransaction $record) => auth()->user()->hasRole(['super_admin', 'Admin']) && $record->payment_proof),

                    // Verifikasi Manual (Khusus Admin)
                    Action::make('verifikasi')
                        ->label('Verifikasi Lunas')
                        ->icon('heroicon-o-check-badge')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalHeading('Verifikasi Pembayaran Kuota')
                        ->modalDescription('Apakah Anda yakin dana sudah masuk ke rekening? Tindakan ini akan otomatis menambah kuota Owner dan mencatatnya ke Buku Kas.')
                        ->modalSubmitActionLabel('Ya, Verifikasi & Lunas')
                        ->visible(fn(QuotaTransaction $record) => auth()->user()->hasRole(['super_admin', 'Admin']) && $record->status === 'menunggu_konfirmasi')
                        ->action(function (QuotaTransaction $record) {

                            $record->update(['status' => 'lunas']);
                            $record->user->increment('listing_quota', $record->quota_added);

                            FinancialLedger::create([
                                'transaction_date' => now(),
                                'reference_code' => $record->invoice_code,
                                'type' => 'in',
                                'category' => 'quota_purchase',
                                'amount' => $record->price,
                                'description' => "Pembelian Kuota ({$record->package_name}) oleh Mitra: {$record->user->name}",
                            ]);

                            Notification::make()
                                ->title('Verifikasi Berhasil!')
                                ->success()
                                ->send();
                        }),
                ])
                    ->label('Aksi')
                    ->icon('heroicon-m-ellipsis-vertical')
                    ->button(),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ManageQuotaTransactions::route('/'),
        ];
    }
}
