<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useApi } from '@/composables/useApi'
import { useToastStore } from '@/stores/toast'
import type { StoreConfig } from '@/types'
import { Store, Save, Loader2, AlertTriangle, DollarSign } from 'lucide-vue-next'

const api = useApi()
const toast = useToastStore()

const config = ref<StoreConfig>({
  store_name: '',
  description: null,
  currency: 'USD',
  paypal_client_id: null,
  sandbox_mode: true,
  enabled: false,
})

const paypalSecret = ref<string>('')
const isLoading = ref(false)
const saving = ref(false)
const isConfigured = ref(false)

const currencyOptions = [
  { value: 'USD', label: 'USD - US Dollar' },
  { value: 'EUR', label: 'EUR - Euro' },
  { value: 'GBP', label: 'GBP - British Pound' },
]

const showPayPalWarning = computed(() => {
  return config.value.enabled && (!config.value.paypal_client_id || !paypalSecret.value)
})

async function fetchConfig() {
  isLoading.value = true
  try {
    const data = await api.get<{ config: StoreConfig }>('/webstore/config')
    config.value = data.config
    isConfigured.value = !!data.config.store_name
  } catch (err: any) {
    if (err.response?.status === 404) {
      // No config yet, use defaults
      isConfigured.value = false
    } else {
      toast.error('Failed to load store configuration')
    }
  } finally {
    isLoading.value = false
  }
}

async function saveConfig() {
  // Validation
  if (!config.value.store_name.trim()) {
    toast.error('Store name is required')
    return
  }

  if (config.value.enabled && !config.value.paypal_client_id) {
    toast.error('PayPal Client ID is required to enable the store')
    return
  }

  saving.value = true
  try {
    const payload: any = {
      store_name: config.value.store_name,
      description: config.value.description,
      currency: config.value.currency,
      paypal_client_id: config.value.paypal_client_id,
      sandbox_mode: config.value.sandbox_mode,
      enabled: config.value.enabled,
    }

    // Only include secret if it was entered
    if (paypalSecret.value.trim()) {
      payload.paypal_client_secret = paypalSecret.value
    }

    await api.put('/webstore/config', payload)
    toast.success('Store configuration saved successfully')
    isConfigured.value = true
    paypalSecret.value = '' // Clear after save
  } catch (err: any) {
    const message = err.response?.data?.error || 'Failed to save configuration'
    toast.error(message)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  fetchConfig()
})
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <Store class="w-5 h-5 text-oxide-500" />
        <div>
          <h1 class="text-2xl font-bold text-neutral-100">Store Configuration</h1>
          <p class="text-sm text-neutral-500 mt-0.5">
            Configure your integrated webstore and PayPal settings
          </p>
        </div>
      </div>
      <button
        @click="saveConfig"
        :disabled="saving || isLoading"
        class="flex items-center gap-2 px-4 py-2 bg-oxide-600 hover:bg-oxide-700 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
      >
        <Loader2 v-if="saving" class="w-4 h-4 animate-spin" />
        <Save v-else class="w-4 h-4" />
        {{ saving ? 'Saving...' : 'Save Configuration' }}
      </button>
    </div>

    <!-- Loading state -->
    <div v-if="isLoading" class="bg-neutral-900 border border-neutral-800 rounded-lg p-12 text-center">
      <Loader2 class="w-8 h-8 text-neutral-500 animate-spin mx-auto mb-3" />
      <p class="text-sm text-neutral-500">Loading configuration...</p>
    </div>

    <!-- Empty state -->
    <div
      v-else-if="!isConfigured && !config.store_name"
      class="bg-neutral-900 border border-neutral-800 rounded-lg p-12 text-center"
    >
      <Store class="w-12 h-12 text-neutral-600 mx-auto mb-4" />
      <h3 class="text-lg font-medium text-neutral-200 mb-2">No Store Configured</h3>
      <p class="text-sm text-neutral-500 mb-6 max-w-md mx-auto">
        Set up your integrated webstore to start selling in-game items, ranks, and currency to your players.
      </p>
      <p class="text-xs text-neutral-600">
        Fill out the form below to get started.
      </p>
    </div>

    <!-- Configuration form -->
    <div v-else class="space-y-6">
      <!-- Store enable toggle with warning -->
      <div
        class="bg-neutral-900 border rounded-lg p-5"
        :class="config.enabled ? 'border-oxide-500/50' : 'border-neutral-800'"
      >
        <div class="flex items-center justify-between">
          <div>
            <h2 class="text-sm font-medium text-neutral-200">Enable Webstore</h2>
            <p class="text-xs text-neutral-500 mt-1">
              Allow players to purchase items from your store
            </p>
          </div>
          <button
            @click="config.enabled = !config.enabled"
            :class="config.enabled ? 'bg-oxide-600' : 'bg-neutral-700'"
            class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-oxide-500 focus:ring-offset-2 focus:ring-offset-neutral-900"
          >
            <span
              :class="config.enabled ? 'translate-x-6' : 'translate-x-1'"
              class="inline-block h-4 w-4 transform rounded-full bg-white transition-transform"
            ></span>
          </button>
        </div>

        <!-- Warning when enabled without PayPal -->
        <div
          v-if="showPayPalWarning"
          class="mt-4 flex items-start gap-3 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg"
        >
          <AlertTriangle class="w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0" />
          <div class="text-xs text-yellow-300">
            <strong>PayPal configuration required.</strong> You must configure PayPal credentials below before the store can process transactions.
          </div>
        </div>
      </div>

      <!-- Basic store info -->
      <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5 space-y-4">
        <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider">Store Information</h2>

        <div>
          <label class="block text-xs text-neutral-500 mb-1">Store Name *</label>
          <input
            v-model="config.store_name"
            type="text"
            placeholder="My Rust Server Store"
            maxlength="200"
            class="w-full px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
          />
          <p class="text-xs text-neutral-600 mt-1">Displayed to players on the store page</p>
        </div>

        <div>
          <label class="block text-xs text-neutral-500 mb-1">Description (optional)</label>
          <textarea
            v-model="config.description"
            placeholder="Welcome to our server store! Support us and get awesome in-game items..."
            rows="3"
            class="w-full px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors resize-none"
          ></textarea>
          <p class="text-xs text-neutral-600 mt-1">Brief description shown on the store page</p>
        </div>

        <div>
          <label class="block text-xs text-neutral-500 mb-1">Currency</label>
          <div class="relative">
            <DollarSign class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-neutral-500 pointer-events-none" />
            <select
              v-model="config.currency"
              class="w-full pl-9 pr-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors appearance-none cursor-pointer"
            >
              <option v-for="opt in currencyOptions" :key="opt.value" :value="opt.value">
                {{ opt.label }}
              </option>
            </select>
          </div>
          <p class="text-xs text-neutral-600 mt-1">Currency used for all transactions</p>
        </div>
      </div>

      <!-- PayPal configuration -->
      <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5 space-y-4">
        <div>
          <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider">PayPal Configuration</h2>
          <p class="text-xs text-neutral-500 mt-1">
            Get your API credentials from the
            <a
              href="https://developer.paypal.com/dashboard/"
              target="_blank"
              class="text-oxide-400 hover:text-oxide-300 underline"
            >
              PayPal Developer Dashboard
            </a>
          </p>
        </div>

        <div>
          <label class="block text-xs text-neutral-500 mb-1">PayPal Client ID *</label>
          <input
            v-model="config.paypal_client_id"
            type="text"
            placeholder="AXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
            class="w-full px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 font-mono placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
          />
        </div>

        <div>
          <label class="block text-xs text-neutral-500 mb-1">PayPal Client Secret *</label>
          <input
            v-model="paypalSecret"
            type="password"
            placeholder="Enter to update (stored encrypted)"
            class="w-full px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 font-mono placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
          />
          <p class="text-xs text-neutral-600 mt-1">
            Stored encrypted. Leave blank to keep existing secret.
          </p>
        </div>

        <!-- Sandbox mode toggle -->
        <div class="flex items-center justify-between p-4 bg-neutral-800 rounded-lg border border-neutral-700">
          <div>
            <p class="text-sm font-medium text-neutral-200">Sandbox Mode</p>
            <p class="text-xs text-neutral-500 mt-1">
              Use PayPal sandbox for testing (no real transactions)
            </p>
          </div>
          <button
            @click="config.sandbox_mode = !config.sandbox_mode"
            :class="config.sandbox_mode ? 'bg-yellow-600' : 'bg-green-600'"
            class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-oxide-500 focus:ring-offset-2 focus:ring-offset-neutral-900"
          >
            <span
              :class="config.sandbox_mode ? 'translate-x-6' : 'translate-x-1'"
              class="inline-block h-4 w-4 transform rounded-full bg-white transition-transform"
            ></span>
          </button>
        </div>

        <!-- Production warning -->
        <div
          v-if="!config.sandbox_mode && config.enabled"
          class="flex items-start gap-3 p-3 bg-red-500/10 border border-red-500/30 rounded-lg"
        >
          <AlertTriangle class="w-4 h-4 text-red-400 mt-0.5 flex-shrink-0" />
          <div class="text-xs text-red-300">
            <strong>Production mode enabled.</strong> Real transactions will be processed. Ensure your PayPal credentials are correct.
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
