<?php

namespace App\Filament\Resources;

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

    protected static ?string $navigationIcon = 'heroicon-o-archive-box-x-mark';
    protected static ?string $navigationGroup = 'Kelola Surat';
    protected static ?string $navigationLabel = 'Surat Kematian';
    protected static ?int $navigationSort = 2;
    protected static bool $shouldRegisterNavigation = false;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Almarhum/Almarhumah')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('nama_lengkap_almarhum')
                            ->label('Nama Lengkap Almarhum/Almarhumah')
                            ->placeholder('Masukkan nama lengkap almarhum/almarhumah')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('nik_almarhum')
                            ->label('NIK Almarhum/Almarhumah')
                            ->placeholder('Masukkan NIK almarhum/almarhumah (jika ada)')
                            ->numeric()
                            ->maxLength(16),
                        Forms\Components\DatePicker::make('tanggal_lahir_almarhum')
                            ->label('Tanggal Lahir Almarhum/Almarhumah')
                            ->placeholder('Pilih tanggal lahir')
                            ->maxDate(now()),
                        Forms\Components\TextInput::make('tempat_lahir_almarhum')
                            ->label('Tempat Lahir Almarhum/Almarhumah')
                            ->placeholder('Contoh: Bogor, Jakarta'),
                        Forms\Components\Select::make('jenis_kelamin_almarhum')
                            ->label('Jenis Kelamin')
                            ->placeholder('Pilih jenis kelamin')
                            ->options([
                                'Laki-laki' => 'Laki-laki',
                                'Perempuan' => 'Perempuan',
                            ])
                            ->required(),
                        Forms\Components\Select::make('agama_almarhum')
                            ->label('Agama')
                            ->placeholder('Pilih agama')
                            ->options([
                                'Islam' => 'Islam',
                                'Kristen Protestan' => 'Kristen Protestan',
                                'Kristen Katolik' => 'Kristen Katolik',
                                'Hindu' => 'Hindu',
                                'Buddha' => 'Buddha',
                                'Konghucu' => 'Konghucu',
                            ]),
                        Forms\Components\TextInput::make('pekerjaan_almarhum')
                            ->label('Pekerjaan')
                            ->placeholder('Contoh: Petani, Ibu Rumah Tangga'),
                        Forms\Components\Textarea::make('alamat_almarhum')
                            ->label('Alamat Lengkap')
                            ->placeholder('Masukkan alamat lengkap (Jl., RT/RW, Desa, Kecamatan, Kabupaten)')
                            ->rows(3)
                            ->columnSpanFull(),
                    ]),

                Forms\Components\Section::make('Detail Kematian')
                    ->columns(2)
                    ->schema([
                        Forms\Components\DatePicker::make('tanggal_kematian')
                            ->label('Tanggal Kematian')
                            ->placeholder('Pilih tanggal kematian')
                            ->required()
                            ->maxDate(now()),
                        Forms\Components\TimePicker::make('waktu_kematian')
                            ->label('Waktu Kematian')
                            ->placeholder('Opsional (Contoh: 14:30)')
                            ->seconds(false),
                        Forms\Components\TextInput::make('tempat_kematian')
                            ->label('Tempat Kematian')
                            ->placeholder('Contoh: Rumah, RSUD, Puskesmas'),
                        Forms\Components\TextInput::make('penyebab_kematian')
                            ->label('Penyebab Kematian')
                            ->placeholder('Contoh: Sakit, Kecelakaan, Usia Lanjut'),
                        Forms\Components\TextInput::make('yang_menerangkan')
                            ->label('Yang Menerangkan Kematian')
                            ->placeholder('Contoh: Dokter, Bidan, Saksi'),
                    ]),

                Forms\Components\Section::make('Informasi Pelapor')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('nama_pelapor')
                            ->label('Nama Pelapor')
                            ->placeholder('Masukkan nama lengkap pelapor')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('nik_pelapor')
                            ->label('NIK Pelapor')
                            ->placeholder('Masukkan NIK pelapor')
                            ->required()
                            ->numeric()
                            ->maxLength(16),
                        Forms\Components\TextInput::make('hubungan_pelapor_dengan_almarhum')
                            ->label('Hubungan Pelapor dengan Almarhum/Almarhumah')
                            ->placeholder('Contoh: Istri, Anak, Kakak, Tetangga')
                            ->required()
                            ->maxLength(255),
                    ]),

                // Field untuk admin (Nomor Surat, Status, Catatan Penolakan, File Surat)
                Forms\Components\TextInput::make('nomor_surat')
                    ->label('Nomor Surat')
                    ->placeholder('Nomor surat akan dibuat otomatis saat disetujui.')
                    ->disabledOn('create')
                    ->helperText('Nomor surat akan dibuat otomatis saat disetujui oleh admin desa.'),

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

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

                Forms\Components\Placeholder::make('file_surat')
                    ->label('File Surat')
                    ->content(function (?SuratKematian $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 Kematian</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_lengkap_almarhum') // Ambil dari field baru
                    ->label('Nama Almarhum')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nik_almarhum') // Ambil dari field baru
                    ->label('NIK Almarhum')
                    ->placeholder('-')
                    ->searchable(),
                Tables\Columns\TextColumn::make('tanggal_kematian')
                    ->label('Tgl Kematian')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('waktu_kematian')
                    ->label('Waktu')
                    ->time()
                    ->sortable(),
                Tables\Columns\TextColumn::make('penyebab_kematian')
                    ->label('Penyebab')
                    ->placeholder('-')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nama_pelapor')
                    ->label('Pelapor')
                    ->sortable()
                    ->searchable(),
                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 (SuratKematian $record) {
                            if (!$record->file_path) {
                                $html = view('pdf.surat_kematian', compact('record'))->render();
                                $pdf = Pdf::loadHtml($html);
                                $filePath = 'surat_kematian/' . 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_kematian', 'nomor_surat', ignoreRecord: true)
                                ->placeholder('Contoh: 470/SK.001/DS.RKJ/V/2025'),
                            Forms\Components\FileUpload::make('signed_pdf')
                                ->label('Unggah PDF Bertanda Tangan')
                                ->acceptedFileTypes(['application/pdf'])
                                ->directory('surat_kematian')
                                ->required(),
                        ])
                        ->action(function (array $data, SuratKematian $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 Kematian berhasil disetujui.')
                                    ->success()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratKematian $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('Masukkan alasan mengapa surat ini ditolak.'),
                        ])
                        ->action(function (array $data, SuratKematian $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 Kematian berhasil ditolak.')
                                    ->danger()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratKematian $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\ListSuratKematians::route('/'),
            'create' => Pages\CreateSuratKematian::route('/create'),
            'edit' => Pages\EditSuratKematian::route('/{record}/edit'),
        ];
    }

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

    public static function afterCreate(SuratKematian $record): void
    {
        try {
            $html = view('pdf.surat_kematian', compact('record'))->render();
            $pdf = Pdf::loadHtml($html);
            $filePath = 'surat_kematian/' . 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);
        }
    }
}