<template>
  <div class="space-y-4">
    <h3 class="text-lg font-bold">Logo</h3>

    <!-- Preview -->
    <div class="flex items-center gap-4">
      <div class="w-24 h-24 border border-base-300 rounded-lg flex items-center justify-center bg-base-200 overflow-hidden">
        <img v-if="settingsStore.logoDataUrl()" :src="settingsStore.logoDataUrl()!" alt="Logo" class="max-w-full max-h-full object-contain" />
        <img v-else src="../../../assets/images/1.png" alt="Default Logo" class="max-w-full max-h-full object-contain" />
      </div>
      <div class="space-y-2">
        <p class="text-sm opacity-70">Upload a custom logo (PNG, JPG, SVG). Max 2MB.</p>
        <div class="flex gap-2">
          <input type="file" ref="fileInput" accept="image/*" class="hidden" @change="onFileSelected" />
          <button class="btn btn-primary btn-sm" @click="($refs.fileInput as HTMLInputElement).click()" :disabled="uploading">
            <span v-if="uploading" class="loading loading-spinner loading-xs"></span>
            Upload
          </button>
          <button v-if="settingsStore.settings.logo_base64" class="btn btn-error btn-sm btn-outline" @click="removeLogo" :disabled="uploading">
            Remove
          </button>
        </div>
      </div>
    </div>
    <div v-if="error" class="alert alert-error alert-sm">{{ error }}</div>
    <div v-if="success" class="alert alert-success alert-sm">{{ success }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useSettingsStore } from '../../../stores/settings'

const settingsStore = useSettingsStore()
const fileInput = ref<HTMLInputElement | null>(null)
const uploading = ref(false)
const error = ref('')
const success = ref('')

async function onFileSelected(event: Event) {
  const input = event.target as HTMLInputElement
  if (!input.files || !input.files[0]) return

  const file = input.files[0]
  if (file.size > 2 * 1024 * 1024) {
    error.value = 'File too large. Maximum size is 2MB.'
    return
  }

  error.value = ''
  success.value = ''
  uploading.value = true
  try {
    await settingsStore.uploadLogo(file)
    success.value = 'Logo uploaded successfully'
  } catch {
    error.value = 'Failed to upload logo'
  } finally {
    uploading.value = false
    input.value = ''
  }
}

async function removeLogo() {
  error.value = ''
  success.value = ''
  uploading.value = true
  try {
    await settingsStore.deleteLogo()
    success.value = 'Logo removed'
  } catch {
    error.value = 'Failed to remove logo'
  } finally {
    uploading.value = false
  }
}
</script>
