<?php

namespace App\Filament\Resources\EmployeeCardResource\Pages;

use App\Filament\Resources\EmployeeCardResource;
use App\Models\User;
use App\Services\QrCardService;
use Filament\Actions;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Auth;

class ListEmployeeCards extends ListRecords
{
    protected static string $resource = EmployeeCardResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\Action::make('generateBatch')
                ->label('Generate Kartu Batch')
                ->icon('heroicon-o-plus-circle')
                ->color('primary')
                ->form([
                    Forms\Components\Select::make('users')
                        ->label('Pilih Karyawan')
                        ->multiple()
                        ->options(function () {
                            $user = Auth::user();
                            $query = User::where('is_active', true)
                                ->whereNotNull('company_id')
                                ->whereDoesntHave('employeeCards', function ($q) {
                                    $q->where('card_status', 'active');
                                });
                            if ($user->company_id) {
                                $query->where('company_id', $user->company_id);
                            }
                            return $query->pluck('name', 'id');
                        })
                        ->searchable()
                        ->preload()
                        ->required(),
                ])
                ->action(function (array $data) {
                    $userIds = $data['users'] ?? [];
                    $result = app(QrCardService::class)->batchCreateCards($userIds);

                    $created = $result['created'];
                    $failedList = $result['failed'] ?? [];

                    if ($created > 0 && empty($failedList)) {
                        Notification::make()
                            ->success()
                            ->title('Kartu Berhasil Dibuat')
                            ->body("{$created} kartu berhasil dibuat.")
                            ->send();
                    } elseif ($created > 0 && !empty($failedList)) {
                        $msg = "{$created} kartu berhasil dibuat. " . count($failedList) . " gagal.";
                        if (count($failedList) <= 3) {
                            foreach ($failedList as $f) {
                                $msg .= "\n• " . ($f['reason'] ?? 'Unknown');
                            }
                        }
                        Notification::make()
                            ->warning()
                            ->title('Sebagian Gagal')
                            ->body($msg)
                            ->send();
                    } else {
                        $msg = count($failedList) > 0
                            ? "Tidak ada kartu yang dibuat. Contoh alasan: " . ($failedList[0]['reason'] ?? 'tidak diketahui')
                            : "Tidak ada karyawan yang dipilih atau data tidak valid.";
                        Notification::make()
                            ->danger()
                            ->title('Generate Kartu Gagal')
                            ->body($msg)
                            ->send();
                    }

                    $this->redirect(EmployeeCardResource::getUrl('index'));
                }),
        ];
    }
}
