<script setup lang="ts">
import {
  DeleteOutlined,
  EditOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue'
import type { PromptRule, PromptRuleGroup } from '@geo/shared-types'
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import { message, type TableColumnsType } from 'ant-design-vue'
import { computed, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'

import PromptRuleModal from '@/components/PromptRuleModal.vue'
import { promptRulesApi } from '@/lib/api'
import { formatDateTime } from '@/lib/display'
import { formatError } from '@/lib/errors'
import { useCompanyStore } from '@/stores/company'

const queryClient = useQueryClient()
const { t } = useI18n()
const companyStore = useCompanyStore()

const selectedGroupId = ref<number | 'all' | 'ungrouped'>('all')
const ruleModalOpen = ref(false)
const editingRule = ref<PromptRule | null>(null)
const groupModalOpen = ref(false)
const editingGroupId = ref<number | null>(null)
const groupForm = reactive({ name: '' })
const page = ref(1)
const pageSize = ref(20)

const groupsQuery = useQuery({
  queryKey: computed(() => ['promptRules', 'groups', companyStore.currentBrandId]),
  enabled: computed(() => Boolean(companyStore.currentBrandId)),
  queryFn: () => promptRulesApi.listGroups(),
})

const ruleListParams = computed(() => {
  const params: Record<string, unknown> = {
    page: page.value,
    page_size: pageSize.value,
  }
  if (selectedGroupId.value === 'ungrouped') {
    params.ungrouped = true
  } else if (selectedGroupId.value !== 'all') {
    params.group_id = selectedGroupId.value
  }
  return params
})

const rulesQuery = useQuery({
  queryKey: computed(() => [
    'promptRules',
    'list',
    companyStore.currentBrandId,
    ruleListParams.value,
  ]),
  enabled: computed(() => Boolean(companyStore.currentBrandId)),
  queryFn: () => promptRulesApi.list(ruleListParams.value),
})

const columns = computed<TableColumnsType<PromptRule>>(() => [
  { title: t('custom.promptRule.name'), dataIndex: 'name', key: 'name', width: 160 },
  {
    title: t('custom.promptRule.content'),
    dataIndex: 'prompt_content',
    key: 'prompt_content',
    ellipsis: true,
  },
  { title: t('custom.promptRule.scene'), dataIndex: 'scene', key: 'scene', width: 120 },
  {
    title: t('custom.promptRule.tone'),
    dataIndex: 'default_tone',
    key: 'default_tone',
    width: 100,
  },
  {
    title: t('custom.promptRule.wordCount'),
    dataIndex: 'default_word_count',
    key: 'default_word_count',
    width: 100,
  },
  {
    title: t('custom.promptRule.articleCount'),
    dataIndex: 'article_count',
    key: 'article_count',
    width: 100,
  },
  { title: t('custom.promptRule.status'), dataIndex: 'status', key: 'status', width: 100 },
  { title: t('common.createdAt'), dataIndex: 'created_at', key: 'created_at', width: 168 },
  { title: t('common.actions'), key: 'actions', width: 140, fixed: 'right', align: 'right' },
])

const groupMutations = {
  create: useMutation({
    mutationFn: () => promptRulesApi.createGroup({ name: groupForm.name.trim() }),
    onSuccess: async () => {
      message.success(t('custom.messages.groupCreated'))
      groupModalOpen.value = false
      await queryClient.invalidateQueries({ queryKey: ['promptRules', 'groups'] })
    },
    onError: (error) => message.error(formatError(error)),
  }),
  update: useMutation({
    mutationFn: () =>
      promptRulesApi.updateGroup(editingGroupId.value as number, { name: groupForm.name.trim() }),
    onSuccess: async () => {
      message.success(t('custom.messages.groupUpdated'))
      groupModalOpen.value = false
      await queryClient.invalidateQueries({ queryKey: ['promptRules', 'groups'] })
    },
    onError: (error) => message.error(formatError(error)),
  }),
  remove: useMutation({
    mutationFn: (id: number) => promptRulesApi.removeGroup(id),
    onSuccess: async () => {
      message.success(t('custom.messages.groupDeleted'))
      if (selectedGroupId.value === editingGroupId.value) {
        selectedGroupId.value = 'all'
      }
      await queryClient.invalidateQueries({ queryKey: ['promptRules'] })
    },
    onError: (error) => message.error(formatError(error)),
  }),
}

const ruleMutations = {
  remove: useMutation({
    mutationFn: (id: number) => promptRulesApi.remove(id),
    onSuccess: async () => {
      message.success(t('custom.messages.ruleDeleted'))
      await queryClient.invalidateQueries({ queryKey: ['promptRules'] })
    },
    onError: (error) => message.error(formatError(error)),
  }),
  toggleStatus: useMutation({
    mutationFn: ({ id, status }: { id: number; status: 'enabled' | 'disabled' }) =>
      promptRulesApi.toggleStatus(id, { status }),
    onSuccess: async (_data, variables) => {
      message.success(
        variables.status === 'enabled'
          ? t('custom.messages.ruleEnabled')
          : t('custom.messages.ruleDisabled'),
      )
      await queryClient.invalidateQueries({ queryKey: ['promptRules'] })
    },
    onError: (error) => message.error(formatError(error)),
  }),
}

function openGroupModal(group?: PromptRuleGroup): void {
  editingGroupId.value = group?.id ?? null
  groupForm.name = group?.name ?? ''
  groupModalOpen.value = true
}

async function submitGroup(): Promise<void> {
  if (!groupForm.name.trim()) return
  if (editingGroupId.value) {
    await groupMutations.update.mutateAsync()
  } else {
    await groupMutations.create.mutateAsync()
  }
}

function openRuleModal(rule?: PromptRule): void {
  editingRule.value = rule ?? null
  ruleModalOpen.value = true
}

function handleTableChange(nextPage: number, nextPageSize: number): void {
  page.value = nextPage
  pageSize.value = nextPageSize
}

watch(selectedGroupId, () => {
  page.value = 1
})

watch(
  () => companyStore.currentBrandId,
  () => {
    selectedGroupId.value = 'all'
    editingRule.value = null
    ruleModalOpen.value = false
    groupModalOpen.value = false
    page.value = 1
  },
)
</script>

<template>
  <div class="prompt-rule-tab">
    <div class="prompt-rule-tab__layout">
      <!-- Group sidebar -->
      <aside class="prompt-rule-tab__sidebar">
        <div class="prompt-rule-tab__sidebar-head">
          <h4>{{ t('custom.group.title') }}</h4>
          <a-button type="text" size="small" @click="openGroupModal()">
            <template #icon><PlusOutlined /></template>
          </a-button>
        </div>

        <div class="prompt-rule-tab__group-list">
          <div
            class="prompt-rule-tab__group-item"
            :class="{ 'prompt-rule-tab__group-item--active': selectedGroupId === 'all' }"
            @click="selectedGroupId = 'all'"
          >
            <span>{{ t('custom.group.allRules') }}</span>
          </div>

          <div
            v-for="group in groupsQuery.data.value ?? []"
            :key="group.id"
            class="prompt-rule-tab__group-item"
            :class="{ 'prompt-rule-tab__group-item--active': selectedGroupId === group.id }"
            @click="selectedGroupId = group.id"
          >
            <span>{{ group.name }}</span>
            <span class="prompt-rule-tab__group-actions">
              <a-button type="text" size="small" @click.stop="openGroupModal(group)">
                <template #icon><EditOutlined /></template>
              </a-button>
              <a-popconfirm
                :title="t('custom.group.deleteConfirm')"
                @confirm="groupMutations.remove.mutate(group.id)"
              >
                <a-button type="text" size="small" danger @click.stop>
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-popconfirm>
            </span>
          </div>

          <div
            class="prompt-rule-tab__group-item"
            :class="{ 'prompt-rule-tab__group-item--active': selectedGroupId === 'ungrouped' }"
            @click="selectedGroupId = 'ungrouped'"
          >
            <span>{{ t('custom.promptRule.ungrouped') }}</span>
          </div>
        </div>
      </aside>

      <!-- Rule list panel -->
      <div class="prompt-rule-tab__panel">
        <div class="prompt-rule-tab__panel-head">
          <span class="prompt-rule-tab__count">
            {{ t('templates.list.count', { count: rulesQuery.data.value?.total ?? 0 }) }}
          </span>
          <a-button type="primary" @click="openRuleModal()">
            <template #icon><PlusOutlined /></template>
            {{ t('common.create') }}
          </a-button>
        </div>

        <a-table
          :columns="columns"
          :data-source="rulesQuery.data.value?.items ?? []"
          :loading="rulesQuery.isPending.value"
          :pagination="{
            current: page,
            pageSize,
            total: rulesQuery.data.value?.total ?? 0,
            showSizeChanger: true,
          }"
          row-key="id"
          size="small"
          :scroll="{ x: 1100 }"
          @change="(p: any) => handleTableChange(p.current, p.pageSize)"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'prompt_content'">
              <span class="prompt-rule-tab__content-cell">{{ record.prompt_content }}</span>
            </template>
            <template v-else-if="column.key === 'scene'">
              {{ record.scene || '--' }}
            </template>
            <template v-else-if="column.key === 'default_tone'">
              {{ record.default_tone || '--' }}
            </template>
            <template v-else-if="column.key === 'default_word_count'">
              {{ record.default_word_count || '--' }}
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="record.status === 'enabled' ? 'green' : 'default'">
                {{
                  record.status === 'enabled'
                    ? t('custom.promptRule.enabled')
                    : t('custom.promptRule.disabled')
                }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'created_at'">
              {{ formatDateTime(record.created_at) }}
            </template>
            <template v-else-if="column.key === 'actions'">
              <div class="table-actions-row">
                <a-tooltip :title="t('common.edit')">
                  <a-button
                    type="text"
                    shape="circle"
                    size="small"
                    class="action-btn action-edit"
                    @click="openRuleModal(record)"
                  >
                    <EditOutlined />
                  </a-button>
                </a-tooltip>
                <a-tooltip
                  :title="
                    record.status === 'enabled'
                      ? t('custom.promptRule.disabled')
                      : t('custom.promptRule.enabled')
                  "
                >
                  <a-button
                    type="text"
                    shape="circle"
                    size="small"
                    :class="[
                      'action-btn',
                      record.status === 'enabled' ? 'action-disable' : 'action-enable',
                    ]"
                    @click="
                      ruleMutations.toggleStatus.mutate({
                        id: record.id,
                        status: record.status === 'enabled' ? 'disabled' : 'enabled',
                      })
                    "
                  >
                    <PauseCircleOutlined v-if="record.status === 'enabled'" />
                    <PlayCircleOutlined v-else />
                  </a-button>
                </a-tooltip>
                <a-popconfirm
                  :title="t('custom.promptRule.deleteConfirm')"
                  @confirm="ruleMutations.remove.mutate(record.id)"
                >
                  <a-button
                    type="text"
                    shape="circle"
                    size="small"
                    class="action-btn action-delete"
                    :title="t('common.delete')"
                  >
                    <DeleteOutlined />
                  </a-button>
                </a-popconfirm>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- Group modal -->
    <a-modal
      :open="groupModalOpen"
      :title="editingGroupId ? t('custom.group.editTitle') : t('custom.group.createTitle')"
      :confirm-loading="
        groupMutations.create.isPending.value || groupMutations.update.isPending.value
      "
      @ok="submitGroup"
      @cancel="groupModalOpen = false"
    >
      <a-form layout="vertical" style="padding-top: 8px">
        <a-form-item :label="t('custom.group.name')" required>
          <a-input v-model:value="groupForm.name" :maxlength="50" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- Rule modal -->
    <PromptRuleModal v-model:open="ruleModalOpen" :rule="editingRule" />
  </div>
</template>

<style scoped>
.prompt-rule-tab__layout {
  display: grid;
  grid-template-columns: 240px minmax(0, 1fr);
  gap: 20px;
}

.prompt-rule-tab__sidebar {
  background: #f8fafc;
  border: 1px solid #e6edf5;
  border-radius: 12px;
  padding: 16px;
}

.prompt-rule-tab__sidebar-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.prompt-rule-tab__sidebar-head h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.prompt-rule-tab__group-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.prompt-rule-tab__group-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 13px;
  border: 1px solid transparent;
  transition:
    background 0.2s,
    border-color 0.2s;
}

.prompt-rule-tab__group-item:hover {
  background: #f0f5ff;
}

.prompt-rule-tab__group-item--active {
  border-color: #bfd7ff;
  background: #eef5ff;
}

.prompt-rule-tab__group-actions {
  display: flex;
  gap: 2px;
  opacity: 0;
  transition: opacity 0.15s;
}

.prompt-rule-tab__group-item:hover .prompt-rule-tab__group-actions {
  opacity: 1;
}

.prompt-rule-tab__panel-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.prompt-rule-tab__count {
  font-size: 13px;
  color: #8c8c8c;
}

.prompt-rule-tab__content-cell {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  font-size: 12px;
  color: #595959;
}

@media (max-width: 720px) {
  .prompt-rule-tab__layout {
    grid-template-columns: 1fr;
  }
}
</style>
