<?php

namespace App\Filament\Resources\EmotionResource\Pages;

use App\Filament\Resources\EmotionResource;
use App\Services\EmotionImportService;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Page;
use Illuminate\Support\Facades\Storage;

class ImportEmotions extends Page
{
    protected static string $resource = EmotionResource::class;
    protected string $view = 'filament.resources.emotion-resource.pages.import-emotions';
    protected ?string $heading = null;

    public ?string $file = null;

    public function form(Form $form): Form
    {
        return $form->schema([
            FileUpload::make('file')
                ->label(__('admin.common.csv_file'))
                ->acceptedFileTypes(['text/csv', 'text/plain'])
                ->directory('imports')
                ->required(),
        ]);
    }

    public function doImport(): void
    {
        $this->validate();

        $path = $this->form->getState()['file'] ?? null;
        if (! $path || ! Storage::disk('public')->exists($path)) {
            Notification::make()->danger()->title(__('admin.notifications.file_not_found'))->send();
            return;
        }

        $fullPath = Storage::disk('public')->path($path);
        [$ok, $fail] = app(EmotionImportService::class)->import($fullPath);

        Notification::make()
            ->success()
            ->title(__('admin.notifications.imported_rows', ['count' => $ok]))
            ->body($fail ? __('admin.notifications.failed_count', ['count' => $fail]) : null)
            ->send();
    }

    public function getHeading(): string
    {
        return __('admin.emotions.import.heading');
    }
}
