<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Exports\UsersExport;
use App\Filament\Resources\UserResource;
use App\Imports\UserImport;
use EightyNine\ExcelImport\ExcelImportAction;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ListUsers extends ListRecords
{
    protected static string $resource = UserResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('download')
                ->label('Download Template')
                ->color('primary')
                ->icon('heroicon-o-document-arrow-down')
                ->requiresConfirmation()
                ->modalHeading('Konfirmasi Download Template')
                ->modalDescription('Anda akan mendownload template Excel untuk import data pengguna. Lanjutkan?')
                ->modalSubmitActionLabel('Ya, Download')
                ->modalCancelActionLabel('Batal')
                ->action(function (): StreamedResponse {
                    return app()->call('App\Http\Controllers\TemplateController@downloadUserTemplate');
                }),
            Action::make('export')
                ->label('Export Data')
                ->color('primary')
                ->icon('heroicon-o-arrow-down-tray')
                ->action(function () {
                    $fileName = 'Export_Pengguna_' . date('Ymd_His') . '.xlsx';
                    return Excel::download(new UsersExport(), $fileName);
                })
                ->requiresConfirmation(),
            ExcelImportAction::make('import')
                ->label('Import Data')
                ->color("primary")
                ->icon('heroicon-o-arrow-up-tray')
                ->modalHeading('Import Data Pengguna')
                ->modalDescription('Hanya sheet "Data Pengguna" yang akan diproses. Pastikan format file sesuai template.')
                ->use(UserImport::class)
                ->beforeUploadField([
                    TextInput::make('default_password')
                        ->label('Default Password')
                        ->password()
                        ->revealable()
                        ->default('password123')
                        ->required(),
                    Toggle::make('update_existing')
                        ->label('Update data yang sudah ada?')
                        ->helperText('Jika diaktifkan, data dengan email yang sama akan diupdate')
                        ->default(false),
                ])
                ->uploadField(
                    fn ($field) => $field
                        ->label('File Data Pengguna')
                        ->helperText('Format: .xlsx atau .xls (CSV tidak diterima). Hanya sheet "Data Pengguna" yang diproses.')
                        ->acceptedFileTypes([
                            'application/vnd.ms-excel', 
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                        ])
                        ->required()
                )
                ->beforeImport(function (array $data) {
                    session([
                        'import_default_password' => $data['default_password'],
                        'import_update_existing' => (bool)$data['update_existing']
                    ]);
                })
                // ->afterImport(function ($result) {
                //     try {
                //         $importResults = session('import_results', [
                //             'success_count' => 0,
                //             'updated_count' => 0,
                //             'errors' => [],
                //             'processed_rows' => 0
                //         ]);

                //         if (is_array($result) && isset($result['success_count'])) {
                //             $importResults = array_merge($importResults, $result);
                //         } elseif ($result instanceof UserImport) {
                //             $importResults = array_merge($importResults, [
                //                 'success_count' => $result->getSuccessCount(),
                //                 'updated_count' => $result->getUpdatedCount(),
                //                 'errors' => $result->getErrors(),
                //                 'processed_rows' => $result->getProcessedRowsCount()
                //             ]);
                //         }

                //         $successCount = $importResults['success_count'];
                //         $updatedCount = $importResults['updated_count'];
                //         $errors = $importResults['errors'];
                //         $processedRows = $importResults['processed_rows'];

                //         session()->forget('import_results');

                //         Log::debug('Final import evaluation', [
                //             'success' => $successCount,
                //             'updated' => $updatedCount,
                //             'errors' => count($errors),
                //             'processed' => $processedRows,
                //             'has_data' => ($successCount + $updatedCount) > 0,
                //             'has_errors' => !empty($errors)
                //         ]);

                //         if (($successCount + $updatedCount) > 0) {
                //             Notification::make()
                //                 ->title('Import Berhasil')
                //                 ->body(sprintf(
                //                     "Berhasil memproses %d data (%d baru, %d diupdate)", 
                //                     $successCount + $updatedCount,
                //                     $successCount,
                //                     $updatedCount
                //                 ))
                //                 ->success()
                //                 ->send();
                //             return;
                //         }

                //         if (!empty($errors)) {
                //             Notification::make()
                //                 ->title('Import Gagal')
                //                 ->body('Terdapat error pada data yang diimport')
                //                 ->danger()
                //                 ->actions([
                //                     Action::make('viewErrors')
                //                         ->label('Lihat Error')
                //                         ->color('danger')
                //                         ->modalHeading('Daftar Error')
                //                         ->modalContent(view('filament.import-errors', [
                //                             'errors' => $errors
                //                         ]))
                //                 ])
                //                 ->send();
                //             return;
                //         }

                //         if ($processedRows > 0) {
                //             Notification::make()
                //                 ->title('Tidak Ada Data Valid')
                //                 ->body('Ditemukan data tetapi tidak ada yang memenuhi kriteria valid')
                //                 ->warning()
                //                 ->send();
                //         } else {
                //             Notification::make()
                //                 ->title('Tidak Ada Data Diproses')
                //                 ->body('Tidak ditemukan data yang valid untuk diimport')
                //                 ->warning()
                //                 ->send();
                //         }
                //     } catch (\Exception $e) {
                //         Log::error('Import notification error: '.$e->getMessage()."\n".$e->getTraceAsString());
                //         Notification::make()
                //             ->title('Error Sistem')
                //             ->body('Terjadi kesalahan saat memproses import. Silakan cek log untuk detailnya.')
                //             ->danger()
                //             ->send();
                //     }
                // }),
                ->afterImport(function ($result) {
                    try {
                        $importResults = session('import_results', [
                            'success_count' => 0,
                            'updated_count' => 0,
                            'errors' => [],
                            'processed_rows' => 0
                        ]);

                        if (is_array($result) && isset($result['success_count'])) {
                            $importResults = array_merge($importResults, $result);
                        } elseif ($result instanceof UserImport) {
                            $importResults = array_merge($importResults, [
                                'success_count' => $result->getSuccessCount(),
                                'updated_count' => $result->getUpdatedCount(),
                                'errors' => $result->getErrors(),
                                'processed_rows' => $result->getProcessedRowsCount()
                            ]);
                        }

                        $successCount = $importResults['success_count'];
                        $updatedCount = $importResults['updated_count'];
                        $errors = $importResults['errors'];
                        $processedRows = $importResults['processed_rows'];

                        session()->forget('import_results');

                        $recipient = Auth::user();

                        if (!$recipient) {
                            Log::error('No authenticated user available for notification');
                            return;
                        }

                        if (($successCount + $updatedCount) > 0) {
                            Notification::make()
                                ->title('Import Berhasil')
                                ->success()
                                ->body(sprintf(
                                    "Berhasil memproses %d data (%d baru, %d diupdate)", 
                                    $successCount + $updatedCount,
                                    $successCount,
                                    $updatedCount
                                ))
                                ->send()
                                ->sendToDatabase($recipient);
                            return;
                        }

                        if (!empty($errors)) {
                            Notification::make()
                                ->title('Import Gagal')
                                ->body('Terdapat error pada data yang diimport')
                                ->actions([
                                    Action::make('viewErrors')
                                        ->label('Lihat Error')
                                        ->color('danger')
                                        ->modalHeading('Daftar Error')
                                        ->modalContent(view('filament.import-errors', [
                                            'errors' => $errors
                                        ]))
                                ])
                                ->send()
                                ->sendToDatabase($recipient);
                            return;
                        }

                        if ($processedRows > 0) {
                            Notification::make()
                                ->title('Tidak Ada Data Valid')
                                ->warning()
                                ->body('Ditemukan data tetapi tidak ada yang memenuhi kriteria valid')
                                ->send()
                                ->sendToDatabase($recipient);
                        } else {
                            Notification::make()
                                ->title('Tidak Ada Data Diproses')
                                ->warning()
                                ->body('Tidak ditemukan data yang valid untuk diimport')
                                ->send()
                                ->sendToDatabase($recipient);
                        }
                    } catch (\Exception $e) {
                        Log::error('Import notification error: '.$e->getMessage()."\n".$e->getTraceAsString());
                        Notification::make()
                            ->title('Error Sistem')
                            ->danger()
                            ->body('Terjadi kesalahan saat memproses import. Silakan cek log untuk detailnya.')
                            ->send()
                            ->sendToDatabase($recipient);
                    }
                }),
            CreateAction::make(),
        ];
    }
}