<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRequestStore } from '../stores/requestStore';
import { useSettingsStore } from '../stores/settingsStore';
import KeyValueEditor from './KeyValueEditor.vue';
import AuthPanel from './AuthPanel.vue';
import CustomSelect from './CustomSelect.vue';
import { invoke } from '@tauri-apps/api/core';
import { Codemirror } from 'vue-codemirror';
import { json } from '@codemirror/lang-json';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView } from '@codemirror/view';
import { Play, Loader2 } from 'lucide-vue-next';

const store = useRequestStore();
const settings = useSettingsStore();
const activeTab = ref('params');
const isLoading = ref(false);

const extensions = computed(() => {
  const theme = EditorView.theme({
    "&": { 
      backgroundColor: "transparent !important", 
      height: "100%",
    },
    ".cm-content, .cm-gutter": {
      fontFamily: `${settings.editorFontFamily} !important`
    },
    ".cm-gutters": { 
      backgroundColor: "transparent !important" 
    }
  });
  
  return [json(), oneDark, theme];
});

const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];

const executeRequest = async () => {
  if (!store.activeRequest.url) return;
  
  isLoading.value = true;
  
  try {
    // Prepare headers and params map
    const headers: Record<string, string> = {};
    store.activeRequest.headers.filter(h => h.enabled && h.key).forEach(h => headers[h.key] = h.value);
    
    const params: Record<string, string> = {};
    store.activeRequest.params.filter(p => p.enabled && p.key).forEach(p => params[p.key] = p.value);

    // Execute
    const response: any = await invoke('execute_request', {
      method: store.activeRequest.method,
      url: store.activeRequest.url,
      headers,
      body: store.activeRequest.body || null,
      queryParams: params,
      auth: store.activeRequest.auth,
    });

    // Update Store
    store.activeRequest.response = {
        status: response.status,
        headers: response.headers,
        body: response.body,
        time: response.time_elapsed,
        size: new Blob([response.body]).size
    };

    // Add to history if successful
    store.addToHistory(store.activeRequest);

  } catch (error) {
    console.error(error);
    // Simple alert for now, or could use a toast
    alert('Request Failed: ' + error);
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <div class="flex flex-col h-full bg-slate-900">
    <!-- Top Bar -->
    <div class="p-4 border-b border-slate-800 flex gap-2 items-center">
      <div class="flex-1 flex items-center bg-slate-950 rounded-lg border border-slate-800 focus-within:border-indigo-500/50 focus-within:ring-1 focus-within:ring-indigo-500/50 transition-all overflow-visible z-20">
        <CustomSelect
            v-model="store.activeRequest.method"
            :options="methods"
            triggerClass="bg-transparent text-xs font-bold px-3 py-2 text-slate-200 border-r border-slate-800 focus:outline-none hover:bg-slate-900 cursor-pointer uppercase h-full min-w-[90px]"
        />
        <input 
            type="text" 
            v-model="store.activeRequest.url"
            placeholder="https://api.example.com/v1/users"
            class="flex-1 bg-transparent border-none focus:ring-0 text-sm text-slate-200 px-3 py-2 placeholder-slate-600 h-full"
            @keydown.enter="executeRequest"
        >
      </div>
      <button 
        @click="executeRequest"
        :disabled="isLoading"
        class="bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed text-white px-4 py-2 rounded-lg font-medium text-sm flex items-center gap-2 transition-all shadow-lg shadow-indigo-900/20"
      >
        <Loader2 v-if="isLoading" class="w-4 h-4 animate-spin" />
        <Play v-else class="w-4 h-4 fill-current" />
        Send
      </button>
    </div>

    <!-- Configuration Tabs -->
    <div class="flex border-b border-slate-800">
      <button 
        v-for="tab in ['params', 'headers', 'body', 'auth']" 
        :key="tab"
        @click="activeTab = tab"
        class="px-4 py-2 text-xs font-medium uppercase tracking-wide border-b-2 transition-colors"
        :class="activeTab === tab ? 'border-indigo-500 text-indigo-400 bg-indigo-500/5' : 'border-transparent text-slate-500 hover:text-slate-300 hover:bg-slate-800/50'"
      >
        {{ tab }}
      </button>
    </div>

    <!-- Content Area -->
    <div class="flex-1 overflow-hidden relative">
        <KeepAlive>
            <KeyValueEditor 
                v-if="activeTab === 'params'" 
                v-model="store.activeRequest.params" 
            />
        </KeepAlive>
        <KeepAlive>
            <KeyValueEditor 
                v-if="activeTab === 'headers'" 
                v-model="store.activeRequest.headers" 
            />
        </KeepAlive>
        <div v-if="activeTab === 'body'" class="h-full w-full overflow-hidden">
            <Codemirror
                v-model="store.activeRequest.body"
                placeholder="Request Body (JSON)"
                :style="{ 
                  height: '100%', 
                  fontSize: settings.editorFontSize + 'px', 
                  fontFamily: settings.editorFontFamily 
                }"
                :autofocus="true"
                :indent-with-tab="true"
                :tab-size="2"
                :extensions="extensions"
            />
        </div>
        <KeepAlive>
            <AuthPanel
                v-if="activeTab === 'auth'" 
            />
        </KeepAlive>
    </div>
  </div>
</template>
