<?php

namespace App\Filament\Pages\Auth;

use Filament\Forms\Components\ViewField;
use Filament\Http\Responses\Auth\LoginResponse;
use Filament\Notifications\Notification;
use Filament\Pages\Auth\Login as BaseLogin;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Component;
use App\Service\CaptchaService;
use Filament\Forms\Form;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Computed;
use Illuminate\Support\Facades\Cache;
use Filament\Forms\Components\View;

class Login extends BaseLogin
{
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static string $view = 'filament.pages.auth.login';

    public ?string $verification_code = null;
    public ?string $captchaImage = null;

    public function mount(): void
    {
        parent::mount();
        if (!$this->captchaImage) {
            $this->refreshCaptcha();
        }
    }

    public function refreshCaptcha(): void
    {
        $captchaService = app(CaptchaService::class);
        $code = $captchaService->generateCode();

        // Store code in cache with user's session ID as key
        Cache::put(
            'verification_code_' . session()->getId(),
            $code,
            now()->addMinutes(5)
        );
        $this->captchaImage = $captchaService->generateImage($code);
        $this->dispatch('captcha-refreshed');
    }

    public function captchaImageUrl(): string
    {
        if(!$this->captchaImage)$this->refreshCaptcha();
        return $this->captchaImage;
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                $this->getEmailFormComponent(),
                $this->getPasswordFormComponent(),
                $this->getVerificationCodeFormComponent(),
                ViewField::make('captcha')
                ->view('filament.pages.auth.captcha'),
                $this->getRememberFormComponent(),
            ])
            ->statePath('data');
    }

    protected function getVerificationCodeFormComponent(): Component
    {
        return TextInput::make('verification_code')
            ->label('Verification Code')
            ->required()
            ->length(6)
            ->placeholder('Enter code shown above');
    }

    public function authenticate(): ?LoginResponse
    {
        $this->validate();
        $formData = $this->form->getState();
        if (! $this->verifyCode($formData['verification_code'])) {
            throw ValidationException::withMessages([
                'data.verification_code' => __('驗證碼錯誤'),
            ]);
        }

        try {
            return parent::authenticate();
        } catch (ValidationException $e) {
            $this->refreshCaptcha();
            // throw $e;
            throw ValidationException::withMessages([
                'verification_code' => __('Invalid verification code.'),
            ]);
        }
    }

    protected function verifyCode(string $code): bool
    {
        $validCode = Cache::get('verification_code_' . session()->getId());
        return $code === $validCode;
    }
}
