import { computed, ref } from 'vue'
import type { ComputedRef, Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  deleteDatasetRecord,
  updateDatasetRecord,
} from '../datasetRecords'
import type { DatasetRecord } from '../datasetRecords'
import type { DatasetFile } from '@/types'
import type { EditField } from './types'

export function useDatasetRecordEditor(
  selectedFile: ComputedRef<DatasetFile | undefined>,
  isViewingActiveVersion: ComputedRef<boolean>,
  previewContent: Ref<string>,
) {
  const editorVisible = ref(false)
  const editingRecord = ref<DatasetRecord | null>(null)
  const editFields = ref<EditField[]>([])
  const rawDraft = ref('')
  const originalDraft = ref('')
  const savingRecord = ref(false)
  const currentDraft = computed(() => editingRecord.value?.kind === 'object'
    ? JSON.stringify(editFields.value)
    : rawDraft.value)
  const hasEditorDraftChanges = computed(
    () => editorVisible.value && currentDraft.value !== originalDraft.value,
  )

  function resetRecordEditor() {
    editorVisible.value = false
    editingRecord.value = null
    editFields.value = []
    rawDraft.value = ''
    originalDraft.value = ''
  }

  function openRecordEditor(record: DatasetRecord) {
    if (!isViewingActiveVersion.value) {
      ElMessage.warning('历史版本为只读，请先设为当前版本')
      return
    }
    editingRecord.value = record
    if (record.kind === 'object') {
      editFields.value = Object.entries(record.value as Record<string, unknown>).map(
        ([key, value]) => ({
          key,
          value: typeof value === 'string' ? value : JSON.stringify(value, null, 2),
          isJson: typeof value !== 'string',
        }),
      )
      rawDraft.value = ''
    } else {
      editFields.value = []
      rawDraft.value = record.raw
    }
    editorVisible.value = true
    originalDraft.value = record.kind === 'object'
      ? JSON.stringify(editFields.value)
      : rawDraft.value
  }

  function updateEditField(index: number, value: string) {
    const field = editFields.value[index]
    if (field) field.value = value
  }

  async function confirmEditorDiscardChanges() {
    if (!hasEditorDraftChanges.value) return true
    try {
      await ElMessageBox.confirm(
        '当前样本存在未暂存修改，放弃后将无法恢复。',
        '确认放弃修改？',
        {
          type: 'warning',
          confirmButtonText: '放弃修改',
          cancelButtonText: '继续编辑',
        },
      )
      return true
    } catch {
      return false
    }
  }

  async function closeRecordEditor(done?: () => void) {
    if (savingRecord.value || !await confirmEditorDiscardChanges()) return
    resetRecordEditor()
    done?.()
  }

  function buildNextRecordValue() {
    if (editingRecord.value?.kind !== 'object') return JSON.parse(rawDraft.value)
    const nextValue: Record<string, unknown> = {}
    for (const field of editFields.value) {
      nextValue[field.key] = field.isJson ? JSON.parse(field.value) : field.value
    }
    return nextValue
  }

  async function saveRecord() {
    if (!selectedFile.value || !editingRecord.value || savingRecord.value) return
    const record = editingRecord.value
    let nextValue: unknown
    try {
      nextValue = buildNextRecordValue()
    } catch (error) {
      ElMessage.error(`JSON 格式校验失败：${error instanceof Error ? error.message : '内容格式不正确'}`)
      return
    }

    savingRecord.value = true
    try {
      previewContent.value = updateDatasetRecord(
        previewContent.value,
        selectedFile.value.name,
        record.sourceIndex,
        nextValue,
      )
      resetRecordEditor()
      ElMessage.success(`第 ${record.displayIndex} 条修改已暂存`)
    } finally {
      savingRecord.value = false
    }
  }

  async function deleteRecord(record: DatasetRecord) {
    if (!selectedFile.value || !isViewingActiveVersion.value) {
      ElMessage.warning('历史版本为只读，请先设为当前版本')
      return
    }
    try {
      await ElMessageBox.confirm(
        '删除后将暂存到当前草稿，点击“保存版本”后正式生效。',
        `删除第 ${record.displayIndex} 条数据？`,
        {
          type: 'warning',
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          confirmButtonClass: 'el-button--danger',
        },
      )
    } catch {
      return
    }

    try {
      previewContent.value = deleteDatasetRecord(
        previewContent.value,
        selectedFile.value.name,
        record.sourceIndex,
      )
      resetRecordEditor()
      ElMessage.success(`第 ${record.displayIndex} 条已删除，请保存为新版本`)
    } catch (error) {
      ElMessage.error(error instanceof Error ? error.message : '删除失败')
    }
  }

  return {
    editorVisible,
    editingRecord,
    editFields,
    rawDraft,
    savingRecord,
    hasEditorDraftChanges,
    openRecordEditor,
    resetRecordEditor,
    updateEditField,
    closeRecordEditor,
    saveRecord,
    deleteRecord,
  }
}
