<?php

namespace App\Filament\Actions;

use App\Services\SopTemplateService;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Notifications\Notification;
use Illuminate\Validation\ValidationException;

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

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

        $this->label('导入模板');

        $this->icon('heroicon-o-arrow-up-tray');

        $this->color('success');

        $this->modalHeading('导入 SOP 模板');

        $this->modalDescription('从 JSON 文件导入 SOP 模板');

        $this->modalSubmitActionLabel('导入');

        $this->form([
            Forms\Components\FileUpload::make('file')
                ->label('选择文件')
                ->acceptedFileTypes(['application/json'])
                ->required()
                ->maxSize(5120), // 5MB
        ]);

        $this->action(function (array $data) {
            try {
                $filePath = storage_path('app/public/' . $data['file']);
                $json = file_get_contents($filePath);

                $service = app(SopTemplateService::class);
                $template = $service->importFromJson($json);

                // 删除临时文件
                @unlink($filePath);

                Notification::make()
                    ->title('导入成功')
                    ->body("SOP 模板「{$template->name}」已成功导入")
                    ->success()
                    ->send();

                // 重定向到编辑页面
                return redirect()->route('filament.admin.resources.sop-templates.edit', ['record' => $template]);
            } catch (ValidationException $e) {
                Notification::make()
                    ->title('导入失败')
                    ->body($e->getMessage())
                    ->danger()
                    ->send();

                throw $e;
            } catch (\Exception $e) {
                Notification::make()
                    ->title('导入失败')
                    ->body('文件格式错误或数据无效')
                    ->danger()
                    ->send();

                throw $e;
            }
        });
    }
}
