<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Mail\ContactFormMailable;
use App\Mail\ContactFormCopyMailable;
use Illuminate\Support\Facades\Mail;
use WireUi\Traits\WireUiActions;

/**
 * Generic contact form component with context-aware content
 *
 * Usage examples:
 * - @livewire('contact-form', ['context' => 'contact'])
 * - @livewire('contact-form', ['context' => 'report-issue'])
 * - @livewire('contact-form', ['context' => 'report-error', 'url' => request()->fullUrl()])
 * - @livewire('contact-form', ['context' => 'delete-profile'])
 */
class ContactForm extends Component
{
    use WireUiActions;

    // Form context: 'contact', 'report-issue', 'report-error', 'delete-profile'
    public $context = 'contact';

    // Form fields
    public $name;
    public $full_name;
    public $email;
    public $subject;
    public $message;
    public $url; // For error/issue reporting - URL where issue occurred

    // UI state
    public $showSuccessMessage = false;

    protected $rules = [
        'name' => 'required|string|max:255',
        'full_name' => 'nullable|string|max:255',
        'email' => 'required|email|max:255',
        'subject' => 'nullable|string|max:255',
        'message' => 'required|string|min:10|max:2000',
        'url' => 'nullable|url|max:500',
    ];

    public function mount($context = 'contact', $url = null, $subject = null, $message = null)
    {
        $this->context = $context;
        $this->url = $url;

        // Pre-fill subject/message from params or query string
        $this->subject = $subject ?? request('subject');
        $this->message = $message ?? request('message');

        // Pre-fill user data if authenticated
        if (auth()->check()) {
            $profile = getActiveProfile();
            if ($profile) {
                $this->name = $profile->name ?? '';
                $this->full_name = $profile->full_name ?? $profile->name ?? '';
                $this->email = $profile->email ?? '';
            }
        }
    }

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

    public function submitForm()
    {
        $data = $this->validate();
        $data['context'] = $this->context;

        // Ensure full_name is set, fallback to name if not
        if (empty($data['full_name'])) {
            $data['full_name'] = $data['name'];
        }

        // Add authentication and profile data
        $data['is_authenticated'] = auth()->check();
        if ($data['is_authenticated']) {
            $profile = getActiveProfile();
            if ($profile) {
                $data['profile_url'] = $profile->profile_url ?? null;
                $data['profile_type'] = class_basename(get_class($profile));
                $data['profile_lang_preference'] = $profile->lang_preference ?? null;
            }
        }

        // Add browser locale (current app locale) for non-authenticated users
        if (!$data['is_authenticated']) {
            $data['browser_locale'] = app()->getLocale();
        }

        try {
            // Get recipient email from config or default
            $recipientEmail = config('mail.from.address', 'info@timebank.cc');

            \Log::info('ContactForm: Queueing emails', [
                'context' => $this->context,
                'recipient' => $recipientEmail,
                'submitter' => $data['email'],
            ]);

            // Queue email to the recipient on 'emails' queue
            Mail::to($recipientEmail)->queue((new ContactFormMailable($data))->onQueue('emails'));
            \Log::info('ContactForm: Email queued to recipient');

            // Queue a copy to the submitter on 'emails' queue
            Mail::to($data['email'])->queue((new ContactFormCopyMailable($data))->onQueue('emails'));
            \Log::info('ContactForm: Copy queued to submitter');

            // Show success notification
            $this->notification()->success(
                title: __('Message sent'),
                description: __('We received your message successfully and will get back to you shortly!')
            );

            $this->showSuccessMessage = true;
            $this->resetForm();

            // Dispatch event for parent components
            $this->dispatch('contact-form-submitted');

        } catch (\Exception $e) {
            $this->notification()->error(
                title: __('Error'),
                description: __('Sorry, there was an error sending your message. Please try again later.')
            );

            \Log::error('Contact form submission failed', [
                'error' => $e->getMessage(),
                'context' => $this->context,
                'email' => $this->email
            ]);
        }
    }

    private function resetForm()
    {
        $this->message = '';
        $this->subject = '';
        $this->url = '';

        // Don't reset name/email if user is authenticated
        if (!auth()->check()) {
            $this->name = '';
            $this->full_name = '';
            $this->email = '';
        }
    }

    public function getSubmitButtonTextProperty()
    {
        return match($this->context) {
            'report-issue' => __('Submit report'),
            'report-error' => __('Report error'),
            'delete-profile' => __('Request deletion'),
            'contact' => __('Send message'),
            default => __('Submit'),
        };
    }

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