<?php

namespace App\Filament\SuperAdmin\Pages\Auth;

use Filament\Auth\Http\Responses\Contracts\LoginResponse as LoginResponseContract;
use Filament\Auth\Pages\Login as BaseLogin;
use Filament\Facades\Filament;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Illuminate\Validation\ValidationException;

class Login extends BaseLogin implements HasForms
{
    use InteractsWithForms;

    public function authenticate(): ?LoginResponseContract
    {
        $data = $this->form->getState();

        $credentials = $this->getCredentialsFromFormData($data);

        $authGuard = Filament::auth();

        if (! $authGuard->attempt($credentials, $data['remember'] ?? false)) {
            throw ValidationException::withMessages([
                'data.email' => __('auth.failed'),
            ]);
        }

        $user = $authGuard->user();

        if (! $user->email_verified_at) {
            $authGuard->logout();

            throw ValidationException::withMessages([
                'data.email' => 'Your email address is not verified. Please check your email for a verification link.',
            ]);
        }

        // SuperAdmin-spezifisch: Prüfe auf SuperAdmin-Rolle, keine Tenant-Prüfung
        if (! $user->isSuperAdmin()) {
            $authGuard->logout();

            throw ValidationException::withMessages([
                'data.email' => 'You do not have access to the SuperAdmin panel. Contact support.',
            ]);
        }

        session()->regenerate();

        return parent::getLoggedInResponse();
    }

    protected function getRedirectUrl(): string
    {
        return '/super-admin';
    }

    protected function getCredentialsFromFormData(array $data): array
    {
        return [
            'email' => $data['data']['email'],
            'password' => $data['data']['password'],
        ];
    }

    public function getFormSchema(): array
    {
        return [
            TextInput::make('data.email')
                ->label('Email')
                ->email()
                ->required()
                ->autofocus(),
            TextInput::make('data.password')
                ->label('Password')
                ->password()
                ->required()
                ->extraAttributes(['tabindex' => 2]),
            Checkbox::make('data.remember')
                ->label('Remember me'),
        ];
    }
}
