<template>
  <div class="min-h-screen bg-base-100 p-4 md:p-6">
    <BreadcrumbHeader title="Key Details" />

    <div class="divider mt-1 mb-0"></div>
    <div class="card border border-base-300/40 shadow-sm"v-if="key" >
        <form @submit.prevent="updateKey" class="card-body space-y-5">
          <div class="space-y-4">
            <h2 class="text-base font-medium text-base-content border-b border-base-300/30 pb-2 mb-4">
              Basic Information
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-4">
              <div class="form-control">
                <label for="name" class="label">
                  <span class="label-text">
                    Name <span class="text-red-500">*</span>
                  </span>
                </label>
                <input id="name" type="text" v-model="key.name" placeholder="API Key Name"
                  class="input input-sm input-bordered w-full" required />
              </div>

              <div class="form-control">
                <label for="apitype" class="label">
                  <span class="label-text">
                    Type <span class="text-red-500">*</span>
                  </span>
                </label>
                <div class="relative">
                  <select id="apitype" v-model="key.type" class="select select-sm select-bordered w-full pl-10"
                    required>
                    <option class="disabled" value="" selected>Select API Type</option>
                    <option value="openai">OpenAI</option>
                    <option value="claude">Claude</option>
                    <option value="gemini">Gemini</option>
                    <option value="openai-compatible">OpenAI Compatible</option>
                  </select>
                  <button type="button" class="absolute inset-y-0 left-0 px-3 flex items-center text-base-content/60 hover:text-base-content/80 focus:outline-none focus:ring-0 rounded-r-md"
                    id="password-visibility-toggle">
                    <template v-if="key.type === 'openai'">
                      <img src="../../assets/openai.svg" class="w-5 h-5" alt="">
                    </template>
                    <template v-else-if="key.type === 'claude'">
                      <img src="../../assets/claude.svg" class="w-5 h-5" alt="">
                    </template>
                    <template v-else-if="key.type === 'gemini'">
                      <img src="../../assets/gemini.svg" class="w-5 h-5" alt="">
                    </template>
                    <template v-else="key.type">
                      <img src="../../assets/logo.svg" class="w-5 h-5" alt="">
                    </template>
                  </button>
                </div>
              </div>

              <div class="form-control">
                <label for="apikey" class="label">
                  <span class="label-text">
                    API Key <span class="text-red-500">*</span>
                  </span>
                </label>
                <input id="apikey" type="text" v-model="key.apikey" placeholder="Your API Key"
                  class="input input-sm input-bordered w-full" required />
              </div>

              <div class="form-control">
                <label for="endpoint" class="label">
                  <span class="label-text">Endpoint</span>
                </label>
                <input id="endpoint" type="text" v-model="key.endpoint" placeholder="API Endpoint URL"
                  class="input input-sm input-bordered w-full" />
              </div>
            </div>
          </div>

          <div class="collapse collapse-arrow">
            <input type="checkbox" checked class="min-h-0 py-2" />
            <div class="collapse-title text-base font-medium min-h-0 py-1 px-0">
              Advanced Options
            </div>
            <div class="collapse-content px-0">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-4 pt-3">
                <div class="form-control">
                  <label for="resource_name" class="label">
                    <span class="label-text">Resource Name</span>
                  </label>
                  <input id="resource_name" type="text" v-model="key.resource_name" placeholder="Resource Name"
                    class="input input-sm input-bordered w-full" />
                </div>

                <div class="form-control">
                  <label for="deployment_name" class="label">
                    <span class="label-text">Deployment Name</span>
                  </label>
                  <input id="deployment_name" type="text" v-model="key.deployment_name"
                    placeholder="Deployment Name" class="input input-sm input-bordered w-full" />
                </div>

                <div class="form-control">
                  <label for="api_secret" class="label">
                    <span class="label-text">API Secret</span>
                  </label>
                  <input id="api_secret" type="text" v-model="key.api_secret" placeholder="API Secret"
                    class="input input-sm input-bordered w-full" />
                </div>

                <div class="form-control">
                  <label for="model_prefix" class="label">
                    <span class="label-text">Model Prefix</span>
                  </label>
                  <input id="model_prefix" type="text" v-model="key.model_prefix" placeholder="Model Prefix"
                    class="input input-sm input-bordered w-full" />
                </div>

                <div class="form-control">
                  <label for="model_alias" class="label">
                    <span class="label-text">Model Alias</span>
                  </label>
                  <textarea id="model_alias" v-model="key.model_alias" placeholder="{}"
                    class="textarea textarea-sm textarea-bordered w-full"></textarea>
                </div>

                <div class="form-control">
                  <label for="parameters" class="label">
                    <span class="label-text">Parameters (JSON)</span>
                  </label>
                  <textarea id="parameters" v-model="key.parameters" placeholder="{}"
                    class="textarea textarea-sm textarea-bordered w-full"></textarea>
                </div>

                <div class="md:col-span-2 form-control">
                  <label for="support_models" class="label">
                    <span class="label-text">Support Models</span>
                  </label>
                  <!-- <textarea id="support_models" v-model="key.support_models_text"
                    placeholder='["model1", "model2"]' class="textarea textarea-sm textarea-bordered w-full"></textarea> -->
                  <el-input-tag v-model="key.support_models_array" :trigger="'Enter'" clearable
                    placeholder="Please input"  @change="onchange_supportmodel"/>
                </div>

                <div class="form-control">
                  <label class="label">
                    <span class="label-text">Status</span>
                  </label>
                  <div class="flex items-center space-x-3 h-9">
                    <input type="checkbox" v-model="key.active"
                      :class="`toggle toggle-sm ${key.active ? 'toggle-success' : 'toggle-error'}`" />
                    <span class="text-sm text-base-content/90">
                      {{ key.active ? 'Active' : 'Inactive' }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="flex justify-end pt-4 items-center gap-2">
            <button @click="cancel" class="btn btn-sm btn-outline">Back</button>
            <button type="submit" class="btn btn-outline btn-sm px-4 text-sm font-medium btn-success">
              Update
            </button>
          </div>
        </form>
      </div>
  
  </div>
</template>

<script setup>
import { ref, computed, onMounted, inject } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import { Eye, EyeOff, BadgeCheck, Send, CircleX, CircleCheckBig, TrashIcon, Infinity } from 'lucide-vue-next';
import { useKeyStore } from '../../stores/key';
import BreadcrumbHeader from '@/components/dashboard/BreadcrumbHeader.vue';

const route = useRoute();
const router = useRouter();
const keyStore = useKeyStore();
const { setToast } = inject('toast');

const keyId = computed(() => route.query.id);

onMounted(async () => {

});

const key = computed(() => keyStore.key);
const loading = computed(() => keyStore.loading);

onMounted(async () => {
  console.log('keyId', keyId.value)
  if (keyId.value) {
    await keyStore.fetchKey(keyId.value);
  }
});

const onchange_supportmodel = () => {
  key.value.support_models = JSON.stringify(key.value.support_models_array)
}

const updateKey = async () => {
  
  try {
    const res = await keyStore.updateKey(key.value);
    console.log('updateKey', res)
    if (res.data?.code == 200) {
      setToast(`Key ${key.value.name} updated`, 'success');
    }
    await keyStore.refreshKey(key.value.id);
  } catch (err) {
    console.error('Error updating key:', err);
  }
};

const cancel = () => {
  router.push({ name: 'ApiKey' });
}

</script>