<template>
  <div class="flex items-center justify-center min-h-screen bg-gray-900">
    <div class="w-full max-w-md p-8 bg-gray-800 rounded-lg shadow-xl border border-gray-700">
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-blue-400">Momentry</h1>
        <p class="text-gray-400 mt-2">Video Analysis Portal</p>
      </div>
      <form @submit.prevent="handleLogin" class="space-y-6">
        <div>
          <label class="block text-sm font-medium text-gray-300 mb-1">Username</label>
          <input 
            v-model="username" 
            type="text" 
            class="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            placeholder="Enter username"
            required
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-300 mb-1">Password</label>
          <div class="relative">
            <input 
              v-model="password" 
              :type="showPassword ? 'text' : 'password'" 
              class="w-full px-4 py-2 pr-10 bg-gray-700 border border-gray-600 rounded text-white focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
              placeholder="Enter password"
              required
            />
            <button 
              type="button"
              @click="showPassword = !showPassword"
              class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-300"
            >
              <svg v-if="showPassword" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" />
              </svg>
              <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M3.707 2.293a1 1 0 00-1.414 1.414l14 14a1 1 0 001.414-1.414l-1.473-1.473A10.014 10.014 0 0019.542 10C18.268 5.943 14.478 3 10 3S1.732 5.943.458 10c-.18.163-.352.328-.507.48zM10 12a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd" />
                <path d="M10 5a1 1 0 011 1 1 1 0 01-2 0 1 1 0 011-1z" />
              </svg>
            </button>
          </div>
        </div>
        <div v-if="error" class="bg-red-900/50 border border-red-700 rounded p-3 text-sm text-red-300">
          {{ error }}
        </div>
        <button 
          type="submit" 
          :disabled="loading"
          class="w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded shadow transition disabled:opacity-50"
        >
          {{ loading ? 'Logging in...' : 'Login' }}
        </button>
      </form>

      <!-- API Demo (dev mode only) -->
      <div v-if="showApiExamples" class="mt-8 pt-6 border-t border-gray-700">
        <h3 class="text-sm font-medium text-gray-400 mb-3">API 範例 <span class="text-xs text-yellow-500">(dev)</span></h3>
        <div class="space-y-2 text-xs font-mono">
          <div class="bg-gray-900 p-2 rounded">
            <span class="text-green-400"># Login</span>
            <pre class="text-gray-300 whitespace-pre-wrap">curl -X POST {{ baseUrl }}/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"demo","password":"demo"}'</pre>
          </div>
          <div class="bg-gray-900 p-2 rounded">
            <span class="text-red-400"># Logout</span>
            <pre class="text-gray-300">curl -X POST {{ baseUrl }}/api/v1/auth/logout \
  -H "X-API-Key: YOUR_API_KEY"</pre>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { httpFetch, getCurrentConfig, saveConfig } from '@/api/client'

const route = useRoute()
const router = useRouter()
const username = ref(route.query.username as string || '')
const password = ref(route.query.password as string || '')
const error = ref('')
const loading = ref(false)
const showPassword = ref(false)

const baseUrl = computed(() => getCurrentConfig().api_base_url)
const showApiExamples = ref(localStorage.getItem('devMode') === 'true')

onMounted(() => {
  if (username.value && password.value) {
    handleLogin()
  }
})

const handleLogin = async () => {
  error.value = ''
  loading.value = true
  
  try {
    const config = getCurrentConfig()
    const data = await httpFetch<{
      success: boolean
      message?: string
      api_key: string
      user: Record<string, any>
    }>(`${config.api_base_url}/api/v1/auth/login`, {
      method: 'POST',
      body: JSON.stringify({ username: username.value, password: password.value })
    })

    if (data.success) {
      localStorage.setItem('momentry_user', JSON.stringify(data.user))
      localStorage.setItem('momentry_api_key', data.api_key)
      saveConfig({ ...config, api_key: data.api_key })
      const redirect = (route.query.redirect as string) || '/home'
      router.push(redirect)
    } else {
      error.value = data.message || 'Login failed'
    }
  } catch (e: any) {
    if (e.message?.includes('401')) {
      error.value = 'Invalid username or password'
    } else {
      error.value = 'Connection error. Is the server running?'
    }
  } finally {
    loading.value = false
  }
}
</script>
