<?php

namespace App\Filament\App\Pages;

use Filament\Pages\Page;
use Filament\Forms\Form;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Actions;

class API extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-key';

    protected static ?string $title = 'API';

    protected static ?string $slug = 'api';

    protected static string $view = 'filament.app.pages.api';

    protected static ?string $navigationGroup = 'Settings';

    protected static ?int $navigationSort = 2;

    public ?array $APIData = [];

    public bool $toggleAPIDisplay = true;

    protected function getForms(): array
    {
        return [
            'showAPIForm',
        ];
    }

    public function mount(): void
    {
        $this->toggleAPI();
    }

    public function toggleAPI(): void
    {
        if ($this->toggleAPIDisplay) {
            $this->showAPIForm->fill([
                'email' => filament()->auth()->user()->email,
                'api_key' => '*****',
            ]);
        } else {
            $this->showAPIForm->fill([
                'email' => filament()->auth()->user()->email,
                'api_key' => $this->getAPIkey(),
            ]);
        }

        $this->toggleAPIDisplay = !$this->toggleAPIDisplay;
    }

    public function getAPIkey(): string
    {
        $key = hash('sha256', 'kkd' . filament()->auth()->user()->email);
        return $key;
    }

    public function showAPIForm(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('API Key')
                    ->aside()
                    ->description(__('Application Programming Interface (API) key can be used for connecting Kad Kahwin Digital with other services or applications.'))
                    ->schema([
                        TextInput::make('email')
                            ->label(__('Your Email Address'))
                            ->disabled()
                            ->required(),
                        TextInput::make('api_key')
                            ->label(__('Your API Key'))
                            ->disabled()
                            ->required()
                            ->suffixAction(
                                Actions\Action::make('toggle')
                                    ->color('gray')
                                    ->icon('heroicon-s-eye')
                                    ->action('toggleAPI'),
                            ),
                    ]),
            ])
            ->statePath('APIData');
    }
}
