<?php

namespace App\Filament\Central\Resources\TestInstanceResource\Pages;

use App\Filament\Central\Resources\TenantResource;
use App\Filament\Central\Resources\TestInstanceResource;
use App\Models\Central\Tenant;
use App\Services\Tenancy\TestInstanceService;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Auth;

class EditTestInstance extends EditRecord
{
    protected static string $resource = TestInstanceResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Action::make('backToInstances')
                ->label('Back to Test Instances')
                ->icon(Heroicon::OutlinedArrowLeft)
                ->color('gray')
                ->url(TestInstanceResource::getUrl('index')),

            Action::make('open')
                ->label('Open Test Instance')
                ->icon(Heroicon::OutlinedArrowTopRightOnSquare)
                ->url(fn (Tenant $record): string => TenantResource::tenantUrl($record))
                ->openUrlInNewTab(),

            Action::make('impersonate')
                ->label('Impersonate')
                ->icon(Heroicon::OutlinedUserCircle)
                ->requiresConfirmation()
                ->modalDescription('Opens a support session inside this test instance as its administrator. The hand-off is written to their audit trail.')
                ->action(fn (Tenant $record) => TenantResource::startImpersonation($record)),

            // Grouped into one dropdown so the header stays at 4 buttons
            // regardless of how many sync variants exist — five-plus separate
            // Action buttons here overflow the header on anything narrower
            // than a full-width desktop viewport (Filament's header actions
            // row doesn't wrap; see .fi-header-actions-ctn's `shrink-0`).
            ActionGroup::make([
                Action::make('syncFromLive')
                    ->label('Everything')
                    ->icon(Heroicon::OutlinedArrowPath)
                    ->requiresConfirmation()
                    ->modalHeading('Sync Test Instance?')
                    ->modalIcon(Heroicon::OutlinedArrowPath)
                    ->modalDescription('This will refresh the test instance using the current live tenant data. Existing test-instance data may be overwritten. This action cannot be automatically undone.')
                    ->modalSubmitActionLabel('Sync from Live')
                    ->action(function (Tenant $record): void {
                        try {
                            $result = app(TestInstanceService::class)->syncFromLive(
                                $record,
                                Auth::guard('central')->id(),
                            );
                        } catch (\Throwable $e) {
                            Notification::make()
                                ->title('Sync failed')
                                ->body($e->getMessage())
                                ->danger()
                                ->persistent()
                                ->send();

                            return;
                        }

                        TenantResource::audit($record, 'test_instance.synced', [
                            'products' => $result['products'],
                            'customers' => $result['customers'],
                            'invoices' => $result['invoices'],
                            'branches' => $result['branches'],
                            'users' => $result['users'],
                            'total_rows' => $result['total_rows'],
                            'seconds' => $result['seconds'],
                        ]);

                        Notification::make()
                            ->title('Test instance synced')
                            ->body(sprintf(
                                'Copied %d products, %d customers, %d invoices, %d branches and %d users (%d rows) from %s in %ss.',
                                $result['products'],
                                $result['customers'],
                                $result['invoices'],
                                $result['branches'],
                                $result['users'],
                                $result['total_rows'],
                                $record->parentTenant?->name ?? 'the live tenant',
                                $result['seconds'],
                            ))
                            ->success()
                            ->persistent()
                            ->send();
                    }),

                Action::make('syncProductsFromLive')
                    ->label('Products Only')
                    ->icon(Heroicon::OutlinedShoppingBag)
                    ->requiresConfirmation()
                    ->modalHeading('Sync Products?')
                    ->modalIcon(Heroicon::OutlinedShoppingBag)
                    ->modalDescription('This will refresh only the product catalog (categories, subcategories, products) in the test instance from the current live tenant data. No other test data is touched. This action cannot be automatically undone.')
                    ->modalSubmitActionLabel('Sync Products')
                    ->action(function (Tenant $record): void {
                        try {
                            $result = app(TestInstanceService::class)->syncProductsFromLive(
                                $record,
                                Auth::guard('central')->id(),
                            );
                        } catch (\Throwable $e) {
                            Notification::make()
                                ->title('Sync failed')
                                ->body($e->getMessage())
                                ->danger()
                                ->persistent()
                                ->send();

                            return;
                        }

                        TenantResource::audit($record, 'test_instance.products_synced', [
                            'products' => $result['products'],
                            'added' => $result['added'],
                            'updated' => $result['updated'],
                            'total_rows' => $result['total_rows'],
                            'seconds' => $result['seconds'],
                        ]);

                        Notification::make()
                            ->title('Products synced')
                            ->body(sprintf(
                                'Copied %d products (%d added, %d updated) from %s in %ss.',
                                $result['products'],
                                $result['added'],
                                $result['updated'],
                                $record->parentTenant?->name ?? 'the live tenant',
                                $result['seconds'],
                            ))
                            ->success()
                            ->persistent()
                            ->send();
                    }),
            ])
                ->label('Sync from Live')
                ->icon(Heroicon::OutlinedArrowPath)
                ->color('primary')
                ->button(),
        ];
    }

    protected function getRedirectUrl(): string
    {
        return TestInstanceResource::getUrl('index');
    }
}
