<?php

namespace App\Filament\Resources\Products\Pages;

use App\Filament\Resources\Products\ProductResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;

class ListProducts extends ListRecords
{
    protected static string $resource = ProductResource::class;

    protected function getHeaderActions(): array
    {
        return [
            \Filament\Actions\Action::make('import_product')
                ->label('Import from URL')
                ->icon('heroicon-o-arrow-down-tray')
                ->color('primary')
                ->closeModalByClickingAway(true)
                ->form([
                    \Filament\Forms\Components\TextInput::make('url')
                        ->label('Product URL')
                        ->placeholder('e.g. https://badhonsworld.com/products/66ea2d0a2ba180e8143b9f7d')
                        ->required()
                        ->url(),
                    \Filament\Forms\Components\Select::make('category_id')
                        ->label('Fallback Category')
                        ->options(\App\Models\Category::pluck('name', 'id'))
                        ->searchable()
                        ->required()
                        ->helperText('Newly imported products will map automatically to badhonsworld categories. If auto-mapping fails, this category will be used.'),
                ])
                ->action(function (array $data) {
                    $url = $data['url'];
                    $categoryId = $data['category_id'];

                    // 1. Extract product ID from URL
                    if (!preg_match('/\/products\/([a-f0-9]{24})/', $url, $matches)) {
                        \Filament\Notifications\Notification::make()
                            ->title('Invalid URL')
                            ->body('Please provide a valid badhonsworld.com product URL containing a 24-character hexadecimal ID.')
                            ->danger()
                            ->send();
                        return;
                    }

                    $productId = $matches[1];

                    // Ensure product is not already imported
                    if (\App\Models\Product::where('external_id', $productId)->exists()) {
                        \Filament\Notifications\Notification::make()
                            ->title('Product Already Exists')
                            ->body("This product has already been imported.")
                            ->warning()
                            ->send();
                        return;
                    }

                    // Call the service to fetch and import it
                    $service = app(\App\Services\BadhonsworldService::class);
                    $apiUrl = "https://api.badhonsworld.com/api/v1/product/product-details?id={$productId}";
                    
                    try {
                        $response = \Illuminate\Support\Facades\Http::withHeaders($service->getHeaders())
                            ->timeout(20)
                            ->get($apiUrl);
                    } catch (\Exception $e) {
                        \Filament\Notifications\Notification::make()
                            ->title('Connection Failed')
                            ->body('Failed to connect to badhonsworld API: ' . $e->getMessage())
                            ->danger()
                            ->send();
                        return;
                    }

                    if (!$response->successful()) {
                        \Filament\Notifications\Notification::make()
                            ->title('Failed to fetch product')
                            ->body('API returned status code ' . $response->status())
                            ->danger()
                            ->send();
                        return;
                    }

                    $json = $response->json();
                    if (empty($json['success']) || empty($json['data'])) {
                        \Filament\Notifications\Notification::make()
                            ->title('Invalid API Response')
                            ->body('The API response did not contain valid product data.')
                            ->danger()
                            ->send();
                        return;
                    }

                    $product = $service->importOrUpdateProduct($json['data'], $categoryId);

                    if ($product) {
                        \Filament\Notifications\Notification::make()
                            ->title('Product Imported Successfully')
                            ->body("Product '{$product->name}' has been successfully imported.")
                            ->success()
                            ->send();
                    } else {
                        \Filament\Notifications\Notification::make()
                            ->title('Import Failed')
                            ->body('Failed to parse and save product.')
                            ->danger()
                            ->send();
                    }
                }),
            \Filament\Actions\Action::make('bulk_import')
                ->label('Bulk Import All')
                ->color('success')
                ->icon('heroicon-o-arrow-down-tray')
                ->closeModalByClickingAway(true)
                ->form([
                    \Filament\Forms\Components\Select::make('category_id')
                        ->label('Default Category')
                        ->relationship('category', 'name')
                        ->required()
                        ->helperText('Newly imported products will be assigned to this category if their category is not mapped.'),
                ])
                ->action(function (array $data) {
                    \App\Jobs\BadhonsworldBulkImportJob::dispatch($data['category_id']);
                    
                    \Filament\Notifications\Notification::make()
                        ->title('Bulk Import Started')
                        ->body("Bulk import has been queued in the background. Products will appear shortly.")
                        ->success()
                        ->send();
                }),
            CreateAction::make(),
        ];
    }

    protected function getHeaderWidgets(): array
    {
        return [
            \App\Filament\Resources\Products\Widgets\ProductStats::class,
        ];
    }
}
