<script lang="ts" setup>
import { Link, useForm, router } from '@inertiajs/vue3'
import { ref, computed } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'

interface EmailTemplate {
  id: number
  slug: string
  name: string
  subject: string
  body: string
  available_variables: string[]
  is_active: boolean
  updated_at: string
}

interface Props {
  template: EmailTemplate
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const form = useForm({
  subject: props.template.subject,
  body: props.template.body,
  is_active: props.template.is_active,
})

const showPreviewDialog = ref<boolean>(false)
const previewLoading = ref<boolean>(false)
const previewSubject = ref<string>('')
const previewBody = ref<string>('')
const showResetDialog = ref<boolean>(false)

const bodyTextareaRef = ref<InstanceType<typeof VTextarea> | null>(null)

function insertVariable(variable: string): void {
  const placeholder = `{{${variable}}}`

  // Find the textarea element within the VTextarea component
  const textareaEl = document.querySelector('.body-editor textarea') as HTMLTextAreaElement | null

  if (textareaEl) {
    const start = textareaEl.selectionStart
    const end = textareaEl.selectionEnd
    const currentValue = form.body

    form.body = currentValue.substring(0, start) + placeholder + currentValue.substring(end)

    // Set cursor position after inserted variable
    const newPosition = start + placeholder.length
    requestAnimationFrame(() => {
      textareaEl.focus()
      textareaEl.setSelectionRange(newPosition, newPosition)
    })
  }
  else {
    // Fallback: append to end
    form.body += placeholder
  }
}

async function loadPreview(): Promise<void> {
  previewLoading.value = true
  showPreviewDialog.value = true

  try {
    const response = await fetch(`/email-templates/${props.template.id}/preview`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content ?? '',
        'Accept': 'application/json',
      },
    })

    if (response.ok) {
      const data = await response.json()
      previewSubject.value = data.subject
      previewBody.value = data.body
    }
  }
  catch {
    previewSubject.value = 'Preview failed'
    previewBody.value = 'Unable to load preview.'
  }
  finally {
    previewLoading.value = false
  }
}

function confirmReset(): void {
  showResetDialog.value = true
}

function resetToDefault(): void {
  router.post(`/email-templates/${props.template.id}/reset`, {}, {
    preserveScroll: true,
    onSuccess: () => {
      showResetDialog.value = false
    },
  })
}

function submit(): void {
  form.put(`/email-templates/${props.template.id}`, {
    preserveScroll: true,
  })
}

const formattedUpdatedAt = computed<string>(() => {
  const date = new Date(props.template.updated_at)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
})
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="d-flex align-center gap-2 mb-1">
          <Link
            href="/email-templates"
            class="text-decoration-none"
          >
            <VBtn
              icon="tabler-arrow-left"
              variant="text"
              size="small"
            />
          </Link>
          <span class="text-h4 font-weight-bold">Edit Email Template</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Editing "{{ template.name }}"
        </div>
      </div>
    </div>

    <form @submit.prevent="submit">
      <VRow>
        <!-- Main Content -->
        <VCol
          cols="12"
          lg="8"
        >
          <!-- Template Details -->
          <VCard
            title="Template Content"
            class="mb-6"
          >
            <VCardText>
              <VRow>
                <!-- Template Name (read-only) -->
                <VCol cols="12">
                  <div class="d-flex align-center gap-2 mb-4">
                    <span class="text-body-1 font-weight-medium">{{ template.name }}</span>
                    <VChip
                      size="x-small"
                      variant="tonal"
                      color="secondary"
                      class="font-monospace"
                    >
                      {{ template.slug }}
                    </VChip>
                  </div>
                </VCol>

                <!-- Subject -->
                <VCol cols="12">
                  <VTextField
                    v-model="form.subject"
                    label="Email Subject"
                    placeholder="Enter email subject line..."
                    :error-messages="form.errors.subject"
                  />
                </VCol>

                <!-- Body -->
                <VCol cols="12">
                  <VTextarea
                    v-model="form.body"
                    label="Email Body (Markdown)"
                    placeholder="Enter email body content..."
                    :rows="16"
                    :error-messages="form.errors.body"
                    class="body-editor"
                    style="font-family: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace; font-size: 13px;"
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>

          <!-- Available Variables -->
          <VCard
            title="Available Variables"
            class="mb-6"
          >
            <VCardText>
              <p class="text-body-2 text-medium-emphasis mb-4">
                Click a variable to insert it at the cursor position in the body editor. Variables use the format <code v-text="'{{variable_name}}'"></code>.
              </p>
              <div class="d-flex flex-wrap gap-2">
                <VChip
                  v-for="variable in template.available_variables"
                  :key="variable"
                  color="primary"
                  variant="tonal"
                  size="small"
                  class="cursor-pointer font-monospace"
                  @click="insertVariable(variable)"
                >
                  <VIcon
                    icon="tabler-plus"
                    size="14"
                    start
                  />
                  <span v-text="'{{' + variable + '}}'"></span>
                </VChip>
              </div>
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol
          cols="12"
          lg="4"
        >
          <!-- Template Info -->
          <VCard
            title="Template Info"
            class="mb-6"
          >
            <VCardText>
              <div class="d-flex justify-space-between align-center mb-4">
                <span class="text-body-2 text-medium-emphasis">Status</span>
                <VSwitch
                  v-model="form.is_active"
                  :label="form.is_active ? 'Active' : 'Inactive'"
                  color="primary"
                  density="compact"
                  hide-details
                />
              </div>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Last Modified</span>
                <span class="text-body-2">{{ formattedUpdatedAt }}</span>
              </div>
              <div class="d-flex justify-space-between align-center">
                <span class="text-body-2 text-medium-emphasis">Variables</span>
                <span class="text-body-2 font-weight-medium">{{ template.available_variables.length }}</span>
              </div>
            </VCardText>
          </VCard>

          <!-- Preview -->
          <VCard class="mb-6">
            <VCardText>
              <VBtn
                color="info"
                variant="tonal"
                block
                prepend-icon="tabler-eye"
                @click="loadPreview"
              >
                Preview with Sample Data
              </VBtn>
            </VCardText>
          </VCard>

          <!-- Actions -->
          <VCard>
            <VCardText>
              <VBtn
                type="submit"
                color="primary"
                block
                :loading="form.processing"
                :disabled="form.processing"
                prepend-icon="tabler-check"
                class="mb-3"
              >
                Save Changes
              </VBtn>
              <VBtn
                variant="outlined"
                color="warning"
                block
                prepend-icon="tabler-restore"
                class="mb-3"
                @click="confirmReset"
              >
                Reset to Default
              </VBtn>
              <Link
                href="/email-templates"
                class="text-decoration-none"
              >
                <VBtn
                  variant="outlined"
                  block
                >
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>

    <!-- Preview Dialog -->
    <VDialog
      v-model="showPreviewDialog"
      max-width="700"
    >
      <VCard>
        <VCardTitle class="d-flex align-center justify-space-between">
          <span>Email Preview</span>
          <VBtn
            icon="tabler-x"
            variant="text"
            size="small"
            @click="showPreviewDialog = false"
          />
        </VCardTitle>
        <VDivider />
        <VCardText v-if="previewLoading">
          <div class="text-center py-8">
            <VProgressCircular
              indeterminate
              color="primary"
            />
            <div class="text-body-2 text-medium-emphasis mt-2">
              Loading preview...
            </div>
          </div>
        </VCardText>
        <VCardText v-else>
          <div class="mb-4">
            <span class="text-body-2 text-medium-emphasis">Subject:</span>
            <div class="text-body-1 font-weight-medium mt-1">
              {{ previewSubject }}
            </div>
          </div>
          <VDivider class="mb-4" />
          <div>
            <span class="text-body-2 text-medium-emphasis">Body:</span>
            <div
              class="mt-2 pa-4 rounded-lg"
              style="background: rgba(var(--v-theme-on-surface), 0.04); white-space: pre-wrap; font-family: inherit; line-height: 1.6;"
            >
              {{ previewBody }}
            </div>
          </div>
        </VCardText>
      </VCard>
    </VDialog>

    <!-- Reset Confirmation Dialog -->
    <VDialog
      v-model="showResetDialog"
      max-width="450"
    >
      <VCard>
        <VCardTitle>Reset to Default</VCardTitle>
        <VCardText>
          Are you sure you want to reset this template to its default content? This will overwrite your current subject and body text.
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn
            variant="text"
            @click="showResetDialog = false"
          >
            Cancel
          </VBtn>
          <VBtn
            color="warning"
            @click="resetToDefault"
          >
            Reset
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
