<?php

namespace App\Livewire\Admin;

use App\Models\LearnerForm;
use App\Models\LearnerFormField;
use App\Services\FlashMessageService;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class LearnerFormBuilder extends Component
{
    public $formId;
    public $formName = '';
    public $formDescription = '';
    public $isActive = true;
    public $editMode = false;

    public $fields = [];
    public $newField = [
        'field_name' => '',
        'field_label' => '',
        'field_type' => 'text',
        'field_options' => [],
        'is_required' => false,
        'placeholder' => '',
        'help_text' => '',
        'sort_order' => 0,
    ];

    protected $rules = [
        'formName' => 'required|string|max:255',
        'formDescription' => 'nullable|string|max:1000',
        'isActive' => 'boolean',
    ];

    protected $messages = [
        'formName.required' => 'Form name is required.',
        'formName.max' => 'Form name must not exceed 255 characters.',
        'formDescription.max' => 'Form description must not exceed 1000 characters.',
    ];

    public function mount($formId = null)
    {
        if ($formId) {
            $this->editMode = true;
            $this->formId = $formId;
            $form = LearnerForm::with('fields')->findOrFail($formId);

            // Check permissions
            if (!Auth::user()->can('learners.edit')) {
                abort(403, 'Unauthorized to edit learner forms.');
            }

            $this->formName = $form->name;
            $this->formDescription = $form->description;
            $this->isActive = $form->is_active;

            // Load existing fields
            $this->fields = $form->fields->map(function ($field) {
                return [
                    'id' => $field->id,
                    'field_name' => $field->field_name,
                    'field_label' => $field->field_label,
                    'field_type' => $field->field_type,
                    'field_options' => $field->field_options ?? [],
                    'is_required' => $field->is_required,
                    'placeholder' => $field->placeholder,
                    'help_text' => $field->help_text,
                    'sort_order' => $field->sort_order,
                ];
            })->toArray();
        } else {
            // Check permissions
            if (!Auth::user()->can('learners.create')) {
                abort(403, 'Unauthorized to create learner forms.');
            }

            // Initialize with default fields
            $this->fields = [
                [
                    'id' => 'first_name',
                    'field_name' => 'first_name',
                    'field_label' => 'First Name',
                    'field_type' => 'text',
                    'field_options' => [],
                    'is_required' => true,
                    'placeholder' => 'Enter first name',
                    'help_text' => '',
                    'sort_order' => 1,
                ],
                [
                    'id' => 'last_name',
                    'field_name' => 'last_name',
                    'field_label' => 'Last Name',
                    'field_type' => 'text',
                    'field_options' => [],
                    'is_required' => true,
                    'placeholder' => 'Enter last name',
                    'help_text' => '',
                    'sort_order' => 2,
                ],
                [
                    'id' => 'email',
                    'field_name' => 'email',
                    'field_label' => 'Email',
                    'field_type' => 'email',
                    'field_options' => [],
                    'is_required' => true,
                    'placeholder' => 'Enter email address',
                    'help_text' => '',
                    'sort_order' => 3,
                ],
            ];
        }
    }

    public function addField()
    {
        if (empty($this->newField['field_label'])) {
            FlashMessageService::error('Field label is required.', 'Validation Error');
            $this->dispatch('flashMessage', 'error', 'Field label is required.', 'Validation Error', 5000);
            return;
        }

        $this->newField['sort_order'] = count($this->fields) + 1;
        $this->fields[] = $this->newField;
        $this->newField = [
            'field_name' => '',
            'field_label' => '',
            'field_type' => 'text',
            'field_options' => [],
            'is_required' => false,
            'placeholder' => '',
            'help_text' => '',
            'sort_order' => 0,
        ];

        FlashMessageService::success('Field added successfully!', 'Field Added');
        $this->dispatch('flashMessage', 'success', 'Field added successfully!', 'Field Added', 3000);
        
        // Dispatch event to clear form inputs
        $this->dispatch('field-added');
        
        // Reset the new field form for adding another field
        $this->reset(['newField']);
        $this->newField = [
            'field_name' => '',
            'field_label' => '',
            'field_type' => 'text',
            'field_options' => [],
            'is_required' => false,
            'placeholder' => '',
            'help_text' => '',
            'sort_order' => 0,
        ];
    }


    private function generateFieldName($fieldLabel)
    {
        // Convert field label to snake_case field name
        return strtolower(preg_replace('/[^a-zA-Z0-9]+/', '_', trim($fieldLabel)));
    }

    public function removeField($index)
    {
        // Don't allow removing mandatory fields
        $fieldName = $this->fields[$index]['field_name'];
        if (in_array($fieldName, ['first_name', 'last_name', 'email'])) {
            FlashMessageService::error('Cannot remove mandatory fields.', 'Cannot Remove');
            $this->dispatch('flashMessage', 'error', 'Cannot remove mandatory fields.', 'Cannot Remove', 5000);
            return;
        }

        unset($this->fields[$index]);
        $this->fields = array_values($this->fields);

        // Reorder fields
        foreach ($this->fields as $index => $field) {
            $this->fields[$index]['sort_order'] = $index + 1;
        }

        FlashMessageService::success('Field removed successfully!', 'Field Removed');
        $this->dispatch('flashMessage', 'success', 'Field removed successfully!', 'Field Removed', 3000);
    }

    public function moveFieldUp($index)
    {
        if ($index > 0) {
            $temp = $this->fields[$index];
            $this->fields[$index] = $this->fields[$index - 1];
            $this->fields[$index - 1] = $temp;

            // Update sort order
            $this->fields[$index]['sort_order'] = $index + 1;
            $this->fields[$index - 1]['sort_order'] = $index;
        }
    }

    public function moveFieldDown($index)
    {
        if ($index < count($this->fields) - 1) {
            $temp = $this->fields[$index];
            $this->fields[$index] = $this->fields[$index + 1];
            $this->fields[$index + 1] = $temp;

            // Update sort order
            $this->fields[$index]['sort_order'] = $index + 1;
            $this->fields[$index + 1]['sort_order'] = $index + 2;
        }
    }

    public function updateFieldOptions($index, $options)
    {
        $this->fields[$index]['field_options'] = array_filter(array_map('trim', explode("\n", $options)));
    }

    public function save()
    {
        // Check permissions
        if ($this->editMode && !Auth::user()->can('learners.edit')) {
            FlashMessageService::error('You do not have permission to edit learner forms.', 'Insufficient Permissions');
            $this->dispatch('flashMessage', 'error', 'You do not have permission to edit learner forms.', 'Insufficient Permissions', 8000);
            return;
        } elseif (!$this->editMode && !Auth::user()->can('learners.create')) {
            FlashMessageService::error('You do not have permission to create learner forms.', 'Insufficient Permissions');
            $this->dispatch('flashMessage', 'error', 'You do not have permission to create learner forms.', 'Insufficient Permissions', 8000);
            return;
        }

        $this->validate();

        try {
            $formData = [
                'name' => $this->formName,
                'description' => $this->formDescription ?: null,
                'is_active' => $this->isActive,
                'created_by' => Auth::id(),
            ];

            if ($this->editMode) {
                $form = LearnerForm::findOrFail($this->formId);
                $form->update($formData);

                // Delete existing fields
                $form->fields()->delete();
            } else {
                $form = LearnerForm::create($formData);
            }

            // Save fields
            foreach ($this->fields as $fieldData) {
                $form->fields()->create([
                    'field_name' => $fieldData['field_name'],
                    'field_label' => $fieldData['field_label'],
                    'field_type' => $fieldData['field_type'],
                    'field_options' => $fieldData['field_options'],
                    'is_required' => $fieldData['is_required'],
                    'placeholder' => $fieldData['placeholder'],
                    'help_text' => $fieldData['help_text'],
                    'sort_order' => $fieldData['sort_order'],
                ]);
            }

            if ($this->editMode) {
                FlashMessageService::success('Form updated successfully!', 'Form Updated');
                $this->dispatch('flashMessage', 'success', 'Form updated successfully!', 'Form Updated', 5000);
            } else {
                FlashMessageService::success('Form created successfully!', 'Form Created');
                $this->dispatch('flashMessage', 'success', 'Form created successfully!', 'Form Created', 5000);
            }

            // Don't redirect - stay on the same page
            // return redirect()->route('admin.learner-forms');
        } catch (\Exception $e) {
            FlashMessageService::error('Failed to save form: ' . $e->getMessage(), 'Save Failed');
            $this->dispatch('flashMessage', 'error', 'Failed to save form: ' . $e->getMessage(), 'Save Failed', 8000);
            \Log::error('Form save error: ' . $e->getMessage());
        }
    }

    public function cancel()
    {
        return redirect()->route('admin.learner-forms');
    }

    public function render()
    {
        return view('livewire.admin.learner-form-builder');
    }
}