<script setup lang="ts">
import { ref, onMounted } from 'vue'

const props = defineProps<{ token: string }>()

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1'

const isLoading = ref(true)
const isSaving = ref(false)
const savedMessage = ref('')
const errorMsg = ref('')

// Default LLM Options based on the API docs GET /sys/config/llms (mocking for now as we didn't build that API fully)
const providers = ['openai', 'anthropic', 'gemini', 'deepseek']

const form = ref({
  product_name: '',
  industry: '',
  target_audience: '',
  core_features: '',
  user_intent: '',
  relevance_keywords: '',
  default_llm_provider: '',
  default_llm_model: ''
})

const fetchProfile = async () => {
  try {
    const res = await fetch(`${API_BASE}/users/me/product_profiles`, {
      headers: { 'Authorization': `Bearer ${props.token}` }
    })
    const data = await res.json()
    if (res.ok && data.code === 200 && data.data) {
      const p = data.data
      form.value = {
        product_name: p.product_name || '',
        industry: p.industry || '',
        target_audience: p.target_audience || '',
        core_features: p.core_features || '',
        user_intent: p.user_intent || '',
        relevance_keywords: p.relevance_keywords || '',
        default_llm_provider: p.default_llm_provider || '',
        default_llm_model: p.default_llm_model || ''
      }
      
      // Sync relevance keywords to local storage for Content Script
      chrome.storage.local.set({ relevance_keywords: form.value.relevance_keywords })
    }
  } catch (err: any) {
    console.error('Failed to load profile:', err)
  } finally {
    isLoading.value = false
  }
}

const saveProfile = async () => {
  isSaving.value = true
  savedMessage.value = ''
  errorMsg.value = ''

  try {
    const res = await fetch(`${API_BASE}/users/me/product_profiles`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${props.token}`
      },
      body: JSON.stringify(form.value)
    })
    
    const data = await res.json()
    
    if (!res.ok || data.code !== 200) {
      throw new Error(data.message || 'Failed to save profile')
    }
    
    // Sync relevance keywords to local storage for Content Script
    chrome.storage.local.set({ relevance_keywords: form.value.relevance_keywords })
    
    savedMessage.value = 'Profile saved successfully!'
    setTimeout(() => { savedMessage.value = '' }, 3000)
    
  } catch (err: any) {
    errorMsg.value = err.message
  } finally {
    isSaving.value = false
  }
}

onMounted(() => {
  if (props.token) {
    fetchProfile()
  }
})
</script>

<template>
  <div v-if="isLoading" class="p-10 flex justify-center">
    <div class="w-6 h-6 border-2 border-white/20 border-t-white rounded-full animate-spin"></div>
  </div>

  <form v-else @submit.prevent="saveProfile" class="space-y-6">
    <div v-if="errorMsg" class="p-3 bg-red-500/10 border border-red-500/20 text-red-400 text-sm rounded-lg">
      {{ errorMsg }}
    </div>
    <div v-if="savedMessage" class="p-3 bg-green-500/10 border border-green-500/20 text-green-400 text-sm rounded-lg">
      {{ savedMessage }}
    </div>

    <div class="grid grid-cols-2 gap-6">
      <div class="space-y-1.5">
        <label class="text-xs font-medium text-zinc-300">Product Name</label>
        <input 
          v-model="form.product_name"
          type="text" 
          required
          class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors"
          placeholder="e.g. SwiftBiu"
        />
      </div>

      <div class="space-y-1.5">
        <label class="text-xs font-medium text-zinc-300">Industry / Niche</label>
        <input 
          v-model="form.industry"
          type="text" 
          class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors"
          placeholder="e.g. AI Tools, Developer Productivity"
        />
      </div>
    </div>

    <div class="space-y-1.5">
      <label class="text-xs font-medium text-zinc-300">Target Audience</label>
      <input 
        v-model="form.target_audience"
        type="text" 
        class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors"
        placeholder="e.g. Indie hackers building on MacOS"
      />
    </div>

    <div class="space-y-1.5">
      <label class="text-xs font-medium text-zinc-300 flex items-center gap-2">
        Core Features 
        <span class="text-[10px] text-zinc-500 font-normal">What does your product do?</span>
      </label>
      <textarea 
        v-model="form.core_features"
        rows="3"
        class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors resize-none"
        placeholder="e.g. One-click screenshot translation, local OCR, native macOS support..."
      ></textarea>
    </div>

    <div class="space-y-1.5">
      <label class="text-xs font-medium text-zinc-300 flex items-center gap-2">
        User Intent / Pitch Angle
        <span class="text-[10px] text-zinc-500 font-normal">How do you usually reply to people?</span>
      </label>
      <textarea 
        v-model="form.user_intent"
        rows="2"
        class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors resize-none"
        placeholder="e.g. I generally want to help people solve translation problems and mention that SwiftBiu is a fast native solution."
      ></textarea>
    </div>

    <div class="space-y-1.5">
      <label class="text-xs font-medium text-zinc-300">Relevance Keywords (Comma separated)</label>
      <input 
        v-model="form.relevance_keywords"
        type="text" 
        class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors"
        placeholder="e.g. translation, OCR, macos app, bob alternative"
      />
    </div>

    <div class="pt-4 border-t border-white/10 pb-2">
      <h3 class="text-sm font-medium text-zinc-300 mb-4">Advanced: Preferred LLM Override</h3>
      <div class="grid grid-cols-2 gap-6">
        <div class="space-y-1.5">
          <label class="text-xs font-medium text-zinc-400">Provider</label>
          <select 
            v-model="form.default_llm_provider"
            class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 appearance-none"
          >
            <option value="">System Default (Recommended)</option>
            <option v-for="p in providers" :key="p" :value="p">{{ p.charAt(0).toUpperCase() + p.slice(1) }}</option>
          </select>
        </div>
        <div class="space-y-1.5">
          <label class="text-xs font-medium text-zinc-400">Model Name</label>
          <input 
            v-model="form.default_llm_model"
            type="text" 
            class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors"
            placeholder="e.g. gpt-4o, claude-3-5-sonnet"
          />
        </div>
      </div>
    </div>

    <div class="pt-4 flex justify-end">
      <button 
        type="submit"
        :disabled="isSaving"
        class="px-6 py-2.5 bg-brand-primary hover:bg-brand-primary/90 text-white rounded-lg text-sm font-medium transition-all shadow-lg flex items-center justify-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
      >
        <span v-if="isSaving" class="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin"></span>
        {{ isSaving ? 'Saving...' : 'Save Profile' }}
      </button>
    </div>
  </form>
</template>
