<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SuratPindahResource\Pages;
use App\Models\SuratPindah;
use App\Models\User; // Pastikan User diimport
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 SuratPindahResource extends Resource
{
    protected static ?string $model = SuratPindah::class;
    protected static ?string $navigationIcon = 'heroicon-o-arrow-up-on-square';
    protected static ?string $navigationGroup = 'Kelola Surat';
    protected static ?string $navigationLabel = 'Surat Pindah';
    protected static ?int $navigationSort = 4;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Pemohon Pindah')
                    ->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')
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->numeric()
                            ->placeholder('Masukkan NIK pemohon'),
                        Forms\Components\TextInput::make('tempat_lahir_pemohon')
                            ->label('Tempat Lahir Pemohon')
                            ->nullable()
                            ->maxLength(255)
                            ->placeholder('Contoh: Bandung'),
                        Forms\Components\DatePicker::make('tanggal_lahir_pemohon')
                            ->label('Tanggal Lahir Pemohon')
                            ->nullable()
                            ->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') // Ganti menjadi Select
                            ->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: Petani / Karyawan Swasta'),
                        Forms\Components\TextInput::make('alamat_asal_pemohon')
                            ->label('Alamat Asal Pemohon')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan alamat lengkap asal'),
                        Forms\Components\TextInput::make('rt_asal_pemohon')
                            ->label('RT Asal Pemohon')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3) // Menggunakan maxLength, bukan length
                            ->placeholder('Contoh: 001'),
                        Forms\Components\TextInput::make('rw_asal_pemohon')
                            ->label('RW Asal Pemohon')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3) // Menggunakan maxLength, bukan length
                            ->placeholder('Contoh: 005'),
                        Forms\Components\DatePicker::make('tanggal_pindah')
                            ->label('Tanggal Pindah')
                            ->required()
                            ->placeholder('Pilih tanggal pindah'),
                        Forms\Components\Textarea::make('alasan_pindah')
                            ->label('Alasan Pindah')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->placeholder('Masukkan alasan pindah'),
                    ]),

                Forms\Components\Section::make('Alamat Tujuan Pindah')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('alamat_tujuan')
                            ->label('Alamat Lengkap Tujuan')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan alamat lengkap tujuan'),
                        Forms\Components\TextInput::make('rt_tujuan')
                            ->label('RT Tujuan')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3) // Menggunakan maxLength, bukan length
                            ->placeholder('Contoh: 002'),
                        Forms\Components\TextInput::make('rw_tujuan')
                            ->label('RW Tujuan')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3) // Menggunakan maxLength, bukan length
                            ->placeholder('Contoh: 008'),
                        Forms\Components\TextInput::make('dusun_tujuan')
                            ->label('Dusun Tujuan')
                            ->nullable()
                            ->maxLength(255)
                            ->placeholder('Contoh: Sindang Jaya'),
                        Forms\Components\TextInput::make('desa_tujuan')
                            ->label('Desa/Kelurahan Tujuan')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama desa/kelurahan tujuan'),
                        Forms\Components\TextInput::make('kecamatan_tujuan')
                            ->label('Kecamatan Tujuan')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama kecamatan tujuan'),
                        Forms\Components\TextInput::make('kabupaten_tujuan')
                            ->label('Kabupaten/Kota Tujuan')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama kabupaten/kota tujuan'),
                        Forms\Components\TextInput::make('provinsi_tujuan')
                            ->label('Provinsi Tujuan')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan nama provinsi tujuan'),
                    ]),

                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',
                    ])
                    ->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_surat')
                    ->label('File Surat')
                    ->content(function (?SuratPindah $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 Pindah</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_pemohon')
                    ->label('Nama Pemohon')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('nik_pemohon')
                    ->label('NIK Pemohon')
                    ->default('-'),
                Tables\Columns\TextColumn::make('tanggal_pindah')
                    ->label('Tanggal Pindah')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('alamat_tujuan')
                    ->label('Alamat Tujuan')
                    ->wrap()
                    ->limit(50),
                Tables\Columns\TextColumn::make('desa_tujuan')
                    ->label('Desa Tujuan'),
                Tables\Columns\TextColumn::make('kecamatan_tujuan')
                    ->label('Kecamatan Tujuan'),
                Tables\Columns\TextColumn::make('kabupaten_tujuan')
                    ->label('Kabupaten Tujuan'),
                Tables\Columns\TextColumn::make('provinsi_tujuan')
                    ->label('Provinsi Tujuan'),
                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 (SuratPindah $record) {
                            if (!$record->file_path) {
                                $html = view('pdf.surat_pindah', compact('record'))->render();
                                $pdf = Pdf::loadHtml($html);
                                $filePath = 'surat_pindah/' . 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_pindah', '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_pindah')
                                ->required(),
                        ])
                        ->action(function (array $data, SuratPindah $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 Pindah berhasil disetujui.')
                                    ->success()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratPindah $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 penolakan surat'),
                        ])
                        ->action(function (array $data, SuratPindah $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 Pindah berhasil ditolak.')
                                    ->danger()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratPindah $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\ListSuratPindahs::route('/'),
            'create' => Pages\CreateSuratPindah::route('/create'),
            'edit' => Pages\EditSuratPindah::route('/{record}/edit'),
        ];
    }

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

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