<template>
  <el-drawer
    :model-value="modelValue"
    :title="isEdit ? `編輯實驗 — ${props.experiment?.name || ''}` : '新增實驗'"
    size="680px"
    direction="rtl"
    :close-on-click-modal="false"
    :before-close="handleClose"
    @closed="resetForm"
  >
    <div class="form-body">

      <!-- 基礎設定 -->
      <div class="section">
        <p class="section__title">基礎設定</p>

        <div v-if="!isEdit" class="field">
          <label class="field__label">所屬網站 <span class="field__required">*</span></label>
          <el-select
            v-model="form.site_id"
            placeholder="選擇網站"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="site in sites"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
          <p v-if="validErrors.site_id" class="field__error">{{ validErrors.site_id }}</p>
        </div>

        <div class="field">
          <label class="field__label">實驗名稱 <span class="field__required">*</span></label>
          <el-input v-model="form.name" placeholder="例：首頁主視覺 A/B 測試" />
          <p v-if="validErrors.name" class="field__error">{{ validErrors.name }}</p>
        </div>

        <div class="field">
          <label class="field__label">狀態</label>
          <div class="status-pills">
            <button
              v-for="opt in statusOptions"
              :key="opt.value"
              class="status-pill"
              :class="{ 'status-pill--active': form.status === opt.value, [`status-pill--${opt.value}`]: true }"
              @click="form.status = opt.value"
              type="button"
            >
              {{ opt.label }}
            </button>
          </div>
        </div>

        <div class="field-row">
          <div class="field">
            <label class="field__label">開始時間</label>
            <el-date-picker
              v-model="form.start_at"
              type="datetime"
              placeholder="選擇開始時間"
              style="width: 100%"
            />
          </div>
          <div class="field">
            <label class="field__label">結束時間</label>
            <el-date-picker
              v-model="form.end_at"
              type="datetime"
              placeholder="選擇結束時間"
              style="width: 100%"
            />
          </div>
        </div>
      </div>

      <!-- 啟用條件 -->
      <div class="section">
        <p class="section__title">啟用條件</p>
        <p class="section__desc">設定這個實驗要套用在哪些頁面網址。實驗只會在符合條件的頁面上執行。</p>

        <div class="field">
          <label class="field__label">實驗頁面網址</label>
          <el-input
            v-model="form.base_url"
            placeholder="例：https://www.example.com/products/page"
            clearable
          />
          <p class="field__hint">這個網址也會作為視覺編輯器的預設載入頁面。</p>
        </div>

        <!-- URL rules -->
        <div class="field">
          <label class="field__label">網址規則</label>

          <div class="rules-box">
            <template v-if="form.url_rules.length === 0">
              <p class="rules-empty">尚未設定規則 — 實驗將只依據上方網址判斷，或套用到所有頁面。</p>
            </template>

            <template v-else>
              <div
                v-for="(rule, idx) in form.url_rules"
                :key="rule._id"
                class="rule-row-wrap"
              >
                <div class="rule-connector">
                  <span class="rule-connector__badge">{{ idx === 0 ? '當' : '且' }}</span>
                </div>
                <div class="rule-row">
                  <el-select v-model="rule.operator" style="width: 160px; flex-shrink: 0">
                    <el-option
                      v-for="op in urlRuleOperators"
                      :key="op.value"
                      :label="op.label"
                      :value="op.value"
                    />
                  </el-select>
                  <el-input
                    v-model="rule.value"
                    placeholder="輸入網址或關鍵字"
                    style="flex: 1"
                    clearable
                  />
                  <button class="rule-delete" @click="removeRule(idx)" type="button" title="刪除此規則">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/>
                    </svg>
                  </button>
                </div>
              </div>
            </template>

            <button class="add-rule-btn" @click="addRule" type="button">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
              新增網址規則
            </button>
          </div>
        </div>

        <!-- URL tester -->
        <div class="field">
          <label class="field__label">規則測試</label>
          <div class="url-tester">
            <el-input
              v-model="testUrl"
              placeholder="輸入網址來測試規則是否符合"
              clearable
              style="flex: 1"
            />
            <el-button @click="runUrlTest" type="button">檢查</el-button>
          </div>
          <div v-if="testResult !== null" class="test-result" :class="testResult ? 'test-result--pass' : 'test-result--fail'">
            {{ testResult ? '✓ 符合規則，實驗將套用到此網址' : '✗ 不符合規則，實驗不會套用到此網址' }}
          </div>
        </div>
      </div>

      <!-- 進階設定 -->
      <div class="section">
        <p class="section__title">進階設定</p>

        <div class="field">
          <label class="field__label">實驗裝置限制</label>
          <p class="field__hint">選擇要讓哪些裝置的訪客參與這個實驗。不選則代表全裝置。</p>
          <div class="device-pills">
            <button
              v-for="d in deviceOptions"
              :key="d.value"
              class="device-pill"
              :class="{ 'device-pill--active': form.device_targets.includes(d.value) }"
              @click="toggleDevice(d.value)"
              type="button"
            >
              <svg v-if="form.device_targets.includes(d.value)" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>
              {{ d.label }}
            </button>
          </div>
        </div>

        <div class="field">
          <label class="checkbox-row">
            <input type="checkbox" v-model="form.hide_hashtag" class="checkbox-input" />
            <span class="checkbox-label">隱藏網址片段（hashtag）</span>
          </label>
          <p class="field__hint">啟用後，當訪客進入實驗頁面時，系統會自動移除網址的 # 片段。</p>
        </div>
      </div>

    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submit">
          {{ isEdit ? "儲存變更" : "建立實驗" }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { computed, ref, watch } from "vue"
import { ElMessage } from "element-plus"
import fastapiClient from "@/services/api/fastapi-client"
import experimentApi from "@/module/experiment/service/experiment-api"

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  experiment: { type: Object, default: null },
})

const emit = defineEmits(["update:modelValue", "saved"])

const isEdit = computed(() => Boolean(props.experiment?.id))

const saving = ref(false)
const sites = ref([])
const validErrors = ref({})
const testUrl = ref("")
const testResult = ref(null)

const statusOptions = [
  { value: "draft", label: "草稿" },
  { value: "running", label: "進行中" },
  { value: "paused", label: "暫停" },
  { value: "ended", label: "已結束" },
]

const urlRuleOperators = [
  { value: "contains", label: "完整網址包含" },
  { value: "equals", label: "完整網址等於" },
  { value: "starts_with", label: "網址開頭為" },
  { value: "regex", label: "符合正規表達式" },
]

const deviceOptions = [
  { value: "mobile", label: "手機" },
  { value: "tablet", label: "平板" },
  { value: "desktop", label: "桌機" },
]

const defaultForm = () => ({
  site_id: "",
  name: "",
  status: "draft",
  start_at: null,
  end_at: null,
  base_url: "",
  url_rules: [],
  device_targets: [],
  hide_hashtag: false,
})

const form = ref(defaultForm())


const addRule = () => {
  form.value.url_rules.push({ _id: Date.now(), operator: "contains", value: "" })
}

const removeRule = (idx) => {
  form.value.url_rules.splice(idx, 1)
  testResult.value = null
}

const toggleDevice = (value) => {
  const idx = form.value.device_targets.indexOf(value)
  if (idx === -1) form.value.device_targets.push(value)
  else form.value.device_targets.splice(idx, 1)
}

const runUrlTest = () => {
  if (!testUrl.value.trim()) return
  if (form.value.url_rules.length === 0) {
    testResult.value = true
    return
  }
  testResult.value = form.value.url_rules.every(rule => {
    const url = testUrl.value
    const val = rule.value
    switch (rule.operator) {
      case "contains": return url.includes(val)
      case "equals": return url === val
      case "starts_with": return url.startsWith(val)
      case "regex": try { return new RegExp(val).test(url) } catch { return false }
      default: return false
    }
  })
}

const loadSites = async () => {
  try {
    const response = await fastapiClient.request("/api/admin/sites")
    sites.value = response.items || []
  } catch {
    sites.value = []
  }
}

watch(
  () => props.modelValue,
  (open) => {
    if (!open) return
    if (!isEdit.value) loadSites()

    if (props.experiment) {
      const tc = props.experiment.targetingConfig || props.experiment.targeting_config || {}
      form.value = {
        site_id: props.experiment.siteId || props.experiment.site_id || "",
        name: props.experiment.name || "",
        status: props.experiment.status || "draft",
        start_at: props.experiment.startAt || props.experiment.start_at || null,
        end_at: props.experiment.endAt || props.experiment.end_at || null,
        base_url: tc.base_url || "",
        url_rules: (tc.url_rules || []).map((r, i) => ({ ...r, _id: i })),
        device_targets: tc.device_targets || [],
        hide_hashtag: tc.hide_hashtag || false,
      }
    } else {
      form.value = defaultForm()
    }
    validErrors.value = {}
    testResult.value = null
  }
)

const resetForm = () => {
  form.value = defaultForm()
  validErrors.value = {}
  testResult.value = null
}

const handleClose = () => {
  emit("update:modelValue", false)
}

const validate = () => {
  const errs = {}
  if (!isEdit.value && !form.value.site_id) errs.site_id = "請選擇所屬網站"
  if (!form.value.name.trim()) errs.name = "請填入實驗名稱"
  validErrors.value = errs
  return Object.keys(errs).length === 0
}

const buildTargetingConfig = () => {
  const config = {}
  if (form.value.base_url.trim()) config.base_url = form.value.base_url.trim()
  const cleanRules = form.value.url_rules
    .filter(r => r.value.trim())
    .map(({ operator, value }) => ({ operator, value }))
  if (cleanRules.length > 0) config.url_rules = cleanRules
  if (form.value.device_targets.length > 0) config.device_targets = form.value.device_targets
  if (form.value.hide_hashtag) config.hide_hashtag = true
  return Object.keys(config).length > 0 ? config : null
}

const submit = async () => {
  if (!validate()) return

  saving.value = true
  try {
    const targeting_config = buildTargetingConfig()
    const payload = {
      name: form.value.name.trim(),
      module_type: "visual",
      status: form.value.status,
      start_at: form.value.start_at || null,
      end_at: form.value.end_at || null,
      targeting_config,
    }

    let result
    if (isEdit.value) {
      result = await experimentApi.updateExperiment(props.experiment.id, payload)
    } else {
      result = await experimentApi.createExperiment({
        ...payload,
        site_id: form.value.site_id,
      })
    }

    ElMessage.success(isEdit.value ? "實驗已更新" : "實驗已建立")
    emit("update:modelValue", false)
    emit("saved", result)
  } catch (error) {
    ElMessage.error(error?.message || "操作失敗，請稍後再試")
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.form-body {
  display: flex;
  flex-direction: column;
  gap: 0;
  padding-bottom: 24px;
}

/* Section */
.section {
  padding: 24px 0;
  border-bottom: 1px solid #f1f5f9;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.section:last-child {
  border-bottom: none;
}

.section__title {
  margin: 0;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  color: #2563eb;
}

.section__desc {
  margin: -10px 0 0;
  font-size: 13px;
  color: #64748b;
  line-height: 1.6;
}

/* Fields */
.field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.field__label {
  font-size: 13px;
  font-weight: 600;
  color: #374151;
}

.field__required {
  color: #e11d48;
}

.field__hint {
  margin: 0;
  font-size: 12px;
  color: #94a3b8;
  line-height: 1.6;
}

.field__error {
  margin: 0;
  font-size: 12px;
  color: #e11d48;
}

.field-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

/* Status pills */
.status-pills {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.status-pill {
  padding: 6px 16px;
  border-radius: 20px;
  border: 1.5px solid #e2e8f0;
  background: #f8fafc;
  font-size: 13px;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  transition: all 0.12s;
}

.status-pill--active.status-pill--draft { background: #fef9c3; border-color: #fde047; color: #854d0e; }
.status-pill--active.status-pill--running { background: #dcfce7; border-color: #86efac; color: #15803d; }
.status-pill--active.status-pill--paused { background: #e0f2fe; border-color: #7dd3fc; color: #075985; }
.status-pill--active.status-pill--ended { background: #ffe4e6; border-color: #fca5a5; color: #9f1239; }

/* URL rules */
.rules-box {
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 16px;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.rules-empty {
  font-size: 13px;
  color: #94a3b8;
  margin: 0 0 8px;
  text-align: center;
  padding: 8px 0;
}

.rule-row-wrap {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.rule-connector {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-left: 2px;
}

.rule-connector__badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 28px;
  padding: 3px 8px;
  border-radius: 6px;
  background: #2563eb;
  color: #fff;
  font-size: 11px;
  font-weight: 700;
}

.rule-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rule-delete {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: #fff;
  color: #94a3b8;
  cursor: pointer;
  flex-shrink: 0;
  transition: color 0.1s, border-color 0.1s;
}

.rule-delete:hover {
  color: #e11d48;
  border-color: #fca5a5;
}

.add-rule-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 10px;
  border: 1px dashed #cbd5e1;
  border-radius: 8px;
  background: transparent;
  color: #2563eb;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.1s;
  align-self: flex-start;
  margin-top: 4px;
}

.add-rule-btn:hover {
  background: #eff6ff;
}

/* URL tester */
.url-tester {
  display: flex;
  gap: 8px;
}

.test-result {
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
}

.test-result--pass {
  background: #dcfce7;
  color: #15803d;
}

.test-result--fail {
  background: #ffe4e6;
  color: #9f1239;
}

/* Device pills */
.device-pills {
  display: flex;
  gap: 8px;
}

.device-pill {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 7px 16px;
  border: 1.5px solid #e2e8f0;
  border-radius: 20px;
  background: #f8fafc;
  font-size: 13px;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  transition: all 0.12s;
}

.device-pill--active {
  background: #eff6ff;
  border-color: #93c5fd;
  color: #1d4ed8;
}

/* Checkbox */
.checkbox-row {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.checkbox-input {
  width: 16px;
  height: 16px;
  accent-color: #2563eb;
  cursor: pointer;
}

.checkbox-label {
  font-size: 13.5px;
  font-weight: 500;
  color: #374151;
}

/* Footer */
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 20px;
  border-top: 1px solid #e2e8f0;
}
</style>
