<?php

declare(strict_types=1);

namespace App\Http\Livewire;

use App\Exports\ContestSignupsExport;
use App\Exports\OnlineMeetingSignupsExport;
use App\Jobs\DeleteSentExport;
use App\Jobs\SendExport;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Livewire\Component;
use Maatwebsite\Excel\Facades\Excel;

class RequestExport extends Component implements HasForms
{
    use InteractsWithForms;

    public ?string $email;

    public bool $processing = false;

    protected function getFormSchema(): array
    {
        return [
            TextInput::make('email')
                ->label('Email')
                ->email()
                ->required()
                ->default(auth()->user()?->email),

            Radio::make('export')
                ->label('Lista de înscrieri de exportat')
                ->columns()
                ->options([
                    OnlineMeetingSignupsExport::class => 'Întâlniri online',
                    ContestSignupsExport::class => 'Concurs',
                ])
                ->default(OnlineMeetingSignupsExport::class)
                ->required(),

        ];
    }

    public function mount(): void
    {
        $this->form->fill();
    }

    public function submit(): void
    {
        $this->processing = false;
        $type = match ($this->export) {
            OnlineMeetingSignupsExport::class => 'intalniri-online',
            ContestSignupsExport::class => 'concurs',
        };

        $timestamp = now()->format('Y-m-d_H-i-s');
        $filePath = "exports/$timestamp-inscrieri-$type.xlsx";

        Excel::queue(new $this->export, $filePath)
            ->chain([
                new SendExport($this->export, $this->email, $filePath),
                new DeleteSentExport($filePath),
            ]);

        $this->processing = true;
    }

    public function render()
    {
        return view('livewire.request-export');
    }
}
