<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { api } from '@/api'
import SecuritySettings from '@/components/SecuritySettings.vue'

const { t } = useI18n()
const authStore = useAuthStore()

const currentPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const loading = ref(false)
const message = ref('')
const error = ref('')
const showSecuritySettings = ref(false)

const logoFile = ref<File | null>(null)
const logoPreview = ref<string | null>(null)
const logoLoading = ref(false)
const logoMessage = ref('')
const logoError = ref('')
const fileInput = ref<HTMLInputElement | null>(null)
const lockMethod = ref<string | null>(null)

onMounted(() => {
  lockMethod.value = localStorage.getItem('lockMethod')
  if (authStore.user?.email) localStorage.setItem('userEmail', authStore.user.email)
  if (authStore.orgLogo) logoPreview.value = authStore.orgLogo
})

function handleLogoSelect(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return
  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml']
  if (!allowedTypes.includes(file.type)) { logoError.value = t('messages.invalid'); return }
  if (file.size > 5 * 1024 * 1024) { logoError.value = t('messages.error'); return }
  logoFile.value = file
  logoError.value = ''
  const reader = new FileReader()
  reader.onload = (e) => { logoPreview.value = e.target?.result as string }
  reader.readAsDataURL(file)
}

async function uploadLogo() {
  if (!logoFile.value) return
  logoLoading.value = true
  logoError.value = ''
  logoMessage.value = ''
  try {
    const formData = new FormData()
    formData.append('logo', logoFile.value)
    const response = await api.post('/uploads/logo', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
    logoMessage.value = t('messages.saved')
    logoFile.value = null
    authStore.setOrgLogo(response.data.logo_url)
    logoPreview.value = response.data.logo_url
  } catch (e) {
    logoError.value = e instanceof Error ? e.message : t('messages.error')
  } finally { logoLoading.value = false }
}

async function deleteLogo() {
  if (!confirm(t('messages.confirmDelete'))) return
  logoLoading.value = true
  logoError.value = ''
  try {
    await api.delete('/uploads/logo')
    logoMessage.value = t('messages.deleted')
    logoPreview.value = null
    logoFile.value = null
    authStore.setOrgLogo(null)
  } catch (e) {
    logoError.value = e instanceof Error ? e.message : t('messages.error')
  } finally { logoLoading.value = false }
}

const lockStatusText = computed(() => {
  if (!lockMethod.value || lockMethod.value === 'none') return t('modules.disabled')
  if (lockMethod.value === 'biometric') return 'Biometric'
  if (lockMethod.value === 'pin') return t('settings.pin')
  return ''
})

const lockStatusClass = computed(() => {
  if (!lockMethod.value || lockMethod.value === 'none') return 'bg-red-100 text-red-700'
  return 'bg-green-100 text-green-700'
})

async function changePassword() {
  if (newPassword.value !== confirmPassword.value) { error.value = t('messages.invalid'); return }
  if (newPassword.value.length < 8) { error.value = t('messages.invalid'); return }
  loading.value = true
  error.value = ''
  message.value = ''
  try {
    await api.post('/auth/change-password', { currentPassword: currentPassword.value, newPassword: newPassword.value })
    message.value = t('messages.saved')
    currentPassword.value = ''
    newPassword.value = ''
    confirmPassword.value = ''
  } catch (e) {
    error.value = e instanceof Error ? e.message : t('messages.error')
  } finally { loading.value = false }
}

function handleSecurityClose() {
  showSecuritySettings.value = false
  lockMethod.value = localStorage.getItem('lockMethod')
}
</script>

<template>
  <div class="space-y-6">
    <h1 class="text-2xl font-bold text-gray-900 dark:text-white">🔧 {{ t('settings.title') }}</h1>

    <!-- Profile -->
    <div class="card">
      <h2 class="text-lg font-semibold mb-4">👤 {{ t('settings.profile') }}</h2>
      <div class="grid grid-cols-2 gap-4">
        <div>
          <label class="block text-sm text-gray-500">{{ t('auth.firstName') }}</label>
          <p class="font-medium">{{ authStore.fullName }}</p>
        </div>
        <div>
          <label class="block text-sm text-gray-500">{{ t('auth.email') }}</label>
          <p class="font-medium">{{ authStore.user?.email }}</p>
        </div>
        <div>
          <label class="block text-sm text-gray-500">{{ t('users.role') }}</label>
          <p class="font-medium capitalize">{{ authStore.user?.role }}</p>
        </div>
        <div>
          <label class="block text-sm text-gray-500">{{ t('auth.orgName') }}</label>
          <p class="font-medium">{{ authStore.orgName }}</p>
        </div>
      </div>
    </div>

    <!-- Organization Logo -->
    <div v-if="authStore.isChef" class="card">
      <h2 class="text-lg font-semibold mb-4">🏢 Logo</h2>
      <div class="flex items-start gap-6">
        <div class="flex-shrink-0">
          <div class="w-32 h-32 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg flex items-center justify-center overflow-hidden bg-gray-50 dark:bg-gray-700">
            <img v-if="logoPreview" :src="logoPreview" alt="Logo" class="max-w-full max-h-full object-contain">
            <span v-else class="text-4xl text-gray-400">🏢</span>
          </div>
        </div>
        <div class="flex-1 space-y-4">
          <div>
            <input ref="fileInput" type="file" accept="image/jpeg,image/png,image/webp,image/svg+xml" class="hidden" @change="handleLogoSelect">
            <button type="button" class="btn btn-secondary" @click="fileInput?.click()">📁 {{ t('app.upload') }}</button>
            <span v-if="logoFile" class="ml-3 text-sm text-gray-600 dark:text-gray-400">{{ logoFile.name }}</span>
          </div>
          <div class="flex gap-2">
            <button v-if="logoFile" type="button" :disabled="logoLoading" class="btn btn-primary" @click="uploadLogo">{{ logoLoading ? t('app.loading') : '⬆️ ' + t('app.upload') }}</button>
            <button v-if="authStore.orgLogo" type="button" :disabled="logoLoading" class="btn btn-secondary text-red-600 hover:bg-red-50" @click="deleteLogo">🗑️ {{ t('app.delete') }}</button>
          </div>
          <div v-if="logoError" class="text-red-600 text-sm">{{ logoError }}</div>
          <div v-if="logoMessage" class="text-green-600 text-sm">{{ logoMessage }}</div>
        </div>
      </div>
    </div>

    <!-- App Security -->
    <div class="card">
      <h2 class="text-lg font-semibold mb-4">🔐 {{ t('settings.security') }}</h2>
      <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
        <div>
          <div class="font-medium">{{ t('settings.lockScreen') }}</div>
          <div :class="['inline-block px-2 py-1 rounded text-sm mt-1', lockStatusClass]">{{ lockStatusText }}</div>
        </div>
        <button @click="showSecuritySettings = true" class="btn btn-primary">{{ t('modules.configure') }}</button>
      </div>
    </div>

    <!-- Change Password -->
    <div class="card">
      <h2 class="text-lg font-semibold mb-4">🔑 {{ t('settings.changePassword') }}</h2>
      <form @submit.prevent="changePassword" class="space-y-4 max-w-md">
        <div>
          <label class="block text-sm font-medium mb-1">{{ t('auth.password') }}</label>
          <input v-model="currentPassword" type="password" required class="input" />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">{{ t('auth.password') }} ({{ t('app.add') }})</label>
          <input v-model="newPassword" type="password" required class="input" />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">{{ t('auth.confirmPassword') }}</label>
          <input v-model="confirmPassword" type="password" required class="input" />
        </div>
        <div v-if="error" class="text-red-600 text-sm">{{ error }}</div>
        <div v-if="message" class="text-green-600 text-sm">{{ message }}</div>
        <button type="submit" :disabled="loading" class="btn btn-primary">{{ loading ? t('app.loading') : t('app.save') }}</button>
      </form>
    </div>

    <SecuritySettings v-if="showSecuritySettings" @close="handleSecurityClose" />
  </div>
</template>
