<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use App\Models\EmailTemplate;
use App\Models\Setting;

class EmailTemplates extends Component
{
    public $templates;
    public $editingTemplate = null;
    public $name;
    public $subject;
    public $body;
    public $enabled;
    public $showEditModal = false;
    public $showPreviewModal = false;

    // Email/SMTP Settings
    public $mail_mailer = 'smtp';
    public $mail_host = '';
    public $mail_port = 587;
    public $mail_username = '';
    public $mail_password = '';
    public $mail_encryption = 'tls';
    public $mail_from_address = '';
    public $mail_from_name = '';

    // AWS SES Settings
    public $aws_access_key_id = '';
    public $aws_secret_access_key = '';
    public $aws_default_region = 'us-east-1';

    // Email Branding Settings
    public $email_logo_url = '';
    public $email_primary_color = '#667eea';
    public $email_secondary_color = '#764ba2';

    protected $rules = [
        'subject' => 'required|string|max:255',
        'body' => 'required|string',
        'enabled' => 'boolean',
    ];

    public function mount()
    {
        $this->loadTemplates();
        $this->loadEmailSettings();
    }

    public function loadTemplates()
    {
        $this->templates = EmailTemplate::orderBy('name')->get();
    }

    public function loadEmailSettings()
    {
        $this->mail_mailer = Setting::get('mail_mailer', 'smtp');
        $this->mail_host = Setting::get('mail_host', '');
        $this->mail_port = Setting::get('mail_port', 587);
        $this->mail_username = Setting::get('mail_username', '');
        $this->mail_password = Setting::get('mail_password', '');
        $this->mail_encryption = Setting::get('mail_encryption', 'tls');
        $this->mail_from_address = Setting::get('mail_from_address', '');
        $this->mail_from_name = Setting::get('mail_from_name', '');
        $this->aws_access_key_id = Setting::get('aws_access_key_id', '');
        $this->aws_secret_access_key = Setting::get('aws_secret_access_key', '');
        $this->aws_default_region = Setting::get('aws_default_region', 'us-east-1');

        // Load email branding settings
        $this->email_logo_url = Setting::get('email_logo_url', '');
        $this->email_primary_color = Setting::get('email_primary_color', '#667eea');
        $this->email_secondary_color = Setting::get('email_secondary_color', '#764ba2');
    }

    public function editTemplate($id)
    {
        $template = EmailTemplate::findOrFail($id);
        $this->editingTemplate = $template->id;
        $this->name = $template->name;
        $this->subject = $template->subject;
        $this->body = $template->body;
        $this->enabled = $template->enabled;
        $this->showEditModal = true;

        // Dispatch event to initialize TinyMCE
        $this->dispatch('editTemplateOpened');
    }

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

        $template = EmailTemplate::findOrFail($this->editingTemplate);
        $template->update([
            'subject' => $this->subject,
            'body' => $this->body,
            'enabled' => $this->enabled,
        ]);

        session()->flash('success', 'Email template updated successfully!');

        $this->closeModal();
        $this->loadTemplates();
    }

    public function toggleEnabled($id)
    {
        $template = EmailTemplate::findOrFail($id);
        $template->update(['enabled' => !$template->enabled]);

        session()->flash('success', 'Template ' . ($template->enabled ? 'enabled' : 'disabled') . ' successfully!');

        $this->loadTemplates();
    }

    public function previewTemplate($id)
    {
        $template = EmailTemplate::findOrFail($id);
        $this->name = $template->name;
        $this->subject = $template->subject;
        $this->body = $template->body;
        $this->showPreviewModal = true;
    }

    public function closeModal()
    {
        $this->showEditModal = false;
        $this->showPreviewModal = false;
        $this->reset(['editingTemplate', 'name', 'subject', 'body', 'enabled']);

        // Dispatch event to cleanup TinyMCE
        $this->dispatch('editorClosed');
    }

    public function saveEmailSettings()
    {
        $this->validate([
            'mail_mailer' => 'required|in:smtp,ses,log',
            'mail_host' => 'required_if:mail_mailer,smtp|nullable|string|max:255',
            'mail_port' => 'required_if:mail_mailer,smtp|nullable|integer|min:1|max:65535',
            'mail_username' => 'nullable|string|max:255',
            'mail_password' => 'nullable|string|max:255',
            'mail_encryption' => 'nullable|in:tls,ssl',
            'mail_from_address' => 'required|email|max:255',
            'mail_from_name' => 'required|string|max:255',
            'aws_access_key_id' => 'required_if:mail_mailer,ses|nullable|string|max:255',
            'aws_secret_access_key' => 'required_if:mail_mailer,ses|nullable|string|max:255',
            'aws_default_region' => 'required_if:mail_mailer,ses|nullable|string|max:50',
        ]);

        Setting::set('mail_mailer', $this->mail_mailer);
        Setting::set('mail_host', $this->mail_host);
        Setting::set('mail_port', $this->mail_port);
        Setting::set('mail_username', $this->mail_username);
        Setting::set('mail_password', $this->mail_password);
        Setting::set('mail_encryption', $this->mail_encryption);
        Setting::set('mail_from_address', $this->mail_from_address);
        Setting::set('mail_from_name', $this->mail_from_name);
        Setting::set('aws_access_key_id', $this->aws_access_key_id);
        Setting::set('aws_secret_access_key', $this->aws_secret_access_key);
        Setting::set('aws_default_region', $this->aws_default_region);

        // Save email branding settings
        Setting::set('email_logo_url', $this->email_logo_url);
        Setting::set('email_primary_color', $this->email_primary_color);
        Setting::set('email_secondary_color', $this->email_secondary_color);

        session()->flash('email_success', 'Email settings updated successfully!');
    }

    public function getTemplateName($name)
    {
        return match ($name) {
            'welcome' => 'Welcome Email',
            'verify_email' => 'Email Verification',
            'reset_password' => 'Reset Password',
            'booking_success' => 'Booking Success',
            default => ucwords(str_replace('_', ' ', $name)),
        };
    }

    public function getPlaceholders($name)
    {
        $common = '{{site_name}}, {{site_url}}, {{logo_url}}, {{year}}, {{user_name}}';

        return match ($name) {
            'welcome' => $common,
            'verify_email' => $common . ', {{verification_url}}',
            'reset_password' => $common . ', {{reset_url}}',
            'booking_success' => $common . ', {{customer_name}}, {{invoice_number}}, {{listing_title}}, {{check_in}}, {{check_out}}, {{guests}}, {{total_price}}, {{host_name}}, {{host_email}}, {{host_phone}}, {{receipt_url}}',
            default => $common,
        };
    }

    public function render()
    {
        return view('livewire.admin.email-templates')->layout('layouts.app');
    }
}
