<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Namu\WireChat\Events\MessageCreated;
use Namu\WireChat\Models\Group;

class NewMessageMail extends Mailable
{
    use Queueable, SerializesModels;

    public $event;
    public $sender;
    public $recipient;
    public $language;

    /**
     * Create a new message instance.
     *
     * @param  MessageCreated  $event
     * @param  mixed  $sender
     * @param  mixed  $recipient
     * @param  string  $language
     * @return void
     */
    public function __construct(MessageCreated $event, $sender, $recipient, $language = null)
    {
        $this->event = $event;
        $this->sender = $sender;
        $this->recipient = $recipient;
        $this->language = $language ?? $recipient->lang_preference ?? config('app.locale', 'en');
    }

    /**
     * Get the message envelope.
     *
     * @return \Illuminate\Mail\Mailables\Envelope
     */
    public function envelope()
    {
        return new Envelope(
            from: new \Illuminate\Mail\Mailables\Address(timebank_config('mail.chat_messenger.email'), timebank_config('mail.chat_messenger.name')),
            subject: trans('mail.new_message_subject', [], $this->language),
        );
    }

    /**
     * Get the message content definition.
     *
     * @return \Illuminate\Mail\Mailables\Content
     */
    public function content()
    {
        // Set application locale for this email
        app()->setLocale($this->language);

        $language = $this->recipient->lang_preference ?? config('app.fallback_locale', 'en');

        Log::info('Content generated', [
            'recipient_id' => $this->recipient->id,
            'recipient_type' => get_class($this->recipient),
            'language' => $language,
            'recipient_lang_preference' => $this->recipient->lang_preference,
        ]);

        // Ensure conversation is loaded
        if (!$this->event->message->relationLoaded('conversation')) {
            $this->event->message->load('conversation.participants');
        }

        // Prepare data for the view
        $conversationId = $this->event->message->conversation->id;

        // Generate appropriate URL based on recipient type
        // For organizations, banks, and admins, use direct login URL
        $chatRoute = route('chat', ['conversation' => $conversationId]);

        if ($this->recipient instanceof \App\Models\Organization) {
            $baseUrl = route('organization.direct-login', [
                'organizationId' => $this->recipient->id,
                'intended' => $chatRoute
            ]);
            $conversationUrl = LaravelLocalization::localizeURL($baseUrl, $this->language);
        } elseif ($this->recipient instanceof \App\Models\Bank) {
            $baseUrl = route('bank.direct-login', [
                'bankId' => $this->recipient->id,
                'intended' => $chatRoute
            ]);
            $conversationUrl = LaravelLocalization::localizeURL($baseUrl, $this->language);
        } elseif ($this->recipient instanceof \App\Models\Admin) {
            $baseUrl = route('admin.direct-login', [
                'adminId' => $this->recipient->id,
                'intended' => $chatRoute
            ]);
            $conversationUrl = LaravelLocalization::localizeURL($baseUrl, $this->language);
        } else {
            // For regular users, just use the chat URL
            $conversationUrl = LaravelLocalization::localizeURL($chatRoute, $this->language);
        }
        // Check if it's a group conversation
        $isGroupChat = $this->event->message->conversation->participants()->count() > 2;
        $group = $isGroupChat ? Group::where('conversation_id', $conversationId)->first() : null;
        $groupName = $isGroupChat
            ? ($group && !empty($group->name)
                ? $group->name
                : trans('mail.group_conversation', [], $this->language))
            : null;

        return new Content(
            markdown: 'emails.messages.new',
            with: [
                'senderName' =>  $this->sender->full_name ?? $this->sender->name,
                'recipientName' => $this->recipient->full_name ?? $this->recipient->name,
                'messageContent' => $this->event->message->body,
                'conversationUrl' => $conversationUrl,
                'isGroupChat' => $isGroupChat,
                'groupName' => $groupName,
            ],
        );
    }
}
