<?php

declare(strict_types=1);

namespace App\Livewire\Admin\PaymentMethods;

use App\Models\PaymentMethod;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Rule;
use Livewire\Component;

#[Layout('layouts.admin')]
final class Edit extends Component
{
    public PaymentMethod $paymentMethod;

    // Basic Information
    #[Rule('required|string|max:255')]
    public string $name = '';

    #[Rule('required|string|in:bank_transfer,crypto,paypal,paystack,flutterwave')]
    public string $type = '';

    #[Rule('required|string|in:automated,manual')]
    public string $gatewayType = 'manual';

    #[Rule('required|boolean')]
    public bool $is_active = true;

    #[Rule('required|integer|min:0')]
    public int $display_order = 0;

    // Processing Information
    #[Rule('required|string|max:255')]
    public string $processing_time = '';

    #[Rule('required|boolean')]
    public bool $requires_proof = true;

    #[Rule('required|numeric|min:0')]
    public float $min_amount = 0.00;

    #[Rule('nullable|numeric|min:0')]
    public ?float $max_amount = null;

    // Configuration (JSON)
    public array $configuration = [];

    // Type-specific configuration fields
    public array $bankConfig = [];

    public array $cryptoConfig = [];

    public array $paypalConfig = [];

    public array $paystackConfig = [];

    public array $flutterwaveConfig = [];

    public function mount(PaymentMethod $paymentMethod): void
    {
        $this->paymentMethod = $paymentMethod;
        $this->name = $paymentMethod->name;
        $this->type = $paymentMethod->type;
        $this->gatewayType = $paymentMethod->gateway_type ?: 'manual';
        $this->is_active = $paymentMethod->is_active;
        $this->display_order = $paymentMethod->display_order;
        $this->processing_time = $paymentMethod->processing_time;
        $this->requires_proof = $paymentMethod->requires_proof;
        $this->min_amount = (float) $paymentMethod->min_amount;
        $this->max_amount = $paymentMethod->max_amount ? (float) $paymentMethod->max_amount : null;
        $this->configuration = $paymentMethod->configuration ?? [];

        $this->loadTypeSpecificConfig();
    }

    public function updatedType(): void
    {
        if (in_array($this->type, ['paystack', 'flutterwave'], true)) {
            $this->gatewayType = 'automated';
            $this->requires_proof = false;
        }

        $this->loadTypeSpecificConfig();
    }

    private function loadTypeSpecificConfig(): void
    {
        $this->bankConfig = [];
        $this->cryptoConfig = [];
        $this->paypalConfig = [];
        $this->paystackConfig = [];
        $this->flutterwaveConfig = [];

        switch ($this->type) {
            case 'bank_transfer':
                $this->bankConfig = $this->configuration['bank_name'] ? [
                    'bank_name' => $this->configuration['bank_name'] ?? '',
                    'account_name' => $this->configuration['account_name'] ?? '',
                    'account_number' => $this->configuration['account_number'] ?? '',
                    'routing_number' => $this->configuration['routing_number'] ?? '',
                    'swift_code' => $this->configuration['swift_code'] ?? '',
                    'instructions' => $this->configuration['instructions'] ?? '',
                ] : [
                    'bank_name' => '',
                    'account_name' => '',
                    'account_number' => '',
                    'routing_number' => '',
                    'swift_code' => '',
                    'instructions' => '',
                ];
                break;
            case 'crypto':
                $this->cryptoConfig = [
                    'supported_currencies' => $this->configuration['supported_currencies'] ?? [],
                    'instructions' => $this->configuration['instructions'] ?? '',
                ];
                break;
            case 'paypal':
                $this->paypalConfig = [
                    'paypal_email' => $this->configuration['paypal_email'] ?? '',
                    'instructions' => $this->configuration['instructions'] ?? '',
                ];
                break;
            case 'paystack':
                $this->paystackConfig = [
                    'public_key' => $this->configuration['public_key'] ?? '',
                    'merchant_id' => $this->configuration['merchant_id'] ?? '',
                    'instructions' => $this->configuration['instructions'] ?? '',
                ];
                break;
            case 'flutterwave':
                $this->flutterwaveConfig = [
                    'public_key' => $this->configuration['public_key'] ?? '',
                    'merchant_id' => $this->configuration['merchant_id'] ?? '',
                    'instructions' => $this->configuration['instructions'] ?? '',
                ];
                break;
        }
    }

    public function addCryptoCurrency(): void
    {
        $this->cryptoConfig['supported_currencies'][] = [
            'code' => '',
            'name' => '',
            'wallet_address' => '',
            'network' => '',
        ];
    }

    public function removeCryptoCurrency(int $index): void
    {
        unset($this->cryptoConfig['supported_currencies'][$index]);
        $this->cryptoConfig['supported_currencies'] = array_values($this->cryptoConfig['supported_currencies']);
    }

    public function updatePaymentMethod(): void
    {
        $this->validate();

        // Build configuration based on type
        $this->buildConfiguration();

        $this->paymentMethod->update([
            'name' => $this->name,
            'type' => $this->type,
            'gateway_type' => $this->gatewayType,
            'is_active' => $this->is_active,
            'display_order' => $this->display_order,
            'processing_time' => $this->processing_time,
            'requires_proof' => $this->requires_proof,
            'min_amount' => $this->min_amount,
            'max_amount' => $this->max_amount,
            'configuration' => $this->configuration,
        ]);

        activity()
            ->causedBy(auth()->user())
            ->performedOn($this->paymentMethod)
            ->withProperties([
                'payment_method_id' => $this->paymentMethod->id,
                'changes' => [
                    'name' => $this->name,
                    'type' => $this->type,
                    'gateway_type' => $this->gatewayType,
                    'is_active' => $this->is_active,
                    'display_order' => $this->display_order,
                    'processing_time' => $this->processing_time,
                    'requires_proof' => $this->requires_proof,
                    'min_amount' => $this->min_amount,
                    'max_amount' => $this->max_amount,
                ],
            ])
            ->log('payment_method_updated');

        session()->flash('success', 'Payment method updated successfully!');
    }

    private function buildConfiguration(): void
    {
        switch ($this->type) {
            case 'bank_transfer':
                $this->configuration = [
                    'bank_name' => $this->bankConfig['bank_name'] ?? '',
                    'account_name' => $this->bankConfig['account_name'] ?? '',
                    'account_number' => $this->bankConfig['account_number'] ?? '',
                    'routing_number' => $this->bankConfig['routing_number'] ?? '',
                    'swift_code' => $this->bankConfig['swift_code'] ?? '',
                    'instructions' => $this->bankConfig['instructions'] ?? '',
                ];
                break;
            case 'crypto':
                $this->configuration = [
                    'supported_currencies' => $this->cryptoConfig['supported_currencies'] ?? [],
                    'instructions' => $this->cryptoConfig['instructions'] ?? '',
                ];
                break;
            case 'paypal':
                $this->configuration = [
                    'paypal_email' => $this->paypalConfig['paypal_email'] ?? '',
                    'instructions' => $this->paypalConfig['instructions'] ?? '',
                ];
                break;
            case 'paystack':
                $this->configuration = [
                    'public_key' => $this->paystackConfig['public_key'] ?? '',
                    'merchant_id' => $this->paystackConfig['merchant_id'] ?? '',
                    'instructions' => $this->paystackConfig['instructions'] ?? '',
                ];
                break;
            case 'flutterwave':
                $this->configuration = [
                    'public_key' => $this->flutterwaveConfig['public_key'] ?? '',
                    'merchant_id' => $this->flutterwaveConfig['merchant_id'] ?? '',
                    'instructions' => $this->flutterwaveConfig['instructions'] ?? '',
                ];
                break;
        }
    }

    public function render()
    {
        return view('livewire.admin.payment-methods.edit');
    }
}
