<script setup>
import { ref, watch } from 'vue';
import { Head, useForm, usePage } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';

const props = defineProps({ settings: Object });
const page = usePage();
const testConnectionState = ref(null);

const aiForm = useForm({
  openai_api_key: '',
  openai_model: props.settings.openai_model,
  openai_max_tokens: parseInt(props.settings.openai_max_tokens),
  ai_planner_enabled: props.settings.ai_planner_enabled === '1',
  ai_humanizer_enabled: props.settings.ai_humanizer_enabled === '1',
  ai_planner_model: props.settings.ai_planner_model,
  ai_humanizer_model: props.settings.ai_humanizer_model,
  ai_allow_personal_data: props.settings.ai_allow_personal_data === '1',
  ai_redact_personal_data: props.settings.ai_redact_personal_data === '1',
});

const testAiConnection = () => {
  testConnectionState.value = {
    type: 'info',
    message: 'Testing OpenAI connection...',
  };

  aiForm.post('/storesight/admin/settings/ai/test', {
    preserveScroll: true,
    preserveState: true,
    onSuccess: () => {
      const flash = page.props.flash || {};

      if (flash.success) {
        testConnectionState.value = { type: 'success', message: flash.success };
        return;
      }

      if (flash.error) {
        testConnectionState.value = { type: 'error', message: flash.error };
        return;
      }

      testConnectionState.value = {
        type: 'success',
        message: 'OpenAI connection test completed.',
      };
    },
    onError: () => {
      testConnectionState.value = {
        type: 'error',
        message: 'The test request could not be completed.',
      };
    },
  });
};

watch(() => page.props.flash?.success, (value) => {
  if (value) {
    testConnectionState.value = { type: 'success', message: value };
  }
});

watch(() => page.props.flash?.error, (value) => {
  if (value) {
    testConnectionState.value = { type: 'error', message: value };
  }
});

const rateForm = useForm({
  rate_limit_per_day: parseInt(props.settings.rate_limit_per_day),
  rate_limit_per_minute: parseInt(props.settings.rate_limit_per_minute),
  max_tokens_per_day: parseInt(props.settings.max_tokens_per_day),
});

const paymentForm = useForm({
  license_price: parseFloat(props.settings.license_price),
  free_trial_days: parseInt(props.settings.free_trial_days),
});

const licenseForm = useForm({
  sites_per_license: parseInt(props.settings.sites_per_license),
  token_expiry_days: parseInt(props.settings.token_expiry_days),
  heartbeat_enabled: props.settings.heartbeat_enabled === '1',
});

const adminForm = useForm({
  admin_email: props.settings.admin_email,
  password: '',
});

</script>

<template>
  <AdminLayout>
    <template #title>Settings</template>
    <Head title="Settings - Admin" />

    <div class="max-w-3xl">
      <!-- AI Config -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">AI Configuration</h2>
        <form @submit.prevent="aiForm.put('/storesight/admin/settings/ai')" class="space-y-5">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">OpenAI API Key</label>
            <input
              v-model="aiForm.openai_api_key"
              type="password"
              autocomplete="new-password"
              :placeholder="props.settings.openai_api_key_configured ? 'Stored securely. Enter a new key to replace it.' : 'sk-...'"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none font-mono"
            >
            <p class="text-xs text-gray-400 mt-1">Stored encrypted in app settings. Leave blank to keep the current key.</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Model</label>
            <select v-model="aiForm.openai_model" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] outline-none">
              <option value="gpt-5.1">gpt-5.1</option>
              <option value="gpt-5-mini">gpt-5-mini</option>
              <option value="gpt-5-nano">gpt-5-nano</option>
              <option value="gpt-4.1">gpt-4.1</option>
              <option value="gpt-4.1-mini">gpt-4.1-mini</option>
              <option value="gpt-4.1-nano">gpt-4.1-nano</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Max Tokens per Request</label>
            <input v-model.number="aiForm.openai_max_tokens" type="number" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Planner Model</label>
              <select v-model="aiForm.ai_planner_model" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] outline-none">
                <option value="gpt-5.1">gpt-5.1</option>
                <option value="gpt-5-mini">gpt-5-mini</option>
                <option value="gpt-5-nano">gpt-5-nano</option>
                <option value="gpt-4.1">gpt-4.1</option>
                <option value="gpt-4.1-mini">gpt-4.1-mini</option>
                <option value="gpt-4.1-nano">gpt-4.1-nano</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Humaniser Model</label>
              <select v-model="aiForm.ai_humanizer_model" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] outline-none">
                <option value="gpt-5.1">gpt-5.1</option>
                <option value="gpt-5-mini">gpt-5-mini</option>
                <option value="gpt-5-nano">gpt-5-nano</option>
                <option value="gpt-4.1">gpt-4.1</option>
                <option value="gpt-4.1-mini">gpt-4.1-mini</option>
                <option value="gpt-4.1-nano">gpt-4.1-nano</option>
              </select>
            </div>
          </div>
          <div class="space-y-3 rounded-lg border border-gray-200 bg-gray-50 p-4">
            <label class="flex items-start gap-3">
              <input v-model="aiForm.ai_planner_enabled" type="checkbox" class="mt-1 h-4 w-4 rounded border-gray-300 text-[#4F46E5] focus:ring-[#4F46E5]">
              <span>
                <span class="block text-sm font-medium text-gray-700">Enable planner fallback</span>
                <span class="block text-xs text-gray-500">Use OpenAI only to interpret low-confidence questions into a structured local query plan.</span>
              </span>
            </label>
            <label class="flex items-start gap-3">
              <input v-model="aiForm.ai_humanizer_enabled" type="checkbox" class="mt-1 h-4 w-4 rounded border-gray-300 text-[#4F46E5] focus:ring-[#4F46E5]">
              <span>
                <span class="block text-sm font-medium text-gray-700">Enable result humanisation</span>
                <span class="block text-xs text-gray-500">Allow OpenAI to rewrite aggregate local results into cleaner natural-language responses.</span>
              </span>
            </label>
            <label class="flex items-start gap-3">
              <input v-model="aiForm.ai_allow_personal_data" type="checkbox" class="mt-1 h-4 w-4 rounded border-gray-300 text-[#4F46E5] focus:ring-[#4F46E5]">
              <span>
                <span class="block text-sm font-medium text-gray-700">Allow personal data in AI requests</span>
                <span class="block text-xs text-gray-500">Off by default. Keep names, emails, and similar identifiers out of AI-bound requests unless you explicitly permit them.</span>
              </span>
            </label>
            <label class="flex items-start gap-3">
              <input v-model="aiForm.ai_redact_personal_data" type="checkbox" class="mt-1 h-4 w-4 rounded border-gray-300 text-[#4F46E5] focus:ring-[#4F46E5]">
              <span>
                <span class="block text-sm font-medium text-gray-700">Redact outbound AI requests</span>
                <span class="block text-xs text-gray-500">Redact emails, phone numbers, and address-like strings before requests leave the site.</span>
              </span>
            </label>
          </div>
          <div class="flex flex-wrap gap-3">
            <button type="submit" :disabled="aiForm.processing" class="bg-[#4F46E5] text-white font-semibold px-6 py-2.5 rounded-lg hover:bg-[#4338CA] transition text-sm">Save AI Settings</button>
            <button type="button" @click="testAiConnection" :disabled="aiForm.processing" class="bg-white text-gray-700 font-semibold px-6 py-2.5 rounded-lg border border-gray-300 hover:bg-gray-50 transition text-sm">
              {{ aiForm.processing ? 'Testing...' : 'Test API Connection' }}
            </button>
          </div>
          <div
            v-if="testConnectionState"
            :class="[
              'rounded-lg border px-4 py-3 text-sm',
              testConnectionState.type === 'success' ? 'border-green-200 bg-green-50 text-green-700' : '',
              testConnectionState.type === 'error' ? 'border-red-200 bg-red-50 text-red-700' : '',
              testConnectionState.type === 'info' ? 'border-blue-200 bg-blue-50 text-blue-700' : '',
            ]"
          >
            {{ testConnectionState.message }}
          </div>
        </form>
      </div>

      <!-- Rate Limiting -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">Rate Limiting</h2>
        <form @submit.prevent="rateForm.put('/storesight/admin/settings/rate-limits')" class="space-y-5">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Requests per day (per license)</label>
              <input v-model.number="rateForm.rate_limit_per_day" type="number" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Requests per minute (per license)</label>
              <input v-model.number="rateForm.rate_limit_per_minute" type="number" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Max tokens per day (global)</label>
            <input v-model.number="rateForm.max_tokens_per_day" type="number" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
            <p class="text-xs text-gray-400 mt-1">Set to 0 for unlimited.</p>
          </div>
          <button type="submit" :disabled="rateForm.processing" class="bg-[#4F46E5] text-white font-semibold px-6 py-2.5 rounded-lg hover:bg-[#4338CA] transition text-sm">Save Rate Limits</button>
        </form>
      </div>

      <!-- Payment -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">Payment Settings</h2>
        <form @submit.prevent="paymentForm.put('/storesight/admin/settings/payment')" class="space-y-5">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Stripe Keys</label>
            <p class="text-xs text-gray-400">Managed via .env file (STRIPE_KEY, STRIPE_SECRET, STRIPE_WEBHOOK_SECRET).</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">License Price (GBP)</label>
            <div class="flex items-center">
              <span class="text-gray-500 mr-2 text-lg">&pound;</span>
              <input v-model.number="paymentForm.license_price" type="number" class="w-32 px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
              <span class="text-gray-400 ml-2 text-sm">/month</span>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Free Trial Duration</label>
            <div class="flex items-center">
              <input v-model.number="paymentForm.free_trial_days" type="number" class="w-32 px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
              <span class="text-gray-400 ml-2 text-sm">days</span>
            </div>
          </div>
          <button type="submit" :disabled="paymentForm.processing" class="bg-[#4F46E5] text-white font-semibold px-6 py-2.5 rounded-lg hover:bg-[#4338CA] transition text-sm">Save Payment Settings</button>
        </form>
      </div>

      <!-- License Config -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">License Configuration</h2>
        <form @submit.prevent="licenseForm.put('/storesight/admin/settings/license')" class="space-y-5">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Sites per License</label>
            <input v-model.number="licenseForm.sites_per_license" type="number" class="w-32 px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Token Expiry</label>
            <div class="flex items-center">
              <input v-model.number="licenseForm.token_expiry_days" type="number" class="w-32 px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
              <span class="text-gray-400 ml-2 text-sm">days</span>
            </div>
          </div>
          <div class="flex items-center space-x-3">
            <input v-model="licenseForm.heartbeat_enabled" type="checkbox" class="w-4 h-4 text-[#4F46E5] border-gray-300 rounded focus:ring-[#4F46E5]">
            <label class="text-sm text-gray-700">Enable heartbeat check</label>
          </div>
          <button type="submit" :disabled="licenseForm.processing" class="bg-[#4F46E5] text-white font-semibold px-6 py-2.5 rounded-lg hover:bg-[#4338CA] transition text-sm">Save License Settings</button>
        </form>
      </div>

      <!-- Admin Account -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">Admin Account</h2>
        <form @submit.prevent="adminForm.put('/storesight/admin/settings/admin')" class="space-y-5">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Admin Email</label>
            <input v-model="adminForm.admin_email" type="email" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Change Password</label>
            <input v-model="adminForm.password" type="password" placeholder="New password" class="w-full px-4 py-3 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#4F46E5] focus:border-[#4F46E5] outline-none">
          </div>
          <button type="submit" :disabled="adminForm.processing" class="bg-[#4F46E5] text-white font-semibold px-6 py-2.5 rounded-lg hover:bg-[#4338CA] transition text-sm">Update Admin Account</button>
        </form>
      </div>
    </div>
  </AdminLayout>
</template>
