<?php

namespace App\Filament\Resources\PendudukResource\Pages;

use App\Filament\Resources\PendudukResource;
use Filament\Actions;
use Filament\Forms;
use Filament\Resources\Pages\ListRecords;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\PendudukExport;
use App\Imports\PendudukImport;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\HtmlString;

class ListPenduduks extends ListRecords
{
    protected static string $resource = PendudukResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\Action::make('import_excel')
                ->label('Impor Data')
                ->color('gray')
                ->icon('heroicon-o-arrow-up-tray')
                ->visible(fn (): bool => Auth::user()->role !== 'kepala_desa')
                ->form([
                    // --- Tambahkan ini di awal form ---
                    Forms\Components\Placeholder::make('download_template')
                        ->content(new HtmlString(
                            'Untuk mengimpor data, harap gunakan format file Excel yang benar.<br> ' .
                            'Ini hanya mengimpor data penduduk, tidak termasuk data KK.' .
                            'Anda dapat mengunduh <a href="' . asset('templates/template_import_penduduk.xlsx') . '" download class="text-primary-600 hover:text-primary-700 font-semibold underline">contoh file Excel di sini</a>. ' .
                            '<br><br>' .
                            'Pastikan kolom NIK diformat sebagai "Teks" di Excel sebelum memasukkan data untuk menghindari kesalahan format.'
                        ))
                        ->columnSpanFull(), // Agar menempati lebar penuh form
                    // --- Akhir penambahan ---

                    Forms\Components\FileUpload::make('file')
                        ->label('Pilih File Excel (.xlsx, .xls)')
                        ->required()
                        ->acceptedFileTypes(['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'])
                        ->storeFiles(false),
                ])
                ->action(function (array $data) {
                    try {
                        Excel::import(new PendudukImport(), $data['file']);
                        Notification::make()
                            ->title('Berhasil mengimpor data!')
                            ->success()
                            ->send();
                    } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
                        $failures = $e->failures();
                        $errorMessage = 'Gagal mengimpor data. Beberapa baris tidak valid:';
                        foreach ($failures as $failure) {
                            $errorMessage .= '<br>Baris ' . $failure->row() . ': ' . implode(', ', $failure->errors());
                        }
                        Notification::make()
                            ->title('Gagal mengimpor data!')
                            ->body(new HtmlString($errorMessage))
                            ->danger()
                            ->duration(15000)
                            ->persistent()
                            ->send();
                    } catch (\Exception $e) {
                        Notification::make()
                            ->title('Terjadi kesalahan saat mengimpor data!')
                            ->body($e->getMessage())
                            ->danger()
                            ->persistent()
                            ->send();
                    }
                }),

            Actions\Action::make('export_all_excel')
                ->label('Ekspor Semua')
                ->icon('heroicon-o-arrow-down-tray')
                ->color('gray')
                ->action(fn () => Excel::download(
                    new PendudukExport(),
                    'data_penduduk_semua_' . now()->format('Ymd_His') . '.xlsx'
                )),

            Actions\CreateAction::make()->visible(fn (): bool => Auth::user()->role !== 'kepala_desa'),
        ];
    }
}