<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { configApi } from '../../services/configApi'
import { useUiStore } from '../../stores/ui'

const ui = useUiStore()
const loading = ref(false)
const saving = ref(false)
const testingEmail = ref(false)
const testEmail = ref('')

const smtp = ref({
  host: '',
  port: 587,
  username: '',
  password: '',
  use_tls: true,
  from_email: '',
  from_name: 'V3Q.AI Notifications',
})

const global_ = ref({
  enabled: false,
  max_retries: 3,
  batch_size: 50,
})

async function load() {
  loading.value = true
  try {
    const { data } = await configApi.getNotificationSettings()
    if (data.smtp) Object.assign(smtp.value, data.smtp)
    if (data.global) Object.assign(global_.value, data.global)
  } catch {
    ui.showToast('Failed to load settings', 'error')
  } finally {
    loading.value = false
  }
}

async function save() {
  saving.value = true
  try {
    await configApi.updateNotificationSettings('smtp', smtp.value)
    await configApi.updateNotificationSettings('global', global_.value)
    ui.showToast('Settings saved', 'success')
  } catch {
    ui.showToast('Failed to save settings', 'error')
  } finally {
    saving.value = false
  }
}

async function sendTest() {
  if (!testEmail.value.trim()) return
  testingEmail.value = true
  try {
    await configApi.sendTestEmail(testEmail.value.trim())
    ui.showToast(`Test email sent to ${testEmail.value}`, 'success')
  } catch (err: any) {
    ui.showToast(err?.response?.data?.detail || 'Test email failed', 'error')
  } finally {
    testingEmail.value = false
  }
}

onMounted(load)
</script>

<template>
  <div class="card space-y-4">
    <h3 class="font-semibold text-sm">SMTP & Notification Settings</h3>

    <div v-if="loading" class="text-dark-500 text-sm py-4 text-center">Loading...</div>
    <template v-else>
      <!-- Global toggle -->
      <div class="flex items-center gap-3 p-3 bg-dark-900 rounded-lg">
        <label class="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" v-model="global_.enabled" class="accent-primary-500" />
          <span class="text-sm">Enable email notifications</span>
        </label>
      </div>

      <!-- SMTP config -->
      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="text-xs text-dark-400 mb-1 block">SMTP Host</label>
          <input v-model="smtp.host" placeholder="smtp.gmail.com" class="input-field w-full" />
        </div>
        <div>
          <label class="text-xs text-dark-400 mb-1 block">Port</label>
          <input v-model.number="smtp.port" type="number" class="input-field w-full" />
        </div>
        <div>
          <label class="text-xs text-dark-400 mb-1 block">Username</label>
          <input v-model="smtp.username" class="input-field w-full" />
        </div>
        <div>
          <label class="text-xs text-dark-400 mb-1 block">Password</label>
          <input v-model="smtp.password" type="password" class="input-field w-full" />
        </div>
        <div>
          <label class="text-xs text-dark-400 mb-1 block">From Email</label>
          <input v-model="smtp.from_email" type="email" placeholder="noreply@company.com" class="input-field w-full" />
        </div>
        <div>
          <label class="text-xs text-dark-400 mb-1 block">From Name</label>
          <input v-model="smtp.from_name" class="input-field w-full" />
        </div>
      </div>

      <label class="flex items-center gap-2 cursor-pointer text-sm">
        <input type="checkbox" v-model="smtp.use_tls" class="accent-primary-500" />
        Use TLS
      </label>

      <div class="flex items-center gap-3">
        <button @click="save" :disabled="saving" class="btn-primary text-sm">
          {{ saving ? 'Saving...' : 'Save Settings' }}
        </button>
      </div>

      <!-- Test email -->
      <div class="border-t border-dark-700 pt-4">
        <h4 class="text-xs font-semibold text-dark-400 mb-2">Test SMTP Connection</h4>
        <div class="flex gap-2">
          <input v-model="testEmail" type="email" placeholder="test@email.com" class="input-field flex-1" />
          <button @click="sendTest" :disabled="testingEmail || !testEmail" class="btn-secondary text-sm">
            {{ testingEmail ? 'Sending...' : 'Send Test' }}
          </button>
        </div>
      </div>
    </template>
  </div>
</template>
