<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SuratPendatangResource\Pages;
use App\Models\SuratPendatang;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Filament\Notifications\Notification;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\HtmlString;

class SuratPendatangResource extends Resource
{
    protected static ?string $model = SuratPendatang::class;

    protected static ?string $navigationIcon = 'heroicon-o-arrow-down-on-square';
    protected static ?string $navigationGroup = 'Kelola Surat';
    protected static ?string $navigationLabel = 'Surat Pendatang';
    protected static ?int $navigationSort = 3;
    protected static bool $shouldRegisterNavigation = false;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Pendatang')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('nama_pendatang')
                            ->label('Nama Lengkap Pendatang')
                            ->required()
                            ->placeholder('Masukkan nama lengkap pendatang'),
                        Forms\Components\TextInput::make('nik_pendatang')
                            ->label('NIK Pendatang')
                            ->required()
                            ->unique(ignoreRecord: true) // NIK harus unik
                            ->numeric()
                            ->placeholder('Masukkan 16 digit NIK pendatang'), // Placeholder for NIK
                        Forms\Components\TextInput::make('tempat_lahir_pendatang')
                            ->label('Tempat Lahir')
                            ->placeholder('Contoh: Jakarta'),
                        Forms\Components\DatePicker::make('tanggal_lahir_pendatang')
                            ->label('Tanggal Lahir')
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal lahir'),
                        Forms\Components\Select::make('jenis_kelamin_pendatang')
                            ->label('Jenis Kelamin')
                            ->options([
                                'Laki-laki' => 'Laki-laki',
                                'Perempuan' => 'Perempuan',
                            ])
                            ->placeholder('Pilih jenis kelamin'),
                        Forms\Components\Select::make('agama_pendatang') // Diubah menjadi Select
                            ->label('Agama')
                            ->options([
                                'Islam' => 'Islam',
                                'Kristen Protestan' => 'Kristen Protestan',
                                'Kristen Katolik' => 'Kristen Katolik',
                                'Hindu' => 'Hindu',
                                'Buddha' => 'Buddha',
                                'Konghucu' => 'Konghucu',
                                'Lainnya' => 'Lainnya',
                            ])
                            ->placeholder('Pilih agama'),
                        Forms\Components\TextInput::make('pekerjaan_pendatang')
                            ->label('Pekerjaan')
                            ->placeholder('Contoh: Pegawai Swasta'),
                        Forms\Components\TextInput::make('alamat_saat_ini_pendatang')
                            ->label('Alamat Saat Ini (di desa Raksajaya)')
                            ->columnSpanFull()
                            ->placeholder('Masukkan alamat lengkap saat ini di desa Raksajaya'),
                        Forms\Components\TextInput::make('rt_saat_ini_pendatang')
                            ->label('RT Saat Ini')
                            ->numeric()
                            ->placeholder('Contoh: 001'),
                        Forms\Components\TextInput::make('rw_saat_ini_pendatang')
                            ->label('RW Saat Ini')
                            ->numeric()
                            ->placeholder('Contoh: 002'),
                        Forms\Components\DatePicker::make('tanggal_datang')
                            ->label('Tanggal Datang')
                            ->required()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal kedatangan'),
                        Forms\Components\Textarea::make('maksud_tujuan')
                            ->label('Maksud dan Tujuan Datang')
                            ->required()
                            ->rows(3)
                            ->columnSpanFull()
                            ->placeholder('Jelaskan maksud dan tujuan pendatang ke desa ini'),
                    ]),

                Forms\Components\Section::make('Alamat Asal')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('alamat_asal')
                            ->label('Alamat Lengkap Asal')
                            ->required()
                            ->placeholder('Contoh: Jl. Merdeka No. 10'),
                        Forms\Components\TextInput::make('rt_asal')
                            ->label('RT Asal')
                            ->nullable()
                            ->numeric()
                            ->placeholder('Contoh: 001'),
                        Forms\Components\TextInput::make('rw_asal')
                            ->label('RW Asal')
                            ->nullable()
                            ->numeric()
                            ->placeholder('Contoh: 002'),
                        Forms\Components\TextInput::make('dusun_asal')
                            ->label('Dusun Asal')
                            ->nullable()
                            ->placeholder('Contoh: Dusun Cempaka'),
                        Forms\Components\TextInput::make('desa_asal')
                            ->label('Desa Asal')
                            ->required()
                            ->placeholder('Contoh: Desa Suka Maju'),
                        Forms\Components\TextInput::make('kecamatan_asal')
                            ->label('Kecamatan Asal')
                            ->required()
                            ->placeholder('Contoh: Kecamatan Jaya Raya'),
                        Forms\Components\TextInput::make('kabupaten_asal')
                            ->label('Kabupaten/Kota Asal')
                            ->required()
                            ->placeholder('Contoh: Kabupaten Bekasi'),
                        Forms\Components\TextInput::make('provinsi_asal')
                            ->label('Provinsi Asal')
                            ->required()
                            ->placeholder('Contoh: Jawa Barat'),
                    ]),

                Forms\Components\TextInput::make('nomor_surat')
                    ->label('Nomor Surat')
                    ->disabledOn('create')
                    ->helperText('Nomor surat akan dibuat otomatis saat disetujui oleh admin desa.')
                    ->placeholder('Nomor surat akan terisi otomatis'),

                Forms\Components\Select::make('status')
                    ->options([
                        'menunggu_acc_admin_desa' => 'Menunggu Persetujuan Admin Desa',
                        'disetujui' => 'Disetujui',
                        'ditolak' => 'Ditolak',
                    ])
                    ->disabledOn('create')
                    ->visibleOn('edit')
                    ->visible(fn (): bool => Auth::user()->role !== 'warga')
                    ->placeholder('Pilih status persetujuan'),

                Forms\Components\Textarea::make('catatan_penolakan')
                    ->label('Catatan Penolakan')
                    ->visible(fn (string $operation, Forms\Get $get): bool => $get('status') === 'ditolak' && $operation === 'edit')
                    ->placeholder('Masukkan alasan penolakan surat ini'),

                Forms\Components\Placeholder::make('file_surat')
                    ->label('File Surat')
                    ->content(function (?SuratPendatang $record) {
                        if ($record && $record->file_path) {
                            $url = Storage::url($record->file_path);
                            return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh Surat Pendatang</a>");
                        }
                        return 'Belum ada file surat.';
                    })
                    ->visibleOn('edit'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('nomor_surat')
                    ->label('No. Surat')
                    ->placeholder('Belum Tersedia')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nama_pendatang')
                    ->label('Nama Pendatang')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nik_pendatang')
                    ->label('NIK Pendatang')
                    ->default('-'),
                Tables\Columns\TextColumn::make('tanggal_datang')
                    ->label('Tanggal Datang')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('alamat_asal')
                    ->label('Alamat Asal')
                    ->wrap()
                    ->limit(50), // Batasi tampilan agar tidak terlalu panjang
                Tables\Columns\TextColumn::make('desa_asal')
                    ->label('Desa Asal'),
                Tables\Columns\TextColumn::make('kecamatan_asal')
                    ->label('Kecamatan Asal'),
                Tables\Columns\TextColumn::make('kabupaten_asal')
                    ->label('Kabupaten Asal'),
                Tables\Columns\TextColumn::make('provinsi_asal')
                    ->label('Provinsi Asal'),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'menunggu_acc_admin_desa' => 'warning',
                        'disetujui' => 'success',
                        'ditolak' => 'danger',
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('disetujuiOleh.name')
                    ->label('Disetujui Oleh')
                    ->placeholder('Belum Disetujui')
                    ->sortable(),
                Tables\Columns\TextColumn::make('tanggal_disetujui')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options([
                        'menunggu_acc_admin_desa' => 'Menunggu Persetujuan Admin Desa',
                        'disetujui' => 'Disetujui',
                        'ditolak' => 'Ditolak',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\Action::make('download_draft')
                        ->label('Unduh Draft PDF')
                        ->icon('heroicon-o-arrow-down-tray')
                        ->color('info')
                        ->action(function (SuratPendatang $record) {
                            if (!$record->file_path) {
                                $html = view('pdf.surat_pendatang', compact('record'))->render();
                                $pdf = Pdf::loadHtml($html);
                                $filePath = 'surat_pendatang/' . uniqid() . '.pdf';
                                Storage::disk('public')->put($filePath, $pdf->output());
                                $record->update(['file_path' => $filePath]);
                                Notification::make()->title('Draft PDF berhasil digenerate.')->success()->send();
                            }
                            return response()->download(Storage::disk('public')->path($record->file_path));
                        }),

                    Tables\Actions\Action::make('setujui_surat')
                        ->label('Setujui & Unggah PDF')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->modalSubmitActionLabel('Unggah & Setujui')
                        ->form([
                            Forms\Components\TextInput::make('nomor_surat_acc')
                                ->label('Nomor Surat Resmi')
                                ->required()
                                ->unique('surat_pendatang', 'nomor_surat', ignoreRecord: true)
                                ->placeholder('Contoh: 470/SP.001/DS.RKJ/V/2025'),
                            Forms\Components\FileUpload::make('signed_pdf')
                                ->label('Unggah PDF Bertanda Tangan')
                                ->acceptedFileTypes(['application/pdf'])
                                ->directory('surat_pendatang')
                                ->required(),
                        ])
                        ->action(function (array $data, SuratPendatang $record) {
                            DB::transaction(function () use ($data, $record) {
                                $record->update([
                                    'status' => 'disetujui',
                                    'nomor_surat' => $data['nomor_surat_acc'],
                                    'file_path' => $data['signed_pdf'],
                                    'disetujui_oleh' => Auth::id(),
                                    'tanggal_disetujui' => now(),
                                ]);

                                Notification::make()
                                    ->title('Surat Pendatang berhasil disetujui.')
                                    ->success()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratPendatang $record): bool => Auth::user()->role !== 'warga' && $record->status === 'menunggu_acc_admin_desa'),

                    Tables\Actions\Action::make('tolak_surat')
                        ->label('Tolak Surat')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->modalSubmitActionLabel('Tolak')
                        ->form([
                            Forms\Components\Textarea::make('catatan_penolakan')
                                ->label('Alasan Penolakan')
                                ->required()
                                ->rows(5)
                                ->placeholder('Jelaskan alasan mengapa surat ini ditolak'),
                        ])
                        ->action(function (array $data, SuratPendatang $record) {
                            DB::transaction(function () use ($data, $record) {
                                $record->update([
                                    'status' => 'ditolak',
                                    'catatan_penolakan' => $data['catatan_penolakan'],
                                    'disetujui_oleh' => Auth::id(),
                                    'tanggal_disetujui' => now(),
                                ]);

                                Notification::make()
                                    ->title('Surat Pendatang berhasil ditolak.')
                                    ->danger()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratPendatang $record): bool => Auth::user()->role !== 'warga' && $record->status === 'menunggu_acc_admin_desa'),
                ]),
                Tables\Actions\DeleteAction::make()->visible(fn (): bool => Auth::user()->role === 'admin_desa'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()->visible(fn (): bool => Auth::user()->role === 'admin_desa'),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                //
            ]);
    }

    public static function afterCreate(SuratPendatang $record): void
    {
        try {
            $html = view('pdf.surat_pendatang', compact('record'))->render();
            $pdf = Pdf::loadHtml($html);
            $filePath = 'surat_pendatang/' . uniqid() . '.pdf';
            Storage::disk('public')->put($filePath, $pdf->output());

            $record->update(['file_path' => $filePath]);
            Notification::make()->title('Draft PDF surat berhasil digenerate.')->success()->send();
        } catch (\Throwable $th) {
            Notification::make()->title('Gagal mengenerate draft PDF surat.')->danger()->body($th->getMessage())->send();
            report($th);
        }
    }
}