<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SuratKeteranganKehilanganResource\Pages;
use App\Models\SuratKeteranganKehilangan;
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 SuratKeteranganKehilanganResource extends Resource
{
    protected static ?string $model = SuratKeteranganKehilangan::class;

    protected static ?string $navigationIcon = 'heroicon-o-document-magnifying-glass'; // Contoh ikon
    protected static ?string $navigationGroup = 'Kelola Surat';
    protected static ?string $navigationLabel = 'Surat Keterangan Kehilangan';
    protected static ?int $navigationSort = 10; // Sesuaikan urutan navigasi

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Data Pemohon (Pelapor)')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('nama_pemohon')
                            ->label('Nama Lengkap Pemohon')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama lengkap pemohon'),
                        Forms\Components\TextInput::make('nik_pemohon')
                            ->label('NIK Pemohon')
                            ->numeric()
                            ->placeholder('Masukkan NIK pemohon (Jika ingat)'),
                        Forms\Components\TextInput::make('nomor_kartu_keluarga_pemohon')
                            ->label('Nomor Kartu Keluarga (KK) Pemohon')
                            ->numeric()
                            ->placeholder('Masukkan Nomor KK (Jika ingat)'),
                        Forms\Components\TextInput::make('tempat_lahir_pemohon')
                            ->label('Tempat Lahir Pemohon')
                            ->nullable()
                            ->maxLength(255)
                            ->placeholder('Contoh: Tasikmalaya'),
                        Forms\Components\DatePicker::make('tanggal_lahir_pemohon')
                            ->label('Tanggal Lahir Pemohon')
                            ->nullable()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal lahir'),
                        Forms\Components\Select::make('jenis_kelamin_pemohon')
                            ->label('Jenis Kelamin Pemohon')
                            ->options([
                                'Laki-laki' => 'Laki-laki',
                                'Perempuan' => 'Perempuan',
                            ])
                            ->nullable()
                            ->placeholder('Pilih jenis kelamin'),
                        Forms\Components\Select::make('agama_pemohon')
                            ->label('Agama Pemohon')
                            ->options([
                                'Islam' => 'Islam',
                                'Kristen Protestan' => 'Kristen Protestan',
                                'Kristen Katolik' => 'Kristen Katolik',
                                'Hindu' => 'Hindu',
                                'Buddha' => 'Buddha',
                                'Konghucu' => 'Konghucu',
                            ])
                            ->nullable()
                            ->placeholder('Pilih agama'),
                        Forms\Components\TextInput::make('pekerjaan_pemohon')
                            ->label('Pekerjaan Pemohon')
                            ->nullable()
                            ->maxLength(255)
                            ->placeholder('Contoh: Pelajar, Karyawan Swasta'),
                        Forms\Components\Textarea::make('alamat_pemohon')
                            ->label('Alamat Lengkap Pemohon')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Contoh: Jl. Pahlawan No. 15, RT 002 RW 003, Desa Raksajaya'),
                        Forms\Components\TextInput::make('rt_pemohon')
                            ->label('RT')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3)
                            ->placeholder('Contoh: 002'),
                        Forms\Components\TextInput::make('rw_pemohon')
                            ->label('RW')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3)
                            ->placeholder('Contoh: 003'),
                    ]),

                Forms\Components\Section::make('Data Barang/Dokumen yang Hilang')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('jenis_barang_hilang')
                            ->label('Jenis Barang/Dokumen yang Hilang')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: KTP, Kartu Keluarga, STNK Motor, Buku Tabungan'),
                        Forms\Components\TextInput::make('nomor_dokumen_hilang')
                            ->label('Nomor Dokumen yang Hilang (Opsional)')
                            ->nullable()
                            ->maxLength(255)
                            ->placeholder('Masukkan nomor dokumen jika ada (contoh: NIK KTP, Nomor KK, Nomor Plat STNK)'),
                        Forms\Components\Textarea::make('uraian_barang_hilang')
                            ->label('Uraian Singkat Barang/Dokumen Hilang')
                            ->required()
                            ->rows(2)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Contoh: KTP atas nama (Nama Lengkap) dengan NIK (Nomor NIK).'),
                        Forms\Components\DatePicker::make('tanggal_hilang')
                            ->label('Tanggal Kejadian Hilang')
                            ->required()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal kejadian kehilangan'),
                        Forms\Components\TextInput::make('tempat_hilang')
                            ->label('Tempat Kejadian Hilang')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Di pasar desa, di jalan depan rumah'),
                        Forms\Components\Textarea::make('kronologi_hilang')
                            ->label('Kronologi Singkat Kejadian Hilang')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Contoh: Pada tanggal (tanggal hilang), saya sedang (aktivitas), kemudian saya menyadari bahwa (barang/dokumen) saya sudah tidak ada.'),
                    ]),

                Forms\Components\Section::make('Dokumen Pendukung')
                    ->columns(2)
                    ->schema([
                        Forms\Components\FileUpload::make('foto_ktp_path')
                            ->label('Foto KTP Pemohon (Optional)')
                            ->image()
                            ->disk('public')
                            ->directory('skh_dokumen/foto_ktp')
                            ->helperText('Unggah foto KTP pemohon.'),
                        Forms\Components\FileUpload::make('foto_kartu_keluarga_path')
                            ->label('Foto Kartu Keluarga (KK) Pemohon (Optional)')
                            ->acceptedFileTypes(['image/*', 'application/pdf'])
                            ->disk('public')
                            ->directory('skh_dokumen/foto_kk')
                            ->helperText('Unggah foto Kartu Keluarga pemohon.'),
                        Forms\Components\FileUpload::make('file_surat_pengantar_path')
                            ->label('File Surat Pengantar RT/RW (Optional)')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('skh_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(1) // Menggunakan 1 kolom agar tampil flex column
                    ->schema([
                        Forms\Components\Placeholder::make('download_foto_ktp_placeholder')
                            ->label('Foto KTP Pemohon')
                            ->content(function (?SuratKeteranganKehilangan $record) {
                                if ($record && $record->foto_ktp_path) {
                                    $url = Storage::url($record->foto_ktp_path);
                                    return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Unduh/Lihat Foto KTP</a>");
                                }
                                return 'Belum ada foto KTP yang diunggah.';
                            }),
                        Forms\Components\Placeholder::make('download_foto_kartu_keluarga_placeholder')
                            ->label('Foto Kartu Keluarga (KK) Pemohon')
                            ->content(function (?SuratKeteranganKehilangan $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 foto Kartu Keluarga yang diunggah.';
                            }),
                        Forms\Components\Placeholder::make('download_file_surat_pengantar_placeholder')
                            ->label('File Surat Pengantar RT/RW')
                            ->content(function (?SuratKeteranganKehilangan $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</a>");
                                }
                                return 'Belum ada surat pengantar yang diunggah.';
                            })
                    ]),

                Forms\Components\Section::make('Detail Surat')
                    ->columns(1)
                    ->schema([
                        Forms\Components\Textarea::make('keperluan')
                            ->label('Keperluan Pembuatan Surat')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->placeholder('Contoh: Untuk pengurusan ulang KTP di Disdukcapil'),
                        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_skh_surat')
                    ->label('File Surat Keterangan Kehilangan')
                    ->content(function (?SuratKeteranganKehilangan $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 SKH</a>");
                        }
                        return 'Belum ada file surat SKH.';
                    })
                    ->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_pemohon')
                    ->label('Nama Pemohon')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nik_pemohon')
                    ->label('NIK Pemohon')
                    ->default('-')
                    ->searchable(),
                Tables\Columns\TextColumn::make('jenis_barang_hilang')
                    ->label('Barang Hilang')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('tanggal_hilang')
                    ->label('Tgl. Hilang')
                    ->date('d M Y')
                    ->sortable(),
                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 (SuratKeteranganKehilangan $record) {
                            if (!$record->file_path) {
                                $html = view('pdf.surat_keterangan_kehilangan', compact('record'))->render();
                                $pdf = Pdf::loadHtml($html);
                                $filePath = 'surat_keterangan_kehilangan/' . 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_kehilangan', 'nomor_surat', ignoreRecord: true)
                                ->placeholder('Contoh: 472/SKH.001/DS.RKJ/V/2025'),
                            Forms\Components\FileUpload::make('signed_pdf')
                                ->label('Unggah PDF Bertanda Tangan')
                                ->acceptedFileTypes(['application/pdf'])
                                ->directory('surat_keterangan_kehilangan')
                                ->required(),
                        ])
                        ->action(function (array $data, SuratKeteranganKehilangan $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 Kehilangan berhasil disetujui.')
                                    ->success()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratKeteranganKehilangan $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, SuratKeteranganKehilangan $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 Kehilangan berhasil ditolak.')
                                    ->danger()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratKeteranganKehilangan $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\ListSuratKeteranganKehilangans::route('/'),
            'create' => Pages\CreateSuratKeteranganKehilangan::route('/create'),
            'edit' => Pages\EditSuratKeteranganKehilangan::route('/{record}/edit'),
        ];
    }

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

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

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