<?php

namespace App\Filament\Actions;

use App\Services\ExcelImportService;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Storage;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;

class ImportFormattedAttendanceAction extends Action
{
    public static function getDefaultName(): ?string
    {
        return 'importFormatted';
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Import Laporan')
            ->icon('heroicon-o-document-arrow-up')
            ->color('warning')
            ->form([
                Forms\Components\FileUpload::make('file')
                    ->label('File Excel')
                    ->required()
                    ->acceptedFileTypes([
                        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        'application/vnd.ms-excel',
                        '.xlsx',
                        '.xls',
                    ])
                    ->maxSize(10240) // 10MB
                    ->helperText('Format yang didukung: .xlsx, .xls (maks 10MB). File dapat berisi header, logo, dan footer - sistem akan otomatis mendeteksi baris data.'),

                Forms\Components\Placeholder::make('format_info')
                    ->label('Format File')
                    ->content('File Excel harus memiliki kolom berikut (minimal):
• Tanggal - Format: dd/mm/yyyy atau yyyy-mm-dd
• Nama Karyawan atau NIP
• Jam Masuk - Format: HH:MM atau HH:MM:SS

Kolom opsional: Jam Pulang, Status, Tipe, Alamat, Catatan, dll.

Sistem akan otomatis melewati baris header/logo dan footer/tanda tangan.'),
            ])
            ->action(function (array $data) {
                $file = $data['file'];

                // Handle file path
                $filePath = null;
                if ($file instanceof TemporaryUploadedFile) {
                    $filePath = $file->getRealPath();
                } elseif (is_string($file)) {
                    // File stored in livewire-tmp
                    $filePath = Storage::disk('local')->path($file);
                    if (!file_exists($filePath)) {
                        $filePath = storage_path('app/livewire-tmp/' . $file);
                    }
                }

                if (!$filePath || !file_exists($filePath)) {
                    Notification::make()
                        ->title('Error')
                        ->body('File tidak dapat dibaca')
                        ->danger()
                        ->send();
                    return;
                }

                // Process import
                $importService = new ExcelImportService();
                $result = $importService->import($filePath);

                // Show result
                if ($result['success'] > 0 || empty($result['errors'])) {
                    $message = "Berhasil: {$result['success']} baris";
                    if ($result['failed'] > 0) {
                        $message .= ", Gagal: {$result['failed']} baris";
                    }
                    if ($result['skipped_rows'] > 0) {
                        $message .= " (melewati {$result['skipped_rows']} baris header)";
                    }

                    Notification::make()
                        ->title('Import Selesai')
                        ->body($message)
                        ->success()
                        ->send();
                } else {
                    $errorMessages = implode("\n", array_slice($result['errors'], 0, 5));
                    if (count($result['errors']) > 5) {
                        $errorMessages .= "\n... dan " . (count($result['errors']) - 5) . " error lainnya";
                    }

                    Notification::make()
                        ->title('Import Gagal')
                        ->body($errorMessages)
                        ->danger()
                        ->persistent()
                        ->send();
                }

                // Cleanup temp file if stored
                if (is_string($data['file'])) {
                    Storage::disk('local')->delete($data['file']);
                }
            });
    }
}
