<script setup>
import { ref, watch, computed, onMounted } from "vue";
import { languages } from "@/utils/languageCode";
import ReusableModal from "@/components/ReusableModal.vue";
import { useSettingStore } from "@/stores/settingStore";
import { useAuthStore } from "@/stores/authStore";
import { storeToRefs } from "pinia";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  entityType: {
    type: String,
    required: true,
    validator: (value) =>
      ["testimonials", "activities", "teachers", "programs"].includes(value),
  },
  selectedCount: {
    type: Number,
    default: 0,
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:visible", "translate", "cancel"]);

const settingStore = useSettingStore();
const authStore = useAuthStore();
const { setting } = storeToRefs(settingStore);
const { user } = storeToRefs(authStore);

const selectedLanguage = ref(null);
const translationMethod = ref("openAI");

onMounted(() => {
  if (!setting.value) {
    settingStore.getSetting();
  }
});

// Translation method options
const methodOptions = [
  { label: "OpenAI", value: "openAI" },
  { label: "Manual", value: "manually" },
];

// Computed title based on entity type
const modalTitle = computed(() => {
  const titles = {
    testimonials: "Translate Testimonials",
    activities: "Translate Activities",
    teachers: "Translate Teachers",
    programs: "Translate Programs",
  };
  return titles[props.entityType] || "Translate";
});

const configuredLanguageCode = computed(
  () => setting.value?.general_settings?.language_code || "en",
);
const configuredLanguageName = computed(
  () => setting.value?.general_settings?.language_name || "English",
);

const isSuperAdmin = computed(() => {
  return (
    user.value?.role === "super_admin" ||
    user.value?.data?.role === "super_admin"
  );
});

const isLanguageConfigured = computed(
  () => configuredLanguageCode.value !== "en",
);

// Filter available languages: Show only the configured language for franchisees, but all for super_admin
const availableLanguages = computed(() => {
  if (isSuperAdmin.value) {
    return languages;
  }

  if (!isLanguageConfigured.value) return [];

  return [
    {
      name: configuredLanguageName.value,
      code: configuredLanguageCode.value,
    },
  ];
});

// Computed label based on entity type
const entityLabel = computed(() => {
  const labels = {
    testimonials: "Testimonials to translate",
    activities: "Activities to translate",
    teachers: "Teachers to translate",
    programs: "Programs to translate",
  };
  return labels[props.entityType] || "Items to translate";
});

// Watch for modal visibility changes
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      selectedLanguage.value = null;
      translationMethod.value = "openAI";
    }
  },
);

const handleTranslate = () => {
  if (!selectedLanguage.value) return;

  // Emit payload with selected language and method for translation
  const selectedLangObj = languages.find(
    (l) => l.code === selectedLanguage.value,
  );
  emit("translate", {
    type: props.entityType,
    language: selectedLangObj?.name || selectedLanguage.value,
    "language-code": selectedLanguage.value,
    method: translationMethod.value,
  });
};

const handleCancel = () => {
  selectedLanguage.value = null;
  translationMethod.value = "openAI";
  emit("cancel");
  emit("update:visible", false);
};

const handleClose = () => {
  handleCancel();
};
</script>

<template>
  <ReusableModal
    :visible="visible"
    @update:visible="(val) => emit('update:visible', val)"
    :title="modalTitle"
    :fields="[]"
    :loading="loading"
    :submitDisabled="!selectedLanguage"
    :submitLabel="
      translationMethod === 'openAI'
        ? 'Translate with AI'
        : 'Create Manual Translation'
    "
    cancelLabel="Cancel"
    persistent
    @submit="handleTranslate"
    @cancel="handleClose"
    class="translation-modal"
  >
    <template #custom-content>
      <div class="translation-content">
        <div class="form-info mb-4">
          <p class="mb-0">
            <strong>{{ entityLabel }}:</strong>
            <span class="count-badge">{{ selectedCount }}</span>
          </p>
        </div>

        <!-- Translation Method Selection -->
        <div class="field mb-4">
          <label for="method" class="field-label">Translation Method:</label>
          <v-select
            v-model="translationMethod"
            :items="methodOptions"
            item-title="label"
            item-value="value"
            placeholder="Select method..."
            variant="outlined"
            density="comfortable"
            class="w-full method-dropdown"
            :disabled="loading"
            :menu-props="{ offsetY: true, location: 'bottom', maxHeight: 150 }"
          />
        </div>

        <!-- Language Selection -->
        <div class="field">
          <label for="language" class="field-label"
            >Select target language:</label
          >

          <template v-if="isLanguageConfigured || isSuperAdmin">
            <v-select
              v-model="selectedLanguage"
              :items="availableLanguages"
              item-title="name"
              item-value="code"
              placeholder="Choose a language..."
              variant="outlined"
              density="comfortable"
              class="w-full translation-dropdown"
              :disabled="loading"
              :menu-props="{
                offsetY: true,
                location: 'bottom',
                maxHeight: 220,
              }"
              show-clear
            >
              <template #option="{ item }">
                <div class="language-option">
                  <span class="language-name">{{ item.name }}</span>
                  <span class="language-code">({{ item.code }})</span>
                </div>
              </template>
            </v-select>
            <small class="help-text">
              Select a language to translate the selected {{ entityType }}
            </small>
          </template>

          <template v-else>
            <div class="no-language-warning">
              <i class="pi pi-exclamation-triangle mr-2"></i>
              <span
                >No additional language configured. Please select any language
                from
                <router-link to="/account-settings" class="settings-link"
                  >setting page</router-link
                >
                to enable translation.</span
              >
            </div>
          </template>
        </div>
      </div>
    </template>
  </ReusableModal>
</template>

<style scoped>
.translation-modal {
  width: 100%;
  max-width: 450px;
}

.translation-content {
  padding: 0.5rem 0;
}

.form-info {
  background: rgba(var(--v-theme-on-surface), 0.03);
  padding: 1rem;
  border-radius: 8px;
  border-left: 4px solid rgb(var(--v-theme-primary));
}

.form-info p {
  margin: 0;
  color: rgb(var(--v-theme-on-surface), 0.8);
  line-height: 1.5;
}

.count-badge {
  background: rgb(var(--v-theme-primary));
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-weight: 600;
  font-size: 0.875rem;
  margin-left: 0.5rem;
}

.field-label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
  color: rgb(var(--v-theme-on-surface));
  font-size: 0.9rem;
}

.help-text {
  color: rgb(var(--v-theme-on-surface), 0.6);
  margin-top: 0.5rem;
  display: block;
}

.no-language-warning {
  background: rgba(var(--v-theme-warning), 0.1);
  border: 1px solid rgba(var(--v-theme-warning), 0.3);
  border-radius: 8px;
  padding: 1rem;
  color: rgb(var(--v-theme-warning));
  font-size: 0.9rem;
  display: flex;
  align-items: flex-start;
}

.no-language-warning i {
  color: #d97706;
  font-size: 1.1rem;
  margin-top: 0.1rem;
}

.settings-link {
  color: #2563eb;
  font-weight: 600;
  text-decoration: underline;
  cursor: pointer;
}

.settings-link:hover {
  color: #1d4ed8;
}

:deep(.translation-dropdown),
:deep(.method-dropdown) {
  min-height: 42px;
}

:deep(.translation-dropdown .p-dropdown-label),
:deep(.method-dropdown .p-dropdown-label) {
  padding: 0.75rem;
}

.language-option {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.language-name {
  font-weight: 500;
}

.language-code {
  color: #9ca3af;
  font-size: 0.875rem;
}
</style>
