<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ProfileLinkChangedMail extends Mailable implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    protected $recipient;
    protected $linkedProfile;
    protected $action; // 'attached' or 'detached'
    protected $buttonUrl;
    public $locale;

    /**
     * Create a new message instance.
     *
     * @param mixed $recipient The profile receiving the notification
     * @param mixed $linkedProfile The profile that was attached/detached
     * @param string $action Either 'attached' or 'detached'
     * @return void
     */
    public function __construct($recipient, $linkedProfile, $action = 'attached')
    {
        $this->recipient = $recipient;
        $this->linkedProfile = $linkedProfile;
        $this->action = $action;

        Log::info('ProfileLinkChangedMail: Constructor called', [
            'recipient_id' => $recipient->id,
            'recipient_type' => get_class($recipient),
            'recipient_lang_preference' => $recipient->lang_preference ?? 'not set',
            'linked_profile_id' => $linkedProfile->id,
            'linked_profile_type' => get_class($linkedProfile),
            'action' => $action,
        ]);

        // Support lang_preference for User, Organization, Bank, and Admin models
        $this->locale = $recipient->lang_preference ?? config('app.fallback_locale');

        // Ensure locale is not empty
        if (empty($this->locale)) {
            $this->locale = config('app.fallback_locale');
        }

        Log::info('ProfileLinkChangedMail: Locale determined', [
            'locale' => $this->locale,
        ]);

        // Generate localized URL to the linked profile
        $linkedProfileType = strtolower(class_basename($linkedProfile));
        $translatedType = __($linkedProfileType, [], $this->locale);

        Log::info('ProfileLinkChangedMail: Profile type translation', [
            'original_type' => $linkedProfileType,
            'translated_type' => $translatedType,
        ]);

        if ($linkedProfile) {
            // For attached action, use direct login routes for elevated profiles
            // This allows the user to log in to the profile directly from the email
            // After successful login, user will be redirected to main page
            if ($this->action === 'attached') {
                $profileClass = get_class($linkedProfile);

                if ($profileClass === 'App\\Models\\Organization') {
                    // Direct login to organization - redirects to main page after login
                    $this->buttonUrl = LaravelLocalization::localizeURL(
                        route('organization.direct-login', ['organizationId' => $linkedProfile->id]),
                        $this->locale
                    );
                } elseif ($profileClass === 'App\\Models\\Bank') {
                    // Direct login to bank - redirects to main page after login
                    $this->buttonUrl = LaravelLocalization::localizeURL(
                        route('bank.direct-login', ['bankId' => $linkedProfile->id]),
                        $this->locale
                    );
                } elseif ($profileClass === 'App\\Models\\Admin') {
                    // Direct login to admin - redirects to main page after login
                    $this->buttonUrl = LaravelLocalization::localizeURL(
                        route('admin.direct-login', ['adminId' => $linkedProfile->id]),
                        $this->locale
                    );
                } else {
                    // For User profiles or other types, just link to the profile page
                    $this->buttonUrl = LaravelLocalization::localizeURL(
                        route('profile.show_by_type_and_id', ['type' => $translatedType, 'id' => $linkedProfile->id]),
                        $this->locale
                    );
                }
            } else {
                // For detached action, just link to the profile page
                $this->buttonUrl = LaravelLocalization::localizeURL(
                    route('profile.show_by_type_and_id', ['type' => $translatedType, 'id' => $linkedProfile->id]),
                    $this->locale
                );
            }

            Log::info('ProfileLinkChangedMail: Generated button URL', [
                'button_url' => $this->buttonUrl,
                'profile_class' => get_class($linkedProfile),
                'action' => $this->action,
            ]);
        } else {
            Log::warning('ProfileLinkChangedMail: Unknown linked profile type');
        }
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // Set application locale for this email
        app()->setLocale($this->locale);

        $subjectKey = $this->action === 'attached'
            ? 'messages.profile_link_attached_subject'
            : 'messages.profile_link_detached_subject';

        $subject = trans($subjectKey, [], $this->locale);
        $template = 'emails.profile-links.link-changed';

        Log::info('ProfileLinkChangedMail: Building email', [
            'action' => $this->action,
            'subject_key' => $subjectKey,
            'subject' => $subject,
            'template' => $template,
            'locale' => $this->locale,
            'from_email' => timebank_config('mail.support.email'),
            'from_name' => timebank_config('mail.support.name'),
        ]);

        return $this
            ->from(timebank_config('mail.support.email'), timebank_config('mail.support.name'))
            ->subject($subject)
            ->view($template)
            ->with([
                'action' => $this->action,
                'recipient' => $this->recipient,
                'linkedProfile' => $this->linkedProfile,
                'buttonUrl' => $this->buttonUrl,
                'locale' => $this->locale,
            ]);
    }
}
