<template>
    <div>
        <h1 class="text-3xl font-bold mb-4 text-gray-800">{{ $t('Chat 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('Enable Floating Chat Widget')"
                            :help="$t('Turn this off to hide the floating chat widget entirely.')"
                        />
                    </div>
                    <div class="settings-control justify-between w-full">
                        <div class="flex items-center gap-3">
                            <button
                                type="button"
                                @click="form.floating_widget_enabled = form.floating_widget_enabled === 'yes' ? 'no' : 'yes'"
                                :class="[
                    'relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
                    form.floating_widget_enabled === 'yes' ? 'bg-blue-600' : 'bg-gray-200'
                  ]"
                            >
                  <span
                      :class="[
                      'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
                      form.floating_widget_enabled === 'yes' ? 'translate-x-6' : 'translate-x-1'
                    ]"
                  />
                            </button>
                            <span class="text-sm text-gray-700">{{ $t('Toggle widget visibility') }}</span>
                        </div>
                        <span
                            class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium"
                            :class="form.floating_widget_enabled === 'yes' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'"
                        >
                {{ form.floating_widget_enabled === 'yes' ? $t('Enabled') : $t('Disabled') }}
              </span>
                    </div>
                </div>
            </div>

            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Agent Name')"
                            :help="$t('Shown as the chat agent’s display name.')"
                        />
                    </div>
                    <div class="settings-control">
                        <FormInput
                            v-model="form.agent_name"
                            type="text"
                            :placeholder="$t('e.g. Support Agent')"
                            class="w-full"
                        />
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Agent Avatar URL')"
                            :help="$t('Provide an image URL to use as the agent avatar.')"
                        />
                    </div>
                    <div class="settings-control">
                        <MediaPicker
                            :attachments="[form.agent_avatar]"
                            @on-media-selected="onMediaSelected"

                        />
<!--                        <input type="url" v-model="form.agent_avatar" class="form-input w-full"-->
<!--                               placeholder="https://example.com/avatar.png"/>-->
                    </div>
                </div>
            </div>

            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Header Color')"
                            help="Color of the chat header bar."
                        />
                    </div>
                    <div class="settings-control">
                        <div class="flex items-center gap-3">
                            <input type="color" v-model="form.chat_bar_header_color" class="color-input"/>
                            <code class="text-xs text-gray-600">{{ form.chat_bar_header_color }}</code>
                        </div>
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Send Button Color')"
                            help="Color of the send button in the chat input."
                        />
                    </div>
                    <div class="settings-control">
                        <div class="flex items-center gap-3">
                            <input type="color" v-model="form.send_button_color" class="color-input"/>
                            <code class="text-xs text-gray-600">{{ form.send_button_color }}</code>
                        </div>
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Bubble Background Color')"
                            help="Background color for neutral system bubbles."
                        />
                    </div>
                    <div class="settings-control">
                        <div class="flex items-center gap-3">
                            <input type="color" v-model="form.bubble_background_color" class="color-input"/>
                            <code class="text-xs text-gray-600">{{ form.bubble_background_color }}</code>
                        </div>
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Agent Chat Background')"
                            help="Background color of the agent’s message bubbles."
                        />
                    </div>
                    <div class="settings-control">
                        <div class="flex items-center gap-3">
                            <input type="color" v-model="form.agent_chat_bg_color" class="color-input"/>
                            <code class="text-xs text-gray-600">{{ form.agent_chat_bg_color }}</code>
                        </div>
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Agent Chat Message Color')"
                            help="Text color used inside the agent’s message bubbles."
                        />
                    </div>
                    <div class="settings-control">
                        <div class="flex items-center gap-3">
                            <input type="color" v-model="form.agent_chat_text_color" class="color-input"/>
                            <code class="text-xs text-gray-600">{{ form.agent_chat_text_color }}</code>
                        </div>
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Customer Chat Background')"
                            help="Background color of the customer’s message bubbles."
                        />
                    </div>
                    <div class="settings-control">
                        <div class="flex items-center gap-3">
                            <input type="color" v-model="form.customer_chat_bg_color" class="color-input"/>
                            <code class="text-xs text-gray-600">{{ form.customer_chat_bg_color }}</code>
                        </div>
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <FormLabel
                            :title="$t('Customer Chat Message Color')"
                            help="Text color used inside the customer’s message bubbles."
                        />
                    </div>
                    <div class="settings-control">
                        <div class="flex items-center gap-3">
                            <input type="color" v-model="form.customer_chat_text_color" class="color-input"/>
                            <code class="text-xs text-gray-600">{{ form.customer_chat_text_color }}</code>
                        </div>
                    </div>
                </div>

            </div>

            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('Show Online Indicator') }}</div>
                    </div>
                    <div class="settings-control justify-between w-full">
                        <div class="flex items-center gap-3">
                            <button
                                type="button"
                                @click="form.online_indicator = form.online_indicator === 'yes' ? 'no' : 'yes'"
                                :class="[
                    'relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
                    form.online_indicator === 'yes' ? 'bg-blue-600' : 'bg-gray-200'
                  ]"
                            >
                  <span
                      :class="[
                      'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
                      form.online_indicator === 'yes' ? 'translate-x-6' : 'translate-x-1'
                    ]"
                  />
                            </button>
                            <span class="text-sm text-gray-700">{{ $t('Toggle availability badge') }}</span>
                        </div>
                        <span
                            class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium"
                            :class="form.online_indicator === 'yes' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'"
                        >
                {{ form.online_indicator === 'yes' ? $t('Enabled') : $t('Disabled') }}
              </span>
                    </div>
                </div>

                <div v-if="form.online_indicator === 'yes'" class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('Online Indicator Text') }}</div>
                    </div>
                    <div class="settings-control">
                        <input type="text" v-model="form.online_indicator_text" class="form-input w-full"
                               placeholder="We're online"/>
                    </div>
                </div>
            </div>

            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('Greeting Message') }}</div>
                        <div class="label-help">{{ $t('Shown when the chat opens to welcome users.') }}</div>
                    </div>
                    <div class="settings-control">
                        <FormInput
                            type="textarea"
                            v-model="form.greeting_message"
                            class="form-textarea w-full"
                            :rows="3"
                            :placeholder="$t('Hi there! How can we help?')"
                        />
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('Support Ticket Link') }}</div>
                        <div class="label-help">{{ $t('Link to your support ticket submission page.') }}</div>
                    </div>
                    <div class="settings-control">
                        <input type="url" v-model="form.support_ticket_link" class="form-input w-full"
                               placeholder="https://example.com/support"/>
                    </div>
                </div>

                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('Contact Us Page Link') }}</div>
                    </div>
                    <div class="settings-control">
                        <input type="url" v-model="form.contact_us_link" class="form-input w-full"
                               placeholder="https://example.com/contact"/>
                    </div>
                </div>
            </div>

            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('Auto Open Chat') }}</div>
                        <div class="label-help">{{ $t('Automatically open the chat after a delay.') }}</div>
                    </div>
                    <div class="settings-control justify-between w-full">
                        <div class="flex items-center gap-3">
                            <button
                                type="button"
                                @click="form.auto_open = form.auto_open === 'yes' ? 'no' : 'yes'"
                                :class="[
                    'relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
                    form.auto_open === 'yes' ? 'bg-blue-600' : 'bg-gray-200'
                  ]"
                            >
                  <span
                      :class="[
                      'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
                      form.auto_open === 'yes' ? 'translate-x-6' : 'translate-x-1'

                    ]"
                  />
                            </button>
                            <span class="text-sm text-gray-700">{{ $t('Toggle auto-open') }}</span>
                        </div>
                        <span
                            class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium"
                            :class="form.auto_open === 'yes' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'"
                        >
                {{ form.auto_open === 'yes' ? 'Enabled' : 'Disabled' }}
              </span>
                    </div>
                </div>


                <div v-if="form.auto_open === 'yes'" class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('Auto Open Delay (ms)') }}</div>
                        <div class="label-help">{{
                                $t('Delay before the chat opens automatically (in milliseconds).')
                            }}
                        </div>
                    </div>
                    <div class="settings-control">
                        <input type="number" min="0" class="form-input w-full max-w-xs"
                               v-model.number="form.auto_open_delay" placeholder="3000"/>
                    </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 MediaPicker from '@/Admin/Components/MediaPicker.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
    }
})

const onMediaSelected = (value) => {
    if (!Array.isArray(value)) {
        value = [value]
    }

    // Store the attachment ID for saving
    if (value.length > 0 && value[0]?.id) {
        form.agent_avatar = value[0].id
    }
}

// Form defaults
const makeDefaults = () => ({
    floating_widget_enabled: 'yes',
    agent_name: 'Support Agent',
    agent_avatar: '',
    chat_bar_header_color: '#0ea5e9',
    send_button_color: '#2563eb',
    bubble_background_color: '#f3f4f6',
    agent_chat_bg_color: '#eef2ff',
    agent_chat_text_color: '#1f2937',
    customer_chat_bg_color: '#dcfce7',
    customer_chat_text_color: '#111827',
    online_indicator: 'yes',
    online_indicator_text: 'We\'re online',
    greeting_message: 'Hi there! How can we help?',
    support_ticket_link: '',
    contact_us_link: '',
    auto_open: 'yes',
    auto_open_delay: 3000
})

const form = useForm(makeDefaults())

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

// API calls
const loadSettings = async () => {
    try {
        state.loading.page = true
        const response = await Http.get('chat-settings')
        if (response?.success) {
            // Fill form with data from API
            form.fill(response.data)

            // Handle agent_avatar - it comes as URL from backend, but we need ID for MediaPicker
            // The backend returns the URL, but we store the ID
            if (response.data.agent_avatar) {
                // Keep the ID if it's numeric, otherwise clear it
                if (!isNaN(response.data.agent_avatar)) {
                    form.agent_avatar = response.data.agent_avatar
                }
            }
        }
    } catch (error) {
        console.error('Failed to load chat settings:', error)
        showError('Failed to load chat settings')
    } finally {
        state.loading.page = false
    }
}

// Actions
const onSave = async () => {
    try {
        state.loading.saving = true

        // Get form data and ensure agent_avatar is sent as ID
        const formData = form.getData()

        const response = await Http.post('chat-settings', formData)

        console.log({ response })

        if (response?.success) {
            showSuccess(response.message || 'Chat settings saved successfully!')

            // Update form with returned data to ensure consistency
            if (response.data) {
                form.fill(response.data)

                // Handle agent_avatar URL to ID conversion if needed
                if (response.data.agent_avatar && !isNaN(response.data.agent_avatar)) {
                    form.agent_avatar = response.data.agent_avatar
                }
            }
        } else {
            showError(response?.message || 'Failed to save chat settings')
        }
    } catch (error) {
        console.error('Failed to save chat settings:', error)
        showError(error.response?.data?.message || 'Failed to save chat settings. Please try again.')
    } finally {
        state.loading.saving = false
    }
}

// Initialize
onMounted(loadSettings)
</script>

<style lang="scss" scoped>
/* Removed old form and button styles - now using reusable components */

/* 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;
}

.color-input {
  @apply h-10 w-16 p-1 border rounded;
}

</style>

