<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\PaymentMethod;
use Livewire\WithFileUploads;
use Illuminate\Support\Str;
new #[Layout('layouts::base')] class extends Component {
    use WithFileUploads;
    public $methods;

    public $name,
        $fee_percent = 0,
        $is_active = true;
    public $fields = [];
    public $instructions = [];
    public $details = [];
    public $type = 'deposit'; // default
    public $logo; // holds the temporary upload

    public $editingMethod = null;

    protected function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255', \Illuminate\Validation\Rule::unique('payment_methods')->ignore($this->editingMethod)->where(fn($query) => $query->where('type', $this->type))],
            'fee_percent' => 'required|numeric|min:0',
            'fields' => 'nullable|array',
            'fields.*.name' => 'required|string|distinct',
            'fields.*.type' => 'required|in:text,textarea,select,file,number',
            'fields.*.label' => 'nullable|string|max:255',
            'fields.*.placeholder' => 'nullable|string|max:255',
            'fields.*.required' => 'boolean',
            'fields.*.options' => 'nullable|array',
            'fields.*.options.*.label' => 'required_with:fields.*.options|string',
            'fields.*.options.*.value' => 'required_with:fields.*.options|string',
            'instructions' => 'nullable|array',
            'details' => 'nullable|array',
            'logo' => $this->editingMethod ? 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048' : 'required|image|mimes:jpg,jpeg,png,svg|max:2048',
        ];
    }

    public function mount($type = 'deposit')
    {
        $this->type = $type;
        $this->loadMethods();
        $paymentMethodId = request()->query('paymentMethodId');

        if ($paymentMethodId) {
            $this->editMethod($paymentMethodId);
        }
    }

    public function loadMethods()
    {
        $this->methods = PaymentMethod::where('type', $this->type)->get();
    }

    public function addField()
    {
        $id = (string) Str::uuid();
        $this->fields[$id] = [
            'id' => $id,
            'name' => '', // internal Laravel-safe key
            'original_name' => '', // stores what admin typed
            'type' => 'text',
            'label' => '', // display label
            'placeholder' => '',
            'required' => true,
            'options' => [],
        ];
    }

    public function removeField($id)
    {
        if (isset($this->fields[$id])) {
            unset($this->fields[$id]);
        }
    }
    public function fieldsReorder($id, $position)
    {
        $keys = array_keys($this->fields);
        $values = array_values($this->fields);

        $index = array_search($id, $keys);
        if ($index === false) {
            return;
        }

        $item = $values[$index];
        unset($values[$index], $keys[$index]);

        array_splice($values, $position, 0, [$item]);
        array_splice($keys, $position, 0, [$id]);

        $this->fields = array_combine($keys, $values);
    }
    public function addInstruction()
    {
        $this->instructions[] = '';
    }

    public function removeInstruction($index)
    {
        unset($this->instructions[$index]);
        $this->instructions = array_values($this->instructions);
    }
    public function addDetail($fields = ['field1' => '', 'field2' => ''])
    {
        $this->details[] = $fields;
    }

    public function removeDetail($key)
    {
        // Remove the detail by its key
        unset($this->details[$key]);
        $this->details = array_values($this->details);
    }

    public function editMethod($id)
    {
        $method = PaymentMethod::where('type', $this->type)->findOrFail($id);
        $this->editingMethod = $method->id;
        $this->name = $method->name;
        $this->fee_percent = $method->fee_percent;
        $this->is_active = $method->is_active;

        // Map fields with UUID keys
        $this->fields = collect($method->fields['fields'] ?? [])
            ->mapWithKeys(function ($field) {
                // Ensure field has persistent ID
                $fieldId = $field['id'] ?? (string) Str::uuid();
                $field['id'] = $fieldId; // 🔥 Persist it

                // If field is select, ensure options also persist IDs
                if (($field['type'] ?? '') === 'select' && isset($field['options'])) {
                    $field['options'] = collect($field['options'])
                        ->mapWithKeys(function ($option) {
                            $optionId = $option['id'] ?? (string) Str::uuid();
                            $option['id'] = $optionId; // 🔥 Persist it

                            return [$optionId => $option];
                        })
                        ->toArray();
                }

                return [$fieldId => $field];
            })
            ->toArray();

        // Instructions and details remain the same
        $this->instructions = $method->instructions[$this->type] ?? [];
        $this->details = $method->details[$this->type] ?? [];
    }
    public function toggleActive($id)
    {
        $method = PaymentMethod::where('type', $this->type)->findOrFail($id);

        $method->is_active = !$method->is_active;
        $method->save();
        $this->dispatch('showToast', message: $method->is_active ? 'Payment Method activated' : 'Payment Method deactivated', type: 'success');
        $this->loadMethods(); // Refresh the list
    }

    public function saveMethod()
    {
        $this->validate();

        $data = [
            'name' => $this->name,
            'fee_percent' => $this->fee_percent,
            'is_active' => $this->is_active,
            'fields' => ['fields' => $this->fields],
            'instructions' => [$this->type => $this->instructions],
            'details' => [$this->type => $this->details],
            'type' => $this->type,
        ];

        if ($this->logo) {
            $path = $this->logo->store('payment-methods', 'public');
            $data['logo'] = $path;

            // Delete old logo if editing
            if ($this->editingMethod) {
                $method = PaymentMethod::find($this->editingMethod);
                if ($method->logo) {
                    \Storage::disk('public')->delete($method->logo);
                }
            }
        }

        if ($this->editingMethod) {
            PaymentMethod::find($this->editingMethod)->update($data);
            $message = 'Method updated successfully!';
            $this->editingMethod = null;
        } else {
            PaymentMethod::create($data);
            $message = 'Method created successfully!';
        }

        $this->dispatch('showToast', message: $message, type: 'success');
        $this->resetForm();
        $this->loadMethods();
    }

    public function resetForm()
    {
        $this->name = '';
        $this->fee_percent = 0;
        $this->is_active = true;
        $this->fields = [];
        $this->instructions = [];
        $this->details = [];
        $this->logo = null;
    }

    public function deleteMethod($id)
    {
        $method = PaymentMethod::findOrFail($id);

        if ($method->logo) {
            \Storage::disk('public')->delete($method->logo);
        }

        $method->delete();
        $this->loadMethods();
        $this->resetForm();
        $this->dispatch('showToast', message: 'Method successfully deleted', type: 'success');
    }

    public function updatedFields($value, $name)
    {
        [$fieldId, $key] = explode('.', $name);

        if (!isset($this->fields[$fieldId])) {
            return;
        }

        // When admin types the field name
        if ($key === 'name') {
            $this->fields[$fieldId]['original_name'] = $value;
            $this->fields[$fieldId]['name'] = $this->makeLaravelSafe($value);

            if (empty($this->fields[$fieldId]['label'])) {
                $this->fields[$fieldId]['label'] = ucwords($value);
            }

            if (empty($this->fields[$fieldId]['placeholder'])) {
                $this->fields[$fieldId]['placeholder'] = 'Enter ' . strtolower($value);
            }
        }

        // Only act when type changes to 'select'
        if ($key === 'type' && $value === 'select') {
            if (!isset($this->fields[$fieldId]['options'])) {
                $this->fields[$fieldId]['options'] = [['label' => '', 'value' => '']];
            }
        }
    }
    protected function makeLaravelSafe(string $name): string
    {
        // Lowercase, replace spaces & special chars with underscores, remove duplicates
        $name = preg_replace('/[^a-zA-Z0-9]/', '_', $name);
        $name = preg_replace('/_+/', '_', $name);
        return strtolower(trim($name, '_'));
    }

    public function addOption($fieldId)
    {
        if (!isset($this->fields[$fieldId]['options'])) {
            $this->fields[$fieldId]['options'] = [];
        }

        $optionId = (string) Str::uuid();

        $this->fields[$fieldId]['options'][$optionId] = [
            'id' => $optionId,
            'label' => '',
            'value' => '',
        ];
    }

    public function removeOption($fieldId, $optionId)
    {
        if (isset($this->fields[$fieldId]['options'][$optionId])) {
            unset($this->fields[$fieldId]['options'][$optionId]);
        }
    }

    public function optionsReorder($encoded, $position)
    {
        // Decode field + option ID
        [$fieldId, $optionId] = explode('|', $encoded);

        if (!isset($this->fields[$fieldId]['options'][$optionId])) {
            return;
        }

        $options = $this->fields[$fieldId]['options'];

        $keys = array_keys($options);
        $values = array_values($options);

        $index = array_search($optionId, $keys);

        if ($index === false) {
            return;
        }

        $item = $values[$index];

        unset($values[$index], $keys[$index]);

        array_splice($values, $position, 0, [$item]);
        array_splice($keys, $position, 0, [$optionId]);

        $this->fields[$fieldId]['options'] = array_combine($keys, $values);
    }
    public function getLogoUrlAttribute()
    {
        return $this->logo ? asset('storage/' . $this->logo) : null;
    }
};
?>
<x-slot:title>
    {{ config('app.name') }} ||
    @php
        // Remove special characters and underscores, then capitalize each word
        $cleanType = preg_replace('/[^a-zA-Z0-9\s]/', '', str_replace('_', ' ', $type));
        $cleanType = ucwords($cleanType);
    @endphp
    {{ $editingMethod ? "Edit $cleanType Method" : "Add $cleanType Method" }}
</x-slot:title>
<div class="min-h-screen bg-gray-50 dark:bg-gray-950 p-6 space-y-6">
    <!-- Dynamic Page Title -->
    <div class="mb-4">
        <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-100">
            Manage Payment Method
        </h2>
    </div>
    {{-- Form --}}
    <div class="bg-white dark:bg-gray-900 p-6 rounded-2xl shadow space-y-6">

        <h2 class="text-2xl font-semibold text-gray-900 dark:text-gray-100">
            @php
                // Remove special characters and underscores, then capitalize each word
                $cleanType = preg_replace('/[^a-zA-Z0-9\s]/', '', str_replace('_', ' ', $type));
                $cleanType = ucwords($cleanType);
            @endphp
            {{ $editingMethod ? "Edit $cleanType Method" : "Add $cleanType Method" }} </h2>

        {{-- Method Name & Fee --}}
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <flux:input wire:model.defer="name" label="Method Name" placeholder="e.g., Crypto, PayPal" />
            <flux:input wire:model.defer="fee_percent" label="Fee %" type="number" placeholder="0" />
        </div>

        {{-- Active Toggle --}}
        <div class="flex items-center gap-3">
            <x-flux::button wire:click="$toggle('is_active')" size="sm"
                class="relative w-20 h-8 rounded-full! cursor-pointer transition-all duration-300 ease-in-out
        {{ $is_active
            ? 'bg-linear-to-r from-green-400 to-green-600 hover:from-green-500 hover:to-green-700'
            : 'bg-linear-to-r from-red-400 to-red-600 hover:from-red-500 hover:to-red-700' }}">

                {{-- Sliding Circle --}}
                <span
                    class="absolute top-0.5 left-0.5 w-7 h-7 rounded-full shadow-md transform transition-all duration-300
            {{ $is_active ? 'translate-x-12 bg-white dark:bg-white' : 'translate-x-0 bg-white dark:bg-white' }}">
                </span>

                {{-- Text Inside Toggle --}}
                <span
                    class="absolute inset-0 flex items-center justify-center text-xs font-semibold text-white pointer-events-none select-none">
                    {{ $is_active ? 'Active' : 'Inactive' }}
                </span>
            </x-flux::button>
        </div>

        {{-- Logo Upload --}}
        <div class="mb-4">
            <label class="block font-medium text-gray-700 dark:text-gray-200 mb-1">
                Logo
            </label>

            {{-- File input --}}
            <input type="file" wire:model="logo" accept="image/*"
                class="block w-full text-sm text-gray-500
        file:mr-4 file:py-2 file:px-4
        file:rounded-md file:border-0
        file:text-sm file:font-semibold
        file:bg-sky-50 dark:file:bg-sky-700
        file:text-sky-700 dark:file:text-white
        hover:file:bg-sky-100 dark:hover:file:bg-sky-600
        transition" />

            {{-- Preview --}}
            <div class="mt-2">
                @if ($logo)
                    {{-- Temporary uploaded file preview --}}
                    <img src="{{ $logo->temporaryUrl() }}" class="h-16 w-16 object-contain rounded-md border">
                @elseif($editingMethod && $methods->firstWhere('id', $editingMethod)?->logo)
                    {{-- Existing logo --}}
                    <img src="{{ $methods->firstWhere('id', $editingMethod)->logo_url }}"
                        class="h-16 w-16 object-contain rounded-md border">
                @endif
            </div>

            {{-- Validation Error --}}
            @error('logo')
                <span class="text-red-600 text-sm">{{ $message }}</span>
            @enderror
        </div>


        {{-- Dynamic Fields --}}
        <div>
            <h3 class="font-semibold text-gray-800 dark:text-gray-200 mb-2">Fields</h3>
            <div wire:sort="fieldsReorder" class="space-y-2">
                @foreach ($fields as $id => $field)
                    <div wire:key="field-{{ $id }}" wire:sort:item="{{ $id }}"
                        class="flex gap-2 items-center p-2 border border-gray-200 rounded bg-white dark:bg-gray-800">

                        <span wire:sort:handle class="cursor-move mr-2 text-gray-500">☰</span>

                        <flux:input wire:model.defer="fields.{{ $id }}.name" placeholder="Field name" />

                        <flux:select wire:model.lazy="fields.{{ $id }}.type">
                            <option value="text">Text</option>
                            <option value="number">Number</option>
                            <option value="textarea">Textarea</option>
                            <option value="file">File</option>
                            <option value="select">Select</option>
                        </flux:select>



                        <flux:input wire:model.defer="fields.{{ $id }}.label" placeholder="Label" />
                        <flux:input wire:model.defer="fields.{{ $id }}.placeholder"
                            placeholder="Placeholder (optional)" />

                        <input type="checkbox" wire:model.defer="fields.{{ $id }}.required" class="mr-2" />
                        <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Required</span>

                        <x-flux::button type="button" variant="danger" size="sm"
                            wire:click="removeField('{{ $id }}')">
                            Remove
                        </x-flux::button>
                    </div>
                    @if ($field['type'] === 'select')
                        <div class="ml-10 mt-2 space-y-2 p-3 bg-gray-50 dark:bg-gray-900 rounded-lg border">

                            <h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300">
                                Select Options
                            </h4>

                            <div wire:sort="optionsReorder" class="space-y-2">
                                @foreach ($field['options'] as $optionId => $option)
                                    <div wire:key="option-{{ $optionId }}"
                                        wire:sort:item="{{ $id }}|{{ $optionId }}"
                                        class="flex gap-2 items-center">
                                        <span wire:sort:handle class="cursor-move text-gray-500">☰</span>

                                        <flux:input
                                            wire:model.defer="fields.{{ $id }}.options.{{ $optionId }}.label"
                                            placeholder="Label" />

                                        <flux:input
                                            wire:model.defer="fields.{{ $id }}.options.{{ $optionId }}.value"
                                            placeholder="Value" />

                                        <x-flux::button type="button" variant="danger" size="sm"
                                            wire:click="removeOption('{{ $id }}','{{ $optionId }}')">
                                            Remove
                                        </x-flux::button>
                                    </div>
                                @endforeach
                            </div>

                            <x-flux::button type="button" variant="primary" color="sky" size="sm"
                                wire:click="addOption('{{ $id }}')">
                                + Add Option
                            </x-flux::button>
                        </div>
                    @endif
                @endforeach
            </div>

            <x-flux::button wire:click="addField" type="button" variant="primary" color="sky" size="sm">
                + Add Field
            </x-flux::button>
        </div>

        {{-- Instructions --}}
        <div>
            <h3 class="font-semibold text-gray-800 dark:text-gray-200 mb-2">Instructions</h3>
            <div class="space-y-2">
                @foreach ($instructions as $i => $instr)
                    <div class="flex flex-col md:flex-row gap-2 md:items-center md:gap-3">
                        <flux:input wire:model.defer="instructions.{{ $i }}" placeholder="Instruction" />
                        <x-flux::button type="button" variant="danger" size="sm"
                            wire:click="removeInstruction({{ $i }})">
                            Remove
                        </x-flux::button>
                    </div>
                @endforeach
            </div>
            <x-flux::button type="button" variant="primary" color="sky" size="sm" wire:click="addInstruction">
                + Add Instruction
            </x-flux::button>
        </div>

        {{-- details --}}
        <div>
            <h3 class="font-semibold text-gray-800 dark:text-gray-200 mb-2">Details</h3>
            <div class="space-y-2">
                @foreach ($details as $i => $detail)
                    <div class="flex flex-col md:flex-row gap-2 md:items-center md:gap-3">
                        @foreach ($detail as $field => $value)
                            <flux:input wire:model.defer="details.{{ $i }}.{{ $field }}"
                                placeholder="{{ ucfirst($field) }}" />
                        @endforeach
                        <x-flux::button type="button" variant="danger" size="sm"
                            wire:click="removeDetail({{ $i }})">
                            Remove
                        </x-flux::button>
                    </div>
                @endforeach
            </div>
            <x-flux::button type="button" variant="primary" color="sky" size="sm" wire:click="addDetail">
                + Add Detail
            </x-flux::button>
        </div>

        {{-- Save / Update --}}
        <x-flux::button wire:click="saveMethod" color="sky" variant="primary" class="w-full">
            {{ $editingMethod ? 'Update Method' : 'Save Method' }}
        </x-flux::button>
    </div>

    {{-- List of Deposit Methods --}}
    <div class="space-y-4">
        @foreach ($methods as $method)
            <div
                class="flex flex-col md:flex-row md:justify-between md:items-center p-5 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-2xl shadow-sm hover:shadow-lg transition">

                {{-- Left: Method Info --}}
                <div class="flex flex-col md:flex-row md:items-center md:gap-6">
                    <div class="flex items-center gap-3">
                        {{-- Icon based on method name --}}
                        <div
                            class="flex h-12 w-12 items-center justify-center rounded-xl 
           bg-white/30 dark:bg-gray-500/30 
           backdrop-blur-sm backdrop-saturate-150 
           border border-white/20 dark:border-gray-400/20 
           shadow-inner">
                            @if ($method->logo)
                                <img src="{{ $method->logo_url }}" alt="{{ $method->name }} logo"
                                    class="h-7 w-7 object-contain">
                            @else
                                <x-icons.default-payment class="w-7 h-7 text-sky-300 dark:text-gray-200" />
                            @endif
                        </div>
                        {{-- Method Info Text --}}
                        <div class="flex flex-col">

                            <span
                                class="font-semibold text-gray-900 dark:text-gray-100 text-lg">{{ $method->name }}</span>
                            <span class="text-sm text-gray-500 dark:text-gray-400">{{ $method->fee_percent }}%
                                fee</span>
                        </div>
                    </div>
                </div>

                {{-- Right: Actions --}}
                <div class="flex items-center gap-4 mt-4 md:mt-0">
                    {{-- Active Toggle --}}
                    <div class="flex items-center gap-3">
                        <x-flux::button variant="primary" size="sm"
                            wire:click="toggleActive({{ $method->id }})"
                            class="relative w-20 h-8 rounded-full cursor-pointer transition-all duration-300 ease-in-out
        {{ $method->is_active
            ? 'bg-linear-to-r from-green-400 to-green-600 hover:from-green-500 hover:to-green-700'
            : 'bg-linear-to-r from-red-400 to-red-600 hover:from-red-500 hover:to-red-700' }}">

                            {{-- Sliding Circle --}}
                            <span
                                class="absolute top-0.5 left-0.5 w-7 h-7 rounded-full shadow-md transform transition-all duration-300
            {{ $method->is_active ? 'translate-x-12 bg-white dark:bg-white' : 'translate-x-0 bg-white dark:bg-white' }}">
                            </span>

                            {{-- Text Inside Toggle --}}
                            <span
                                class="absolute inset-0 flex items-center justify-center text-xs font-semibold text-white pointer-events-none select-none">
                                {{ $method->is_active ? 'Active' : 'Inactive' }}
                            </span>
                        </x-flux::button>
                    </div>

                    {{-- Edit Button --}}
                    <x-flux::button type="button" variant="primary" color="sky" size="sm"
                        wire:click="editMethod({{ $method->id }})">
                        Edit
                    </x-flux::button>

                    {{-- Delete Button --}}
                    <x-flux::button wire:click="deleteMethod({{ $method->id }})"
                        wire:confirm="Are you sure you want to delete this method?" type="button" variant="danger">
                        Delete
                    </x-flux::button>

                </div>
            </div>
        @endforeach
    </div>
</div>
