<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SuratKeteranganSkckResource\Pages;
use App\Models\SuratKeteranganSkck;
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 Filament\Support\RawJs;
use Illuminate\Support\HtmlString;

class SuratKeteranganSkckResource extends Resource
{
    protected static ?string $model = SuratKeteranganSkck::class;

    protected static ?string $navigationIcon = 'heroicon-o-finger-print'; // Contoh ikon
    protected static ?string $navigationGroup = 'Kelola Surat';
    protected static ?string $navigationLabel = 'Surat Keterangan SKCK';
    protected static ?int $navigationSort = 11; // Sesuaikan urutan navigasi
    protected static bool $shouldRegisterNavigation = false;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Data Pemohon')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('nama_lengkap')
                            ->label('Nama Lengkap')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama lengkap pemohon'),
                        Forms\Components\TextInput::make('nik')
                            ->label('NIK')
                            ->required()
                            ->numeric()
                            ->placeholder('Masukkan NIK pemohon'),
                        Forms\Components\TextInput::make('nomor_kartu_keluarga')
                            ->label('Nomor Kartu Keluarga (KK)')
                            ->required()
                            ->numeric()
                            ->placeholder('Masukkan Nomor KK'),
                        Forms\Components\TextInput::make('tempat_lahir')
                            ->label('Tempat Lahir')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Tasikmalaya'),
                        Forms\Components\DatePicker::make('tanggal_lahir')
                            ->label('Tanggal Lahir')
                            ->required()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal lahir'),
                        Forms\Components\Select::make('jenis_kelamin')
                            ->label('Jenis Kelamin')
                            ->options([
                                'Laki-laki' => 'Laki-laki',
                                'Perempuan' => 'Perempuan',
                            ])
                            ->required()
                            ->placeholder('Pilih jenis kelamin'),
                        Forms\Components\Select::make('agama')
                            ->label('Agama')
                            ->options([
                                'Islam' => 'Islam',
                                'Kristen Protestan' => 'Kristen Protestan',
                                'Kristen Katolik' => 'Kristen Katolik',
                                'Hindu' => 'Hindu',
                                'Buddha' => 'Buddha',
                                'Konghucu' => 'Konghucu',
                            ])
                            ->required()
                            ->placeholder('Pilih agama'),
                        Forms\Components\Select::make('status_perkawinan')
                            ->label('Status Perkawinan')
                            ->options([
                                'Belum Kawin' => 'Belum Kawin',
                                'Kawin' => 'Kawin',
                                'Cerai Hidup' => 'Cerai Hidup',
                                'Cerai Mati' => 'Cerai Mati',
                            ])
                            ->required()
                            ->placeholder('Pilih status perkawinan'),
                        Forms\Components\TextInput::make('pekerjaan')
                            ->label('Pekerjaan')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Mahasiswa, Karyawan Swasta'),
                        Forms\Components\Textarea::make('alamat')
                            ->label('Alamat Sesuai KTP')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Contoh: Jl. Merdeka No. 1, RT 001 RW 002, Desa Raksajaya'),
                        Forms\Components\TextInput::make('rt')
                            ->label('RT')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3)
                            ->placeholder('Contoh: 001'),
                        Forms\Components\TextInput::make('rw')
                            ->label('RW')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3)
                            ->placeholder('Contoh: 002'),
                    ]),

                Forms\Components\Section::make('Data Tambahan SKCK')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('riwayat_pendidikan_terakhir')
                            ->label('Pendidikan Terakhir')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: SMA/SMK, Sarjana'),
                        Forms\Components\TextInput::make('riwayat_pekerjaan')
                            ->label('Riwayat Pekerjaan (Opsional)')
                            ->nullable()
                            ->maxLength(255)
                            ->placeholder('Contoh: Karyawan PT ABC (2020-2023)'),
                        Forms\Components\TextInput::make('kewarganegaraan')
                            ->label('Kewarganegaraan')
                            ->required()
                            ->default('WNI')
                            ->maxLength(255)
                            ->placeholder('Contoh: WNI'),
                        Forms\Components\TextInput::make('nama_ayah')
                            ->label('Nama Ayah Kandung')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama lengkap ayah'),
                        Forms\Components\TextInput::make('nama_ibu')
                            ->label('Nama Ibu Kandung')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama lengkap ibu'),
                        Forms\Components\TextInput::make('nama_pasangan')
                            ->label('Nama Suami/Istri (Opsional)')
                            ->nullable()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama suami/istri jika sudah menikah'),
                        Forms\Components\Textarea::make('alamat_sekarang')
                            ->label('Alamat Sekarang (Jika Berbeda)')
                            ->nullable()
                            ->rows(2)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Alamat domisili saat ini jika berbeda dengan KTP'),
                        Forms\Components\Textarea::make('alamat_domisili_saat_ini')
                            ->label('Alamat Domisili Saat Ini (untuk SKCK)')
                            ->required()
                            ->rows(2)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Alamat lengkap domisili saat ini yang akan dicantumkan di SKCK'),
                    ]),

                Forms\Components\Section::make('Dokumen Pendukung')
                    ->columns(2)
                    ->schema([
                        Forms\Components\FileUpload::make('foto_ktp_sim_path')
                            ->label('Foto KTP / SIM Pemohon')
                            ->acceptedFileTypes(['image/*', 'application/pdf'])
                            ->disk('public')
                            ->directory('skck_dokumen/foto_ktp_sim')
                            ->required()
                            ->helperText('Unggah foto KTP atau SIM pemohon.'),
                        Forms\Components\FileUpload::make('foto_kartu_keluarga_path')
                            ->label('Foto Kartu Keluarga (KK) Pemohon')
                            ->acceptedFileTypes(['image/*', 'application/pdf'])
                            ->disk('public')
                            ->directory('skck_dokumen/foto_kk')
                            ->required()
                            ->helperText('Unggah foto Kartu Keluarga pemohon.'),
                        Forms\Components\FileUpload::make('file_akta_lahir_ijazah_path')
                            ->label('File Akta Lahir / Ijazah Terakhir')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('skck_dokumen/akta_ijazah')
                            ->required()
                            ->helperText('Unggah file Akta Kelahiran atau Ijazah terakhir (format PDF/Gambar).'),
                        Forms\Components\FileUpload::make('pas_foto_path')
                            ->label('Pas Foto 4x6 (Optional)')
                            ->image()
                            ->disk('public')
                            ->directory('skck_dokumen/pas_foto')
                            ->nullable()
                            ->helperText('Unggah pas foto berwarna 4x6 (jika diperlukan).'),
                        Forms\Components\FileUpload::make('file_surat_pengantar_path')
                            ->label('File Surat Pengantar RT/RW (Optional)')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('skck_dokumen/surat_pengantar')
                            ->nullable()
                            ->helperText('Unggah surat pengantar dari RT/RW jika ada (format PDF/Gambar).'),
                    ]),

                // ----- PLACEHOLDER UNTUK LINK UNDUH DI HALAMAN EDIT -----
                Forms\Components\Section::make('Link Dokumen Terunggah')
                    ->description('Klik link di bawah untuk melihat atau mengunduh dokumen yang telah diunggah.')
                    ->visibleOn('edit') // Hanya tampil di halaman edit
                    ->columns(2)
                    ->schema([
                        Forms\Components\Placeholder::make('download_foto_ktp_sim_placeholder')
                            ->label('Foto KTP / SIM')
                            ->content(function (?SuratKeteranganSkck $record) {
                                if ($record && $record->foto_ktp_sim_path) {
                                    $url = Storage::url($record->foto_ktp_sim_path);
                                    return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Foto KTP / SIM</a>");
                                }
                                return 'Belum ada file KTP / SIM.';
                            }),
                        Forms\Components\Placeholder::make('download_foto_kartu_keluarga_placeholder')
                            ->label('Foto Kartu Keluarga (KK)')
                            ->content(function (?SuratKeteranganSkck $record) {
                                if ($record && $record->foto_kartu_keluarga_path) {
                                    $url = Storage::url($record->foto_kartu_keluarga_path);
                                    return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Foto Kartu Keluarga</a>");
                                }
                                return 'Belum ada file Kartu Keluarga.';
                            }),
                        Forms\Components\Placeholder::make('download_file_akta_lahir_ijazah_placeholder')
                            ->label('File Akta Lahir / Ijazah Terakhir')
                            ->content(function (?SuratKeteranganSkck $record) {
                                if ($record && $record->file_akta_lahir_ijazah_path) {
                                    $url = Storage::url($record->file_akta_lahir_ijazah_path);
                                    return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Akta Lahir / Ijazah</a>");
                                }
                                return 'Belum ada file Akta Lahir / Ijazah.';
                            }),
                        Forms\Components\Placeholder::make('download_pas_foto_placeholder')
                            ->label('Pas Foto 4x6')
                            ->content(function (?SuratKeteranganSkck $record) {
                                if ($record && $record->pas_foto_path) {
                                    $url = Storage::url($record->pas_foto_path);
                                    return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Pas Foto</a>");
                                }
                                return 'Belum ada file Pas Foto.';
                            }),
                        Forms\Components\Placeholder::make('download_file_surat_pengantar_placeholder')
                            ->label('File Surat Pengantar RT/RW')
                            ->content(function (?SuratKeteranganSkck $record) {
                                if ($record && $record->file_surat_pengantar_path) {
                                    $url = Storage::url($record->file_surat_pengantar_path);
                                    return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Surat Pengantar RT/RW</a>");
                                }
                                return 'Belum ada file Surat Pengantar.';
                            }),
                    ]),

                Forms\Components\Section::make('Detail Surat')
                    ->columns(1)
                    ->schema([
                        Forms\Components\Textarea::make('keperluan')
                            ->label('Keperluan Pembuatan SKCK')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->placeholder('Contoh: Melamar pekerjaan, Pendaftaran CPNS/Polri/TNI, Pendaftaran sekolah'),
                        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\DatePicker::make('tanggal_dikeluarkan')
                            ->label('Tanggal Surat Dibuat')
                            ->required()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal surat dibuat'),
                    ]),

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

                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'),

                Forms\Components\Placeholder::make('file_skck_surat')
                    ->label('File Surat Keterangan SKCK')
                    ->content(function (?SuratKeteranganSkck $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 SKCK</a>");
                        }
                        return 'Belum ada file surat SKCK.';
                    })
                    ->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_lengkap')
                    ->label('Nama Lengkap')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nik')
                    ->label('NIK')
                    ->default('-')
                    ->searchable(),
                Tables\Columns\TextColumn::make('keperluan')
                    ->label('Keperluan')
                    ->limit(50)
                    ->wrap(),
                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 (SuratKeteranganSkck $record) {
                            if (!$record->file_path) {
                                $html = view('pdf.surat_keterangan_skck', compact('record'))->render();
                                $pdf = Pdf::loadHtml($html);
                                $filePath = 'surat_keterangan_skck/' . 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_keterangan_skck', 'nomor_surat', ignoreRecord: true)
                                ->placeholder('Contoh: 476/SKCK.001/DS.RKJ/V/2025'),
                            Forms\Components\FileUpload::make('signed_pdf')
                                ->label('Unggah PDF Bertanda Tangan')
                                ->acceptedFileTypes(['application/pdf'])
                                ->directory('surat_keterangan_skck')
                                ->required(),
                        ])
                        ->action(function (array $data, SuratKeteranganSkck $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 Keterangan SKCK berhasil disetujui.')
                                    ->success()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratKeteranganSkck $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),
                        ])
                        ->action(function (array $data, SuratKeteranganSkck $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 Keterangan SKCK berhasil ditolak.')
                                    ->danger()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratKeteranganSkck $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\ListSuratKeteranganSkcks::route('/'),
            'create' => Pages\CreateSuratKeteranganSkck::route('/create'),
            'edit' => Pages\EditSuratKeteranganSkck::route('/{record}/edit'),
        ];
    }

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

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

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