<?php

namespace App\Filament\Pages\Verification;

use App\Enums\VerificationStatus;
use App\Filament\Pages\Verification\Actions\SubmitVerificationAction;
use App\Filament\Pages\Verification\Services\VerificationAdminNotifier;
use App\Filament\Pages\Verification\Services\VerificationProgressService;
use App\Filament\Pages\Verification\Services\VerificationSubmissionService;
use App\Filament\Support\CheerfulNotification;
use App\Models\Company;
use App\Models\VerificationRequest;
use BackedEnum;
use BezhanSalleh\FilamentShield\Traits\HasPageShield;
use Filament\Actions\Action;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Actions\Contracts\HasActions;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use UnitEnum;

class Index extends Page implements HasActions, HasForms
{
    use HasPageShield, InteractsWithActions, InteractsWithForms;

    public ?Company $company = null;

    protected static string|UnitEnum|null $navigationGroup = 'Kelola';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCheckBadge;

    protected static ?string $navigationLabel = 'Verifikasi';

    protected static ?int $navigationSort = 5;

    protected static ?string $slug = 'manage/verification';

    protected static ?string $title = 'Verifikasi';

    public ?VerificationRequest $verificationRequest = null;

    protected string $view = 'filament.pages.verification';

    public static function canAccess(): bool
    {
        return auth()->user()->can('View:Verification');
    }

    public function mount(): void
    {
        $user = Auth::user();
        $this->company = $user->company;

        // Load unified verification request
        if ($this->company) {
            $this->verificationRequest = $this->company->verificationRequest()
                ->with(['reviews.reviewer'])
                ->latest()
                ->first();
        }
    }

    /**
     * Get unified verification progress
     */
    public function getVerificationProgress(): array
    {
        return app(VerificationProgressService::class)->getProgress(
            $this->company,
            $this->verificationRequest,
        );
    }

    /**
     * Submit unified verification action
     */
    public function submitVerificationAction(): Action
    {
        return SubmitVerificationAction::make();
    }

    public function handleVerificationSubmit(array $data = []): void
    {
        $user = Auth::user();
        $progress = app(VerificationProgressService::class)->getProgress(
            $this->company,
            $this->verificationRequest,
        );

        if (! $progress['isDataComplete']) {
            CheerfulNotification::danger(
                CheerfulNotification::getByKey('verification.incomplete.title'),
                CheerfulNotification::getByKey(
                    'verification.incomplete.body',
                    ['missing' => implode(', ', $progress['missingData'])]
                )
            )->send();

            return;
        }

        $isRevision = $this->verificationRequest && $this->verificationRequest->status === VerificationStatus::NEED_REVISION;

        $this->verificationRequest = app(VerificationSubmissionService::class)->submit(
            $this->company,
            $this->verificationRequest,
            $user,
        );

        CheerfulNotification::success(
            CheerfulNotification::getByKey('verification.success.title'),
            CheerfulNotification::getByKey('verification.success.body')
        )->send();

        app(VerificationAdminNotifier::class)->notifySuperAdmins($user, $isRevision);
    }

    /**
     * Check if all required data is complete for verification
     */
    protected function isDataComplete(): bool
    {
        return app(VerificationProgressService::class)->isDataComplete($this->company);
    }

    /**
     * Get missing data items for verification
     */
    protected function getMissingData(): array
    {
        return app(VerificationProgressService::class)->getMissingData($this->company);
    }

    /**
     * Check if user can submit verification
     */
    protected function canSubmit(): bool
    {
        return app(VerificationProgressService::class)->canSubmit($this->company, $this->verificationRequest);
    }

    /**
     * Determine the current step based on status
     */
    protected function resolveStep(): int
    {
        return app(VerificationProgressService::class)->resolveStep($this->company, $this->verificationRequest);
    }

    /**
     * Get the latest review notes
     */
    protected function getLatestReviewNotes(): ?string
    {
        return app(VerificationProgressService::class)->getLatestReviewNotes($this->verificationRequest);
    }

    /**
     * Get all reviews history
     */
    protected function getReviewHistory(): Collection
    {
        return app(VerificationProgressService::class)->getReviewHistory($this->verificationRequest);
    }

    /**
     * Submit unified verification
     */
    protected function submitVerification(): VerificationRequest
    {
        return app(VerificationSubmissionService::class)->submit(
            $this->company,
            $this->verificationRequest,
            Auth::user(),
        );
    }

    /**
     * Get alert data for verification status
     */
    protected function getAlertData(): ?array
    {
        return app(VerificationProgressService::class)->getAlertData($this->verificationRequest);
    }

    /**
     * Get missing data buttons configuration
     */
    protected function getMissingDataButtons(): array
    {
        return app(VerificationProgressService::class)->getMissingDataButtons($this->company);
    }

    /**
     * Get steps array for stepper
     */
    protected function getSteps(bool $isComplete): array
    {
        return app(VerificationProgressService::class)->getSteps(
            $this->company,
            $this->verificationRequest,
            $isComplete
        );
    }

    public function getViewData(): array
    {
        return [
            'verificationProgress' => $this->getVerificationProgress(),
        ];
    }
}
