<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SuratKeteranganUsahaResource\Pages;
use App\Models\SuratKeteranganUsaha;
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; // Digunakan jika ada formatting uang atau sejenisnya
use Illuminate\Support\HtmlString;

class SuratKeteranganUsahaResource extends Resource
{
    protected static ?string $model = SuratKeteranganUsaha::class;

    protected static ?string $navigationIcon = 'heroicon-o-building-storefront'; // Contoh ikon
    protected static ?string $navigationGroup = 'Kelola Surat';
    protected static ?string $navigationLabel = 'Surat Keterangan Usaha';
    protected static ?int $navigationSort = 7; // Sesuaikan urutan navigasi

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Usaha')
                    ->columns(2)
                    ->schema([
                        Forms\Components\TextInput::make('nama_usaha')
                            ->label('Nama Usaha')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Warung Makmur Jaya'),
                        Forms\Components\TextInput::make('jenis_usaha')
                            ->label('Jenis Usaha')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Contoh: Warung Sembako, Bengkel Motor'),
                        Forms\Components\Textarea::make('alamat_usaha')
                            ->label('Alamat Lengkap Usaha')
                            ->required()
                            ->rows(3)
                            ->maxLength(65535)
                            ->columnSpanFull()
                            ->placeholder('Contoh: Jl. Raya Desa No. 10, RT 001 RW 002, Desa Raksajaya'),
                        Forms\Components\DatePicker::make('tanggal_mulai_usaha')
                            ->label('Tanggal Mulai Usaha')
                            ->required()
                            ->maxDate(now())
                            ->placeholder('Pilih tanggal usaha mulai beroperasi'),
                        Forms\Components\FileUpload::make('foto_usaha_path')
                            ->label('Foto Lokasi Usaha (Optional)')
                            ->image()
                            ->disk('public')
                            ->directory('sku_dokumen/foto_usaha')
                            ->nullable()
                            ->helperText('Unggah foto tampak depan usaha Anda.'),
                    ]),

                Forms\Components\Section::make('Informasi Pemohon (Pemilik Usaha)')
                    ->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()
                            ->numeric()
                            ->placeholder('Masukkan NIK pemohon (16 digit)'),
                        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()
                            ->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: Pedagang / Wirausaha'),
                        Forms\Components\TextInput::make('alamat_domisili_pemohon')
                            ->label('Alamat Domisili Pemohon')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('Masukkan alamat domisili lengkap pemohon'),
                        Forms\Components\TextInput::make('rt_pemohon')
                            ->label('RT Domisili')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3)
                            ->placeholder('Contoh: 001'),
                        Forms\Components\TextInput::make('rw_pemohon')
                            ->label('RW Domisili')
                            ->nullable()
                            ->numeric()
                            ->maxLength(3)
                            ->placeholder('Contoh: 005'),
                        Forms\Components\TextInput::make('nomor_kartu_keluarga_pemohon')
                            ->label('Nomor Kartu Keluarga (KK) Pemohon')
                            ->required()
                            ->numeric()
                            ->placeholder('Masukkan Nomor KK'),
                    ]),

                Forms\Components\Section::make('Dokumen Pendukung')
                    ->columns(2)
                    ->schema([
                        Forms\Components\FileUpload::make('foto_ktp_path')
                            ->label('Foto KTP Pemohon')
                            ->image()
                            ->disk('public')
                            ->directory('sku_dokumen/foto_ktp')
                            ->required()
                            ->helperText('Unggah foto KTP pemohon.'),
                        Forms\Components\FileUpload::make('foto_kartu_keluarga_path')
                            ->label('Foto Kartu Keluarga (KK) Pemohon')
                            ->acceptedFileTypes(['image/*', 'application/pdf'])
                            ->disk('public')
                            ->directory('sku_dokumen/foto_kk')
                            ->required()
                            ->helperText('Unggah foto Kartu Keluarga pemohon.'),
                        Forms\Components\FileUpload::make('file_surat_pengantar_path')
                            ->label('File Surat Pengantar (Optional)')
                            ->acceptedFileTypes(['application/pdf', 'image/*'])
                            ->disk('public')
                            ->directory('sku_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_usaha')
                            ->label('Foto Lokasi Usaha')
                            ->content(function (?SuratKeteranganUsaha $record) {
                                if ($record && $record->foto_usaha_path) {
                                    $url = Storage::url($record->foto_usaha_path);
                                    return new HtmlString("<a href='{$url}' target='_blank' class='filament-link text-primary-600 hover:text-primary-500'>Lihat/Unduh Foto Usaha</a>");
                                }
                                return 'Belum ada foto lokasi usaha.';
                            })
                            ->visible(fn (?SuratKeteranganUsaha $record): bool => (bool) $record->foto_usaha_path),

                        Forms\Components\Placeholder::make('download_foto_ktp')
                            ->label('Foto KTP Pemohon')
                            ->content(function (?SuratKeteranganUsaha $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'>Lihat/Unduh Foto KTP</a>");
                                }
                                return 'Belum ada foto KTP pemohon.';
                            })
                            ->visible(fn (?SuratKeteranganUsaha $record): bool => (bool) $record->foto_ktp_path),

                        Forms\Components\Placeholder::make('download_foto_kartu_keluarga')
                            ->label('Foto Kartu Keluarga (KK) Pemohon')
                            ->content(function (?SuratKeteranganUsaha $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'>Lihat/Unduh Foto KK</a>");
                                }
                                return 'Belum ada foto Kartu Keluarga pemohon.';
                            })
                            ->visible(fn (?SuratKeteranganUsaha $record): bool => (bool) $record->foto_kartu_keluarga_path),

                        Forms\Components\Placeholder::make('download_file_surat_pengantar')
                            ->label('File Surat Pengantar')
                            ->content(function (?SuratKeteranganUsaha $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'>Lihat/Unduh Surat Pengantar</a>");
                                }
                                return 'Belum ada file surat pengantar.';
                            })
                            ->visible(fn (?SuratKeteranganUsaha $record): bool => (bool) $record->file_surat_pengantar_path),
                    ]),

                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 mengajukan pinjaman bank / legalitas usaha'),
                        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_sku_surat')
                    ->label('File Surat Keterangan Usaha')
                    ->content(function (?SuratKeteranganUsaha $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 SKU</a>");
                        }
                        return 'Belum ada file surat SKU.';
                    })
                    ->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_usaha')
                    ->label('Nama Usaha')
                    ->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('jenis_usaha')
                    ->label('Jenis Usaha')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('tanggal_mulai_usaha')
                    ->label('Mulai Usaha')
                    ->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 (SuratKeteranganUsaha $record) {
                            if (!$record->file_path) {
                                $html = view('pdf.surat_keterangan_usaha', compact('record'))->render();
                                $pdf = Pdf::loadHtml($html);
                                $filePath = 'surat_keterangan_usaha/' . 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_usaha', 'nomor_surat', ignoreRecord: true)
                                ->placeholder('Contoh: 510/SKU.001/DS.RKJ/V/2025'),
                            Forms\Components\FileUpload::make('signed_pdf')
                                ->label('Unggah PDF Bertanda Tangan')
                                ->acceptedFileTypes(['application/pdf'])
                                ->directory('surat_keterangan_usaha')
                                ->required(),
                        ])
                        ->action(function (array $data, SuratKeteranganUsaha $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 Usaha berhasil disetujui.')
                                    ->success()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratKeteranganUsaha $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, SuratKeteranganUsaha $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 Usaha berhasil ditolak.')
                                    ->danger()
                                    ->send();
                            });
                        })
                        ->visible(fn (SuratKeteranganUsaha $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\ListSuratKeteranganUsahas::route('/'),
            'create' => Pages\CreateSuratKeteranganUsaha::route('/create'),
            'edit' => Pages\EditSuratKeteranganUsaha::route('/{record}/edit'),
        ];
    }

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

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

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