<?php

namespace App\Filament\Pages\Auth;

use Exception;
use Filament\Auth\Http\Responses\Contracts\LoginResponse;
use Filament\Auth\Pages\Login as BaseLogin;
use Filament\Facades\Filament;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Schema;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\HtmlString;
use Illuminate\Validation\ValidationException;

class Login extends BaseLogin
{
    public function getHeading(): string|Htmlable
    {
        try {
            $panelId = Filament::getCurrentPanel()?->getId();

            return match ($panelId) {
                'admin' => 'Admin Panel',
                'super-admin' => 'Super Admin Panel',
                default => 'Agent Panel',
            };
        } catch (Exception) {
            return 'Login';
        }
    }

    /**
     * @throws Exception
     */
    public function form(Schema $schema): Schema
    {
        return $schema->components([
            $this->getLoginFormComponent(),
            $this->getPasswordFormComponent(),
        ]);
    }

    /**
     * @throws Exception
     */
    protected function getLoginFormComponent(): Component
    {
        return TextInput::make('username')
            ->required()
            ->autocomplete(false)
            ->autofocus()
            ->extraInputAttributes(['tabindex' => 1]);
    }

    protected function getPasswordFormComponent(): Component
    {
        $panelId = Filament::getCurrentPanel()?->getId();
        $resetUrl = $panelId === 'admin' ? Filament::getRequestPasswordResetUrl() : null;

        return TextInput::make('password')
            ->label('Password')
            ->hint($resetUrl ? new HtmlString('<a href="' . $resetUrl . '" tabindex="3" class="fi-link">Forgot password?</a>') : null)
            ->password()
            ->revealable(filament()->arePasswordsRevealable())
            ->autocomplete('current-password')
            ->required()
            ->extraInputAttributes(['tabindex' => 2]);
    }

    public function getRules(): array
    {
        return [
            'username' => 'required|string',
            'password' => 'required|string',
        ];
    }

    /**
     * @return LoginResponse|null
     * @throws ValidationException
     */
    public function authenticate(): ?LoginResponse
    {
        try {
            return parent::authenticate();
        } catch (ValidationException $e) {
            throw ValidationException::withMessages([
                'data.username' => $e->getMessage(),
                'data.password' => $e->getMessage(),
            ]);
        }
    }

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