<?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 ProfileEditedByAdminMail extends Mailable implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    protected $profile;
    protected $changedFields;
    protected $buttonUrl;
    public $locale;

    /**
     * Create a new message instance.
     *
     * @param mixed $profile The profile that was edited
     * @param array $changedFields Array of field names that were changed
     * @return void
     */
    public function __construct($profile, $changedFields = [])
    {
        $this->profile = $profile;

        // Normalize changedFields: support both ['field1', 'field2'] and ['field1' => ['old' => 'x', 'new' => 'y']]
        $normalizedFields = [];
        foreach ($changedFields as $key => $value) {
            if (is_array($value)) {
                // Format: ['field1' => ['old' => 'x', 'new' => 'y']]
                $normalizedFields[] = $key;
            } else {
                // Format: ['field1', 'field2']
                $normalizedFields[] = $value;
            }
        }

        // Filter out 'comment' field as it's admin-only
        $this->changedFields = array_filter($normalizedFields, function($field) {
            return $field !== 'comment';
        });

        Log::info('ProfileEditedByAdminMail: Constructor called', [
            'profile_id' => $profile->id,
            'profile_type' => get_class($profile),
            'profile_lang_preference' => $profile->lang_preference ?? 'not set',
            'changed_fields' => $changedFields,
        ]);

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

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

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

        // Generate the appropriate login URL based on profile type
        $profileClass = get_class($profile);

        if ($profileClass === 'App\\Models\\User') {
            // Get the localized profile.edit URL for this profile's language
            $profileEditPath = LaravelLocalization::getURLFromRouteNameTranslated(
                $this->locale,
                'routes.profile.edit'
            );
            // Convert to absolute URL
            $profileEditUrl = url($profileEditPath);

            // Direct user login with redirect to profile.edit and username pre-filled
            $this->buttonUrl = LaravelLocalization::localizeURL(
                route('user.direct-login', [
                    'userId' => $profile->id,
                    'intended' => $profileEditUrl,
                    'name' => $profile->name
                ]),
                $this->locale
            );
        } elseif ($profileClass === 'App\\Models\\Organization') {
            // Get the localized profile.edit URL for this profile's language
            $profileEditPath = LaravelLocalization::getURLFromRouteNameTranslated(
                $this->locale,
                'routes.profile.edit'
            );
            // Convert to absolute URL
            $profileEditUrl = url($profileEditPath);

            // Direct organization login with redirect to profile.edit
            $this->buttonUrl = LaravelLocalization::localizeURL(
                route('organization.direct-login', ['organizationId' => $profile->id, 'intended' => $profileEditUrl]),
                $this->locale
            );
        } elseif ($profileClass === 'App\\Models\\Bank') {
            // Get the localized profile.edit URL for this profile's language
            $profileEditPath = LaravelLocalization::getURLFromRouteNameTranslated(
                $this->locale,
                'routes.profile.edit'
            );
            // Convert to absolute URL
            $profileEditUrl = url($profileEditPath);

            // Direct bank login with redirect to profile.edit
            $this->buttonUrl = LaravelLocalization::localizeURL(
                route('bank.direct-login', ['bankId' => $profile->id, 'intended' => $profileEditUrl]),
                $this->locale
            );
        } elseif ($profileClass === 'App\\Models\\Admin') {
            // Get the localized profile.settings URL for admin profiles
            $profileSettingsPath = LaravelLocalization::getURLFromRouteNameTranslated(
                $this->locale,
                'routes.profile.settings'
            );
            // Convert to absolute URL
            $profileSettingsUrl = url($profileSettingsPath);

            // Direct admin login with redirect to profile.settings
            $this->buttonUrl = LaravelLocalization::localizeURL(
                route('admin.direct-login', ['adminId' => $profile->id, 'intended' => $profileSettingsUrl]),
                $this->locale
            );
        } else {
            // Fallback to main login
            $this->buttonUrl = LaravelLocalization::localizeURL(
                route('login'),
                $this->locale
            );
        }

        Log::info('ProfileEditedByAdminMail: Generated button URL', [
            'button_url' => $this->buttonUrl,
            'profile_class' => $profileClass,
        ]);
    }

    /**
     * Translate field names to human-readable labels
     *
     * @param string $fieldName
     * @return string
     */
    protected function translateFieldName($fieldName)
    {
        $translations = [
            'name' => trans('Username', [], $this->locale),
            'full_name' => trans('Full name', [], $this->locale),
            'level' => trans('Bank level', [], $this->locale),
            'email' => trans('Email', [], $this->locale),
            'about_short' => trans('Short introduction', [], $this->locale),
            'about' => trans('Long introduction', [], $this->locale),
            'motivation' => trans('Motivation to Timebank', [], $this->locale),
            'website' => trans('Website', [], $this->locale),
            'phone' => trans('Phone', [], $this->locale),
            'inactive_at' => trans('Re-activate', [], $this->locale),
        ];

        return $translations[$fieldName] ?? ucfirst(str_replace('_', ' ', $fieldName));
    }

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

        $subject = trans('messages.profile_edited_by_admin_subject', [], $this->locale);
        $template = 'emails.profile-edited.profile-edited';

        // Translate field names
        $translatedFields = array_map(function($field) {
            return $this->translateFieldName($field);
        }, $this->changedFields);

        Log::info('ProfileEditedByAdminMail: Building email', [
            'subject' => $subject,
            'template' => $template,
            'locale' => $this->locale,
            'from_email' => timebank_config('mail.support.email'),
            'from_name' => timebank_config('mail.support.name'),
            'translated_fields' => $translatedFields,
        ]);

        return $this
            ->from(timebank_config('mail.support.email'), timebank_config('mail.support.name'))
            ->subject($subject)
            ->view($template)
            ->with([
                'profile' => $this->profile,
                'changedFields' => $translatedFields,
                'buttonUrl' => $this->buttonUrl,
            ]);
    }
}
