<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PaymentResource\Pages;
use App\Models\Payment;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use App\Models\AppSetting;
use Filament\Notifications\Notification;
use Illuminate\Support\Str;
use Filament\Forms\Components\FileUpload;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\HtmlString;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Get;



class PaymentResource extends Resource
{
    protected static ?string $model = Payment::class;

    protected static ?string $navigationGroup = 'Transaksi';
    protected static ?string $navigationIcon = 'heroicon-o-banknotes';
    protected static ?string $navigationLabel = 'Pembayaran';
    protected static ?int $navigationSort = 73;

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make('Pembayaran')
                ->columns(2)
                ->schema([
                    Forms\Components\Select::make('tenant_id')
                        ->label('Penyewa')
                        ->relationship('tenant','name')
                        ->searchable()
                        ->preload()
                        ->required(),

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

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

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

                    Forms\Components\TextInput::make('total_amount')
                        ->label('Total')
                        ->numeric()
                        ->prefix('Rp')
                        ->required(),
                    Placeholder::make('proof_preview')
                          ->label('Bukti Bayar (Existing)')
                          ->visible(fn ($record) => filled($record?->proof_image))
                          ->content(function ($record) {
                              $url = route('payment.proof', $record); // route A kamu (stream by payment)
                              return new HtmlString('
                                  <div class="space-y-2">
                                      <a href="'.$url.'" target="_blank" rel="noopener">
                                          <img
                                              src="'.$url.'"
                                              alt="Bukti Pembayaran"
                                              style="max-width: 100%; height: auto; border-radius: 12px; border: 1px solid #e5e7eb;"
                                          />
                                      </a>
                                      <div class="text-xs text-gray-500">Klik gambar untuk membuka di tab baru.</div>
                                  </div>
                              ');
                          })
                          ->columnSpanFull(),

                    FileUpload::make('proof_image')
                            ->label('Bukti Bayar')
                            ->disk('public')
                            ->directory('payments/proofs')
                            ->image()
                            ->imageEditor() // optional, boleh hapus kalau tidak perlu
                            ->maxSize(2048) // 2MB
                             ->imagePreviewHeight(0)
                            ->helperText('Upload gambar (JPG/PNG/WebP) max 2MB.')
                            ->columnSpanFull(),

                    Forms\Components\Textarea::make('notes')->label('Catatan')->columnSpanFull(),
                ]),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('receipt_no')->label('Receipt')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('tenant.name')->label('Penyewa')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('paid_at')->label('Tanggal')->dateTime()->sortable(),
                Tables\Columns\TextColumn::make('method')->label('Metode')->badge()->sortable(),
                Tables\Columns\TextColumn::make('total_amount')->label('Total')->money('IDR', true)->sortable(),
            ])
            ->defaultSort('created_at', 'desc')
            ->actions([
              Tables\Actions\Action::make('wa')
                  ->label('Kirim WA')
                  ->icon('heroicon-o-chat-bubble-left-right')
                  ->color('success')
                  ->visible(fn ($record) => ! empty($record->tenant?->phone))
                  ->action(function ($record) {

                      $settings = AppSetting::singleton();

                      if (! $settings->wa_enabled) {
                          Notification::make()
                              ->title('WhatsApp tidak aktif')
                              ->danger()
                              ->send();
                          return;
                      }

                      $phone = preg_replace('/\D+/', '', $record->tenant->phone);

                      // link kuitansi publik
                      $publicUrl = route('receipt.public', $record->public_token);

                      // template pesan
                      $period = '-';
                      if ($record->invoice?->period_start && $record->invoice?->period_end) {
                          $period = $record->invoice->period_start->translatedFormat('d M Y')
                              .' – '.
                              $record->invoice->period_end->translatedFormat('d M Y');
                      }

                      $template = $settings->wa_message_template ?:
                          "Halo {tenant_name},\n\n"
                        . "Kami informasikan pembayaran sewa Anda:\n"
                        . "Periode: {period}\n"
                        . "No Kuitansi: {receipt_no}\n"
                        . "Total: Rp{amount}\n\n"
                        . "Bukti pembayaran:\n{public_url}\n\n"
                        . "Terima kasih.";

                      $message = str_replace(
                          ['{tenant_name}', '{period}', '{receipt_no}', '{amount}', '{public_url}'],
                          [
                              $record->tenant->name,
                              $period,
                              $record->receipt_no,
                              number_format($record->total_amount, 0, ',', '.'),
                              $publicUrl
                          ],
                          $template
                        );

                      // buka WA
                      redirect()->away(
                          'https://wa.me/' . $phone . '?text=' . urlencode($message)
                      );
                  }),
                  Tables\Actions\Action::make('view_proof')
                        ->label('Bukti')
                        ->icon('heroicon-o-photo')
                        ->color('info')
                        ->visible(fn ($record) => filled($record->proof_image))
                        ->modalHeading('Bukti Pembayaran')
                        ->modalWidth('2xl')
                        ->modalSubmitAction(false)
                        ->modalCancelActionLabel('Tutup')
                        ->modalContent(function ($record) {
                            $url = route('payment.proof', $record);

                            return new \Illuminate\Support\HtmlString('
                                <div class="space-y-3">
                                    <div class="text-sm text-gray-600">Klik gambar untuk memperbesar di tab baru.</div>
                                    <a href="'.$url.'" target="_blank" rel="noopener">
                                        <img
                                            src="'.$url.'"
                                            alt="Bukti Pembayaran"
                                            style="max-width: 100%; height: auto; border-radius: 12px; border: 1px solid #e5e7eb;"
                                        />
                                    </a>
                                </div>
                            ');
                        }),


              Tables\Actions\EditAction::make(),
              Tables\Actions\DeleteAction::make(),
          ])

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

    public static function getPages(): array
    {
        return [
            'index'  => Pages\ListPayments::route('/'),
            'create' => Pages\CreatePayment::route('/create'),
            'edit'   => Pages\EditPayment::route('/{record}/edit'),
        ];
    }
}
