<template>
  <div>
    <div class="flex items-center justify-between mb-4">
      <div>
        <h1 class="text-3xl font-bold text-gray-800">
          {{ isEditMode ? $t('Edit Saved Reply') : $t('Add Saved Reply') }}
        </h1>
        <p class="text-gray-600 mt-1">
          {{ isEditMode ? $t('Update the saved reply details.') : $t('Create a new predefined response.') }}
        </p>
      </div>
      <router-link
        to="/settings/saved-replies"
        class="inline-flex items-center px-4 py-2 text-gray-700 text-sm font-medium rounded-md border border-gray-300 hover:bg-gray-50 transition-colors"
      >
        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
        </svg>
        {{ $t('Back to List') }}
      </router-link>
    </div>
    <div class="border-b border-gray-100 mb-6"></div>

    <!-- Loading State -->
    <div v-if="state.loading.page" class="py-8 text-center text-gray-500">
      {{ $t('Loading...') }}
    </div>

    <!-- Form -->
    <form v-else @submit.prevent="onSubmit" class="space-y-6">
      <!-- Question -->
      <div class="settings-row border-b border-gray-100 py-4">
        <div class="settings-label">
          <FormLabel
            :title="$t('Question')"
            :help="$t('The question or trigger phrase that users might ask.')"
            :required="true"
          />
        </div>
        <div class="settings-control">
          <FormInput
            v-model="form.question"
            type="textarea"
            :rows="2"
            :placeholder="$t('e.g., What are your business hours?')"
            :error="!!errors.question"
            class="w-full"
          />
          <p v-if="errors.question" class="text-red-500 text-xs mt-1">{{ errors.question }}</p>
        </div>
      </div>

      <!-- Answer -->
      <div class="settings-row border-b border-gray-100 py-4">
        <div class="settings-label">
          <FormLabel
            :title="$t('Answer')"
            :help="$t('The response to send when this question is matched.')"
            :required="true"
          />
        </div>
        <div class="settings-control">
          <FormInput
            v-model="form.answer"
            type="textarea"
            :rows="4"
            :placeholder="$t('e.g., Our business hours are Monday to Friday, 9 AM to 6 PM EST.')"
            :error="!!errors.answer"
            class="w-full"
          />
          <p v-if="errors.answer" class="text-red-500 text-xs mt-1">{{ errors.answer }}</p>
        </div>
      </div>

      <!-- Match Type -->
      <div class="settings-row border-b border-gray-100 py-4">
        <div class="settings-label">
          <FormLabel
            :title="$t('Match Type')"
            :help="$t('How the question should be matched against user input.')"
          />
        </div>
        <div class="settings-control">
          <div class="flex flex-wrap gap-3">
            <label
              v-for="option in matchTypeOptions"
              :key="option.value"
              class="match-type-option"
              :class="{ 'selected': form.match_type === option.value }"
            >
              <input
                type="radio"
                :value="option.value"
                v-model="form.match_type"
                class="sr-only"
              />
              <div class="flex items-center">
                <span :class="option.badgeClass" class="text-xs px-2 py-1 rounded-full mr-2">
                  {{ option.label }}
                </span>
                <span class="text-xs text-gray-500">{{ option.description }}</span>
              </div>
            </label>
          </div>
        </div>
      </div>

      <!-- Keywords -->
      <div class="settings-row border-b border-gray-100 py-4">
        <div class="settings-label">
          <FormLabel
            :title="$t('Keywords')"
            :help="$t('Comma-separated keywords for matching. Used with keyword and contains match types.')"
          />
        </div>
        <div class="settings-control">
          <FormInput
            v-model="form.keywords"
            type="text"
            :placeholder="$t('e.g., hours, open, close, schedule, time')"
            class="w-full"
          />
        </div>
      </div>

      <!-- Language -->
      <div class="settings-row border-b border-gray-100 py-4">
        <div class="settings-label">
          <FormLabel
            :title="$t('Language')"
            :help="$t('Select the language for this reply.')"
          />
        </div>
        <div class="settings-control">
          <el-select
            v-model="form.language"
            class="form-select w-full"
            filterable
            :placeholder="$t('Select language')"
          >
            <el-option
              v-for="lang in availableLanguages"
              :key="lang.code"
              :label="`${lang.language} (${lang.code})`"
              :value="lang.language_code"
            />
          </el-select>
        </div>
      </div>

      <!-- Priority -->
      <div class="settings-row border-b border-gray-100 py-4">
        <div class="settings-label">
          <FormLabel
            :title="$t('Priority')"
            :help="$t('Higher priority replies are matched first. Range: 0-100.')"
          />
        </div>
        <div class="settings-control">
          <FormInput
            v-model.number="form.priority"
            type="number"
            :min="0"
            :max="100"
            class="w-full max-w-xs"
          />
        </div>
      </div>

      <!-- Active Status -->
      <div class="settings-row border-b border-gray-100 py-4">
        <div class="settings-label">
          <FormLabel
            :title="$t('Active')"
            :help="$t('Only active replies will be used for matching.')"
          />
        </div>
        <div class="settings-control !flex-row !items-center justify-between w-full">
          <div class="flex items-center gap-3">
            <button
              type="button"
              @click="form.is_active = !form.is_active"
              :class="[
                'relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
                form.is_active ? 'bg-blue-600' : 'bg-gray-200'
              ]"
            >
              <span
                :class="[
                  'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
                  form.is_active ? 'translate-x-6' : 'translate-x-1'
                ]"
              />
            </button>
            <span class="text-sm text-gray-700">{{ $t('Toggle active status') }}</span>
          </div>
          <span
            class="inline-flex items-center px-2.5 py-0.5 rounded text-xs font-medium flex-shrink-0"
            :class="form.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'"
          >
            {{ form.is_active ? $t('Active') : $t('Inactive') }}
          </span>
        </div>
      </div>

      <!-- Actions -->
      <div class="flex items-center justify-end gap-3 pt-4">
        <router-link
          to="/settings/saved-replies"
          class="px-4 py-2 text-gray-700 text-sm font-medium rounded-md border border-gray-300 hover:bg-gray-50 transition-colors"
        >
          {{ $t('Cancel') }}
        </router-link>
        <BaseButton
          variant="primary"
          type="submit"
          :loading="state.loading.saving"
          :disabled="state.loading.saving"
        >
          {{ isEditMode ? $t('Update Reply') : $t('Create Reply') }}
        </BaseButton>
      </div>
    </form>
  </div>
</template>

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

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

const router = useRouter()
const route = useRoute()
const { showSuccess, showError } = useToast()

// Check if edit mode
const isEditMode = computed(() => !!route.params.id)

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

// Form data
const form = reactive({
  question: '',
  answer: '',
  match_type: 'exact',
  keywords: '',
  language: 'en',
  priority: 50,
  is_active: true
})

// Validation errors
const errors = reactive({
  question: '',
  answer: ''
})

// Match type options
const matchTypeOptions = [
  {
    value: 'exact',
    label: t('Exact'),
    description: t('Exact phrase match'),
    badgeClass: 'bg-blue-100 text-blue-700'
  },
  {
    value: 'contains',
    label: t('Contains'),
    description: t('Question contains phrase'),
    badgeClass: 'bg-purple-100 text-purple-700'
  },
  {
    value: 'keyword',
    label: t('Keyword'),
    description: t('Match any keyword'),
    badgeClass: 'bg-amber-100 text-amber-700'
  }
]

// Available languages from localized admin config (same as GeneralSettings)
const availableLanguages = computed(() => window.zenochatbot_admin?.languages || [])

// Validate form
const validate = () => {
  let isValid = true
  errors.question = ''
  errors.answer = ''

  if (!form.question.trim()) {
    errors.question = t('Question is required')
    isValid = false
  }

  if (!form.answer.trim()) {
    errors.answer = t('Answer is required')
    isValid = false
  }

  return isValid
}

// Load reply for editing
const loadReply = async () => {
  if (!isEditMode.value) return

  try {
    state.loading.page = true
    const response = await Http.get(`admin/saved-replies/${route.params.id}`)

    if (response.success && response.data) {
      Object.assign(form, {
        question: response.data.question || '',
        answer: response.data.answer || '',
        match_type: response.data.match_type || 'exact',
        keywords: response.data.keywords || '',
        language: response.data.language || 'en',
        priority: response.data.priority ?? 50,
        is_active: Boolean(response.data.is_active)
      })
    }
  } catch (error) {
    console.error('Failed to load saved reply:', error)
    showError(t('Failed to load saved reply'))
    router.push('/settings/saved-replies')
  } finally {
    state.loading.page = false
  }
}

// Submit form
const onSubmit = async () => {
  if (!validate()) return

  try {
    state.loading.saving = true

    const payload = {
      question: form.question,
      answer: form.answer,
      match_type: form.match_type,
      keywords: form.keywords,
      language: form.language,
      priority: form.priority,
      is_active: form.is_active ? 1 : 0
    }

    let response
    if (isEditMode.value) {
      response = await Http.patch(`admin/saved-replies/${route.params.id}`, payload)
    } else {
      response = await Http.post('admin/saved-replies', payload)
    }

    if (response.success) {
      showSuccess(response.message || (isEditMode.value ? t('Reply updated successfully') : t('Reply created successfully')))
      router.push('/settings/saved-replies')
    } else {
      showError(response.message || t('Failed to save reply'))
    }
  } catch (error) {
    console.error('Failed to save reply:', error)
    showError(error.message || t('Failed to save reply'))
  } finally {
    state.loading.saving = false
  }
}

// Initialize
onMounted(() => {
  if (isEditMode.value) {
    loadReply()
  }
})
</script>

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

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

.settings-control {
  @apply md:col-span-8 flex flex-col;
}

/* Form select */
.form-select {
  @apply px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors bg-white;
}

/* Match type option */
.match-type-option {
  @apply flex items-center px-4 py-3 border border-gray-200 rounded-lg cursor-pointer transition-all duration-200;

  &:hover {
    @apply border-gray-300 bg-gray-50;
  }

  &.selected {
    @apply border-blue-500 bg-blue-50 ring-1 ring-blue-500;
  }
}

/* Screen reader only */
.sr-only {
  @apply absolute w-px h-px p-0 -m-px overflow-hidden whitespace-nowrap border-0;
  clip: rect(0, 0, 0, 0);
}
</style>
