<template>
    <div>
        <h1 class="text-3xl font-bold mb-4 text-gray-800">{{ $t('Email Settings') }}</h1>
        <div class="border-b border-gray-100 mb-4"></div>

        <div class="space-y-4">
            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('From Name')"
                            :help="$t('Name that appears in the From field of outbound emails.')"
                        />
                    </div>
                    <div class="settings-control">
                        <FormInput
                            v-model="form.from_name"
                            class="w-full"
                            type="text"
                            :placeholder="$t('e.g. Support Team')"
                        />
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('From Email')"
                            :help="$t('Email address used in the From field of outbound emails.')"
                        />
                    </div>
                    <div class="settings-control">
                        <FormInput
                            v-model="form.from_email"
                            type="email"
                            placeholder="support@example.com"
                            class="w-full"
                        />
                    </div>
                </div>


                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Reply-To Email')"
                            :help="$t('Address where replies should be sent. Defaults to From Email if empty.')"
                        />
                    </div>
                    <div class="settings-control">
                        <FormInput
                            v-model="form.reply_to"
                            type="email"
                            placeholder="reply@example.com"
                            class="w-full"
                        />
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Reply-To Name')"
                            :help="$t('Name that appears in the Reply-To field. Optional.')"
                        />
                    </div>
                    <div class="settings-control">
                        <FormInput
                            v-model="form.reply_to_name"
                            type="text"
                            placeholder="e.g. Support Team"
                            class="w-full"
                        />
                    </div>
                </div>
            </div>



            <!-- Actions -->
            <div class="flex items-center justify-end pt-2">
                <BaseButton
                    variant="primary"
                    :loading="state.loading.saving"
                    :disabled="state.loading.page || state.loading.saving"
                    @click="onSave"
                >
                    {{ $t('Save Settings') }}
                </BaseButton>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import BaseButton from '@/Admin/Components/BaseButton.vue'
import FormInput from '@/Admin/Components/FormInput.vue'
import FormLabel from '@/Admin/Components/FormLabel.vue'

import { useForm } from '@/Admin/js/composables/useForm.js'
import { useToast } from '@/Admin/js/composables/useToast.js'
import Http from '@/Admin/js/utils/http.js'

// Reactive state
const state = reactive({
    loading: {
        page: false,
        saving: false
    }
})

// Toast notifications
const { showSuccess, showError } = useToast()

// Form defaults
const makeDefaults = () => ({
    from_name: 'Support Team',
    from_email: '',
    reply_to: '',
    reply_to_name: ''
})

const form = useForm(makeDefaults())

// API calls
const loadSettings = async () => {
    try {
        state.loading.page = true
        const response = await Http.get('email-settings')

        if (response.success) {
            form.fill(response.settings)
        }
    } catch (error) {
        console.error('Failed to load email settings:', error)
        showError('Failed to load email settings', 'Please check your connection and try again')
    } finally {
        state.loading.page = false
    }
}

// Actions

const onSave = async () => {
    if (state.loading.saving) return

    try {
        state.loading.saving = true

        const response = await Http.post('email-settings', form.getData())

        if (response.success) {
            form.fill(response.data)

            // Handle test email result
            if (response.test_result) {
                if (response.test_result.success) {
                    showSuccess(`Settings saved! ${response.test_result.message}`)
                } else {
                    showError(`Settings saved, but test email failed: ${response.test_result.message}`)
                }
            } else {
                showSuccess('Email settings saved successfully!')
            }
        } else {
            showError(response.message || 'Failed to save settings')
        }
    } catch (error) {
        console.error('Save error:', error)
        showError('Failed to save email settings')
    } finally {
        state.loading.saving = false
    }
}

// Initialize
onMounted(loadSettings)
</script>

<style lang="scss" scoped>
/* Settings two-column row layout */
.settings-row {
  @apply grid grid-cols-1 md:grid-cols-12 items-center gap-6;
}

.settings-label {
  @apply md:col-span-5 flex flex-col justify-center;
}

.settings-control {
  @apply md:col-span-7 flex items-center;
}

.label-title {
  @apply text-sm md:text-base font-medium text-gray-800;
}

.label-help {
  @apply text-xs text-gray-500 mt-1;
}
</style>
