<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import {
  dataManagementAPI,
  type DataManagementS3Profile,
  type TestS3Request
} from '@/api/admin/dataManagement'
import BaseDialog from '@/components/common/BaseDialog.vue'

const { t } = useI18n()
const appStore = useAppStore()

const loading = ref(false)
const profiles = ref<DataManagementS3Profile[]>([])
const showModal = ref(false)
const editing = ref<DataManagementS3Profile | null>(null)
const saving = ref(false)

const form = ref<{
  profile_id: string
  name: string
  enabled: boolean
  endpoint: string
  region: string
  bucket: string
  access_key_id: string
  secret_access_key: string
  prefix: string
  force_path_style: boolean
  use_ssl: boolean
  set_active: boolean
}>({
  profile_id: '',
  name: '',
  enabled: true,
  endpoint: '',
  region: 'us-east-1',
  bucket: '',
  access_key_id: '',
  secret_access_key: '',
  prefix: '',
  force_path_style: false,
  use_ssl: true,
  set_active: false
})

async function fetchProfiles() {
  loading.value = true
  try {
    const resp = await dataManagementAPI.listS3Profiles()
    profiles.value = resp.items
  } catch (err: any) {
    console.error('[S3ProfilesCard] Failed to fetch profiles', err)
    appStore.showError(err?.response?.data?.detail || t('common.loadFailed'))
  } finally {
    loading.value = false
  }
}

function openModal(profile?: DataManagementS3Profile) {
  if (profile) {
    editing.value = profile
    form.value = {
      profile_id: profile.profile_id,
      name: profile.name,
      enabled: profile.s3.enabled,
      endpoint: profile.s3.endpoint,
      region: profile.s3.region,
      bucket: profile.s3.bucket,
      access_key_id: profile.s3.access_key_id,
      secret_access_key: '',
      prefix: profile.s3.prefix,
      force_path_style: profile.s3.force_path_style,
      use_ssl: profile.s3.use_ssl,
      set_active: false
    }
  } else {
    editing.value = null
    form.value = {
      profile_id: '',
      name: '',
      enabled: true,
      endpoint: '',
      region: 'us-east-1',
      bucket: '',
      access_key_id: '',
      secret_access_key: '',
      prefix: '',
      force_path_style: false,
      use_ssl: true,
      set_active: false
    }
  }
  showModal.value = true
}

function closeModal() {
  showModal.value = false
  editing.value = null
}

async function save() {
  saving.value = true
  try {
    if (editing.value) {
      await dataManagementAPI.updateS3Profile(form.value.profile_id, {
        name: form.value.name,
        enabled: form.value.enabled,
        endpoint: form.value.endpoint,
        region: form.value.region,
        bucket: form.value.bucket,
        access_key_id: form.value.access_key_id,
        secret_access_key: form.value.secret_access_key || undefined,
        prefix: form.value.prefix,
        force_path_style: form.value.force_path_style,
        use_ssl: form.value.use_ssl
      })
    } else {
      await dataManagementAPI.createS3Profile(form.value)
    }
    await fetchProfiles()
    closeModal()
    appStore.showSuccess(t('common.saved'))
  } catch (err: any) {
    console.error('[S3ProfilesCard] Failed to save profile', err)
    appStore.showError(err?.response?.data?.detail || t('common.saveFailed'))
  } finally {
    saving.value = false
  }
}

async function test(profile: DataManagementS3Profile) {
  try {
    const req: TestS3Request = {
      endpoint: profile.s3.endpoint,
      region: profile.s3.region,
      bucket: profile.s3.bucket,
      access_key_id: profile.s3.access_key_id,
      prefix: profile.s3.prefix,
      force_path_style: profile.s3.force_path_style,
      use_ssl: profile.s3.use_ssl
    }
    await dataManagementAPI.testS3(req)
    appStore.showSuccess(t('admin.dataManagement.s3.testSuccess'))
  } catch (err: any) {
    console.error('[S3ProfilesCard] Failed to test profile', err)
    appStore.showError(err?.response?.data?.detail || t('admin.dataManagement.s3.testFailed'))
  }
}

async function activate(profileId: string) {
  try {
    await dataManagementAPI.setActiveS3Profile(profileId)
    await fetchProfiles()
    appStore.showSuccess(t('common.saved'))
  } catch (err: any) {
    console.error('[S3ProfilesCard] Failed to activate profile', err)
    appStore.showError(err?.response?.data?.detail || t('common.saveFailed'))
  }
}

async function remove(profileId: string) {
  if (!confirm(t('admin.dataManagement.profiles.confirmDelete'))) return
  try {
    await dataManagementAPI.deleteS3Profile(profileId)
    await fetchProfiles()
    appStore.showSuccess(t('common.deleted'))
  } catch (err: any) {
    console.error('[S3ProfilesCard] Failed to delete profile', err)
    appStore.showError(err?.response?.data?.detail || t('common.deleteFailed'))
  }
}

onMounted(fetchProfiles)

defineExpose({ refresh: fetchProfiles })
</script>

<template>
  <div class="card p-6">
    <div class="mb-4 flex items-center justify-between">
      <div>
        <h3 class="text-base font-semibold text-gray-900 dark:text-white">
          {{ t('admin.dataManagement.s3.title') }}
        </h3>
        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
          {{ t('admin.dataManagement.s3.description') }}
        </p>
      </div>
      <button type="button" class="btn btn-primary btn-sm" @click="openModal()">
        {{ t('admin.dataManagement.s3.addProfile') }}
      </button>
    </div>

    <div v-if="loading" class="py-8 text-center text-gray-500 dark:text-gray-400">
      {{ t('common.loading') }}
    </div>
    <div v-else-if="profiles.length === 0" class="py-8 text-center text-gray-500 dark:text-gray-400">
      {{ t('admin.dataManagement.s3.noProfiles') }}
    </div>
    <div v-else class="overflow-x-auto">
      <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
        <thead>
          <tr>
            <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
              {{ t('admin.dataManagement.profiles.name') }}
            </th>
            <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
              {{ t('admin.dataManagement.s3.bucket') }}
            </th>
            <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
              {{ t('admin.dataManagement.s3.region') }}
            </th>
            <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
              {{ t('admin.dataManagement.profiles.status') }}
            </th>
            <th class="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
              {{ t('common.actions') }}
            </th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
          <tr v-for="profile in profiles" :key="profile.profile_id">
            <td class="whitespace-nowrap px-4 py-3 text-sm text-gray-900 dark:text-white">
              {{ profile.name }}
            </td>
            <td class="whitespace-nowrap px-4 py-3 text-sm text-gray-500 dark:text-gray-400">
              {{ profile.s3.bucket }}
            </td>
            <td class="whitespace-nowrap px-4 py-3 text-sm text-gray-500 dark:text-gray-400">
              {{ profile.s3.region }}
            </td>
            <td class="whitespace-nowrap px-4 py-3 text-sm">
              <span
                class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
                :class="profile.is_active ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400' : 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400'"
              >
                {{ profile.is_active ? t('admin.dataManagement.profiles.active') : t('admin.dataManagement.profiles.inactive') }}
              </span>
            </td>
            <td class="whitespace-nowrap px-4 py-3 text-right text-sm">
              <button
                type="button"
                class="mr-2 text-primary-600 hover:text-primary-700"
                @click="test(profile)"
              >
                {{ t('admin.dataManagement.s3.test') }}
              </button>
              <button
                v-if="!profile.is_active"
                type="button"
                class="mr-2 text-primary-600 hover:text-primary-700"
                @click="activate(profile.profile_id)"
              >
                {{ t('admin.dataManagement.profiles.activate') }}
              </button>
              <button
                type="button"
                class="mr-2 text-primary-600 hover:text-primary-700"
                @click="openModal(profile)"
              >
                {{ t('common.edit') }}
              </button>
              <button
                type="button"
                class="text-red-600 hover:text-red-700"
                @click="remove(profile.profile_id)"
              >
                {{ t('common.delete') }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Modal -->
    <BaseDialog
      :show="showModal"
      :title="editing ? t('admin.dataManagement.s3.editProfile') : t('admin.dataManagement.s3.addProfile')"
      width="wide"
      @close="closeModal"
    >
      <form @submit.prevent="save">
        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div>
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.dataManagement.profiles.profileId') }}
            </label>
            <input
              v-model="form.profile_id"
              :disabled="!!editing"
              class="input w-full"
              required
            />
          </div>
          <div>
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.dataManagement.profiles.name') }}
            </label>
            <input v-model="form.name" class="input w-full" required />
          </div>
          <div>
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.dataManagement.s3.endpoint') }}
            </label>
            <input v-model="form.endpoint" class="input w-full" placeholder="https://s3.amazonaws.com" />
          </div>
          <div>
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.dataManagement.s3.region') }}
            </label>
            <input v-model="form.region" class="input w-full" placeholder="us-east-1" />
          </div>
          <div>
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.dataManagement.s3.bucket') }}
            </label>
            <input v-model="form.bucket" class="input w-full" required />
          </div>
          <div>
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.dataManagement.s3.prefix') }}
            </label>
            <input v-model="form.prefix" class="input w-full" />
          </div>
          <div>
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.dataManagement.s3.accessKeyId') }}
            </label>
            <input v-model="form.access_key_id" class="input w-full" required />
          </div>
          <div>
            <label class="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">
              {{ t('admin.dataManagement.s3.secretAccessKey') }}
            </label>
            <input v-model="form.secret_access_key" type="password" class="input w-full" :placeholder="editing ? t('admin.dataManagement.s3.secretPlaceholder') : ''" />
          </div>
          <div class="flex items-center gap-4 md:col-span-2">
            <label class="inline-flex items-center gap-2">
              <input v-model="form.use_ssl" type="checkbox" class="checkbox" />
              <span class="text-sm">{{ t('admin.dataManagement.s3.useSsl') }}</span>
            </label>
            <label class="inline-flex items-center gap-2">
              <input v-model="form.force_path_style" type="checkbox" class="checkbox" />
              <span class="text-sm">{{ t('admin.dataManagement.s3.forcePathStyle') }}</span>
            </label>
          </div>
        </div>
        <div class="mt-4 flex justify-end gap-2">
          <button type="button" class="btn btn-secondary" @click="closeModal">
            {{ t('common.cancel') }}
          </button>
          <button type="submit" class="btn btn-primary" :disabled="saving">
            {{ saving ? t('common.loading') : t('common.save') }}
          </button>
        </div>
      </form>
    </BaseDialog>
  </div>
</template>
