<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 -->
      <div class="mt-8 pt-6 border-t border-gray-700">
        <h3 class="text-sm font-medium text-gray-400 mb-3">API 範例</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 http://127.0.0.1:3003/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 http://127.0.0.1:3003/api/v1/auth/logout</pre>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const username = ref('')
const password = ref('')
const error = ref('')
const loading = ref(false)
const showPassword = ref(false)
const router = useRouter()

const handleLogin = async () => {
  error.value = ''
  loading.value = true
  
  try {
    const response = await fetch('http://127.0.0.1:3003/api/v1/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username: username.value,
        password: password.value
      })
    });

    if (response.ok) {
      const data = await response.json();
      
      if (data.success) {
        // Save User Info
        localStorage.setItem('momentry_user', JSON.stringify(data.user));
        // Save API Key
        localStorage.setItem('momentry_api_key', data.api_key);
        
        // Update Config
        const config = {
          api_base_url: 'http://127.0.0.1:3003',
          api_key: data.api_key,
          timeout_secs: 30,
        };
        localStorage.setItem('portal_config', JSON.stringify(config));
        
        router.push('/home');
      } else {
        error.value = data.message || 'Login failed';
      }
    } else if (response.status === 401) {
      error.value = 'Invalid username or password';
    } else {
      error.value = 'Server error';
    }
  } catch (e) {
    error.value = 'Connection error. Is the server running?';
  } finally {
    loading.value = false;
  }
}
</script>
