<?php

namespace App\Livewire;

use App\Models\Otp;
use App\Services\OtpService;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\On;
use Livewire\Component;
use Propaganistas\LaravelPhone\PhoneNumber;

class OtpFormModal extends Component
{
    public ?string $identifier = null; // Can be email or phone

    public ?string $otp = null;

    public ?string $verificationType = null; // 'login', 'email', or 'phone'

    #[On('setAssociationAdminEmail')]
    public function setEmail(string $identifier): void
    {
        $this->identifier = $identifier;
        $this->verificationType = 'login';
    }

    #[On('openVerificationModal')]
    public function openVerificationModal(string $identifier, string $type): void
    {
        $this->identifier = $identifier;
        $this->verificationType = $type; // 'email' or 'phone'
        $this->otp = null;
        $this->resetErrorBag();
        $this->dispatch('open-modal', id: 'otp-modal');
    }

    #[On('close-modal')]
    public function closeModal(): void
    {
        // Clear the OTP input and reset errors when modal closes
        $this->reset(['otp']);
        $this->resetErrorBag();
        $this->dispatch('clearOtpInputs');
    }

    public function submit()
    {
        // Validate the OTP input
        $this->validate([
            'otp' => 'required|size:6',
        ]);

        if ($this->identifier === null) {
            $this->addError('otp', __('association.system_error'));

            return;
        }

        // Normalize the identifier (phone number if not email)
        $normalizedIdentifier = $this->normalizeIdentifier($this->identifier);

        // Use OtpService for verification
        $otpService = app(OtpService::class);
        $isValid = $otpService->verifyOtp($normalizedIdentifier, $this->otp);

        if (! $isValid) {
            $this->addError('otp', 'رمز التحقق غير صالح أو منتهي الصلاحية.');

            return;
        }

        // Handle different verification types
        if ($this->verificationType === 'email' || $this->verificationType === 'phone') {
            // Update association verification status
            $user = Auth::user();
            if ($user && $user->association) {
                if ($this->verificationType === 'email') {
                    $user->association->update([
                        'email_verified' => true,
                        'email_verified_at' => now(),
                    ]);
                } else {
                    $user->association->update([
                        'phone_verified' => true,
                        'phone_verified_at' => now(),
                    ]);
                }

                $this->dispatch('verificationSuccess', type: $this->verificationType);
                $this->dispatch('close-modal', id: 'otp-modal');
                $this->reset(['otp', 'identifier', 'verificationType']);
            }
        } else {
            // Original login flow
            $this->dispatch('otpConfirmed');
        }
    }

    /**
     * Normalize identifier (phone number) to match stored format
     */
    private function normalizeIdentifier(?string $identifier): string
    {
        if ($identifier === null) {
            return '';
        }
        // Check if it's an email
        if (filter_var($identifier, FILTER_VALIDATE_EMAIL)) {
            return $identifier;
        }

        // If it's not an email, treat it as a phone number and normalize it
        try {
            $phoneNumber = new PhoneNumber($identifier, 'SA');

            return $phoneNumber->formatE164();
        } catch (\Exception $e) {
            // If normalization fails, return the original identifier
            return $identifier;
        }
    }

    public function render()
    {
        return view('livewire.otp-form-modal');
    }
}
