import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  CreateOrEditAiRequest,
  createService,
  GenerateContentRequest,
  GenerateImageRequest,
  GetImageGenerateResultRequest,
} from '@/services/create'
import { aiUserKeys, createKeys } from '@/lib/query-keys'
import { useCallback, useState } from 'react'
import { Gender } from '@/types/user'

// 表单数据类型
export interface TypeFormData {
  roleCode: string
  characterCode: string
  tagCode: string
}

// 完整的创建表单数据类型
export interface CreateFormData {
  type: TypeFormData
  character?: {
    nickname: string
    sex: Gender
    birthday: string
    aiUserExt: {
      userProfile: string
    }
  }
  dialogue?: {
    // 对话相关数据
    aiUserExt: {
      userDialogueStyle?: string
      prologue: string
      voice: {
        content: string
        tone: number
        speed: number
      }
    }
  }
  image?: {
    imageUrl: string
    avatarUrl: string
    intro: string
    isPublic: boolean
    imageStyleCode?: number
    imageDesc?: string
  }
  hasPreferenceByAI: boolean
  hasStyleByAI: boolean
}

export function useCreateDict() {
  return useQuery({
    queryKey: createKeys.dict(),
    queryFn: () => createService.dict(),
  })
}

export function useGenerateContent() {
  return useMutation({
    mutationFn: (data: GenerateContentRequest) => createService.generateContent(data),
  })
}

export function useGenerateImage() {
  return useMutation({
    mutationFn: (data: GenerateImageRequest) => createService.generateImage(data),
  })
}

export function useGetImageGenerateResult() {
  return useMutation({
    mutationFn: (data: GetImageGenerateResultRequest) => createService.getImageGenerateResult(data),
  })
}

export function useCreateAI() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateOrEditAiRequest) => createService.createOrEditAI(data),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: createKeys.getAICharacterList(),
      })
    },
  })
}

export function useGetAI(aiId: number) {
  return useQuery({
    queryKey: createKeys.getAI(aiId),
    queryFn: () => createService.getAI({ aiId }),
  })
}

export function useEditAI(aiId: number) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateOrEditAiRequest) => createService.createOrEditAI(data),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: createKeys.getAICharacterList(),
      })
      queryClient.invalidateQueries({
        queryKey: createKeys.getAI(aiId),
      })
      queryClient.invalidateQueries({
        queryKey: aiUserKeys.baseInfo({ aiId }),
      })
    },
  })
}

export function useEditAIAvatar() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { aiId: number; userHead: string }) => createService.editAIAvatar(data),
    onSuccess: (_, { aiId }) => {
      queryClient.invalidateQueries({
        queryKey: createKeys.getAI(aiId),
      })
      queryClient.invalidateQueries({
        queryKey: aiUserKeys.baseInfo({ aiId }),
      })
    },
  })
}

export function useGetAICharacterList() {
  return useQuery({
    queryKey: createKeys.getAICharacterList(),
    queryFn: () => createService.getAICharacterList(),
  })
}

// LocalStorage 键名
const CREATE_FORM_STORAGE_KEY = 'create_form_data'

// 表单数据暂存 Hook
export function useCreateFormStorage() {
  const [formData, setFormData] = useState<CreateFormData>(() => {
    // 初始化时从 localStorage 读取数据
    if (typeof window !== 'undefined') {
      try {
        const saved = localStorage.getItem(CREATE_FORM_STORAGE_KEY)
        return saved
          ? JSON.parse(saved)
          : {
              type: { roleCode: '', characterCode: '', tagCode: '' },
              character: {
                nickname: '',
                sex: undefined,
                birthday: '',
                aiUserExt: { userProfile: '' },
              },
              dialogue: {
                aiUserExt: {
                  userDialogueStyle: '',
                  prologue: '',
                  voice: { content: '', tone: 5, speed: 5 },
                },
              },
              image: {
                imageUrl: '',
                avatarUrl: '',
                intro: '',
                isPublic: true,
                imageStyleCode: undefined,
                imageDesc: undefined,
              },
            }
      } catch (error) {
        console.error('读取表单数据失败:', error)
        return {
          type: { roleCode: '', characterCode: '', tagCode: '' },
          character: { nickname: '', sex: undefined, birthday: '', aiUserExt: { userProfile: '' } },
          dialogue: {
            aiUserExt: {
              userDialogueStyle: '',
              prologue: '',
              voice: { content: '', tone: 5, speed: 5 },
            },
          },
          image: {
            imageUrl: '',
            avatarUrl: '',
            intro: '',
            isPublic: true,
            imageStyleCode: undefined,
            imageDesc: undefined,
          },
        }
      }
    }
    return {
      type: { roleCode: '', characterCode: '', tagCode: '' },
      character: { nickname: '', sex: undefined, birthday: '', aiUserExt: { userProfile: '' } },
      dialogue: {
        aiUserExt: {
          userDialogueStyle: '',
          prologue: '',
          voice: { content: '', tone: 5, speed: 5 },
        },
      },
      image: {
        imageUrl: '',
        avatarUrl: '',
        intro: '',
        isPublic: true,
        imageStyleCode: undefined,
        imageDesc: undefined,
      },
    }
  })

  // 保存数据到 localStorage
  const saveToStorage = useCallback((data: CreateFormData) => {
    if (typeof window !== 'undefined') {
      try {
        localStorage.setItem(CREATE_FORM_STORAGE_KEY, JSON.stringify(data))
      } catch (error) {
        console.error('保存表单数据失败:', error)
      }
    }
  }, [])

  // 更新表单数据
  const updateFormData = useCallback(
    (updates: Partial<CreateFormData>) => {
      setFormData((prev) => {
        const newData = { ...prev, ...updates }
        saveToStorage(newData)
        return newData
      })
    },
    [saveToStorage]
  )

  // 更新特定步骤的数据
  const updateTypeData = useCallback(
    (typeData: TypeFormData) => {
      updateFormData({ type: typeData })
    },
    [updateFormData]
  )

  const updateCharacterData = useCallback(
    (characterData: CreateFormData['character']) => {
      updateFormData({ character: characterData })
    },
    [updateFormData]
  )

  const updateDialogueData = useCallback(
    (dialogueData: CreateFormData['dialogue']) => {
      updateFormData({ dialogue: dialogueData })
    },
    [updateFormData]
  )

  const updateImageData = useCallback(
    (imageData: CreateFormData['image']) => {
      updateFormData({ image: imageData })
    },
    [updateFormData]
  )

  // 清除所有数据
  const clearFormData = useCallback(() => {
    const emptyData = {
      type: { roleCode: '', characterCode: '', tagCode: '' },
      hasPreferenceByAI: false,
      hasStyleByAI: false,
    }
    setFormData(emptyData)
    if (typeof window !== 'undefined') {
      localStorage.removeItem(CREATE_FORM_STORAGE_KEY)
    }
  }, [])

  // 获取特定步骤的数据
  const getTypeData = useCallback(() => formData.type, [formData.type])
  const getCharacterData = useCallback(() => formData.character, [formData.character])
  const getDialogueData = useCallback(() => formData.dialogue, [formData.dialogue])
  const getImageData = useCallback(() => {
    // 直接从 localStorage 读取最新数据，避免 React state 更新延迟
    if (typeof window !== 'undefined') {
      try {
        const saved = localStorage.getItem(CREATE_FORM_STORAGE_KEY)
        if (saved) {
          const data = JSON.parse(saved) as CreateFormData
          return data.image
        }
      } catch (error) {
        console.error('读取 image 数据失败:', error)
      }
    }
    return formData.image
  }, [formData.image])
  const getFormData = useCallback(() => localStorage.getItem(CREATE_FORM_STORAGE_KEY), [])

  const isFormDataEmpty = useCallback(() => {
    const formData = JSON.parse(getFormData() || '{}') as CreateFormData
    const { type, character, dialogue, image } = formData || {}
    // 检查 type 数据是否有值
    const hasTypeData = type && (type.roleCode || type.characterCode || type.tagCode)

    // 检查 character 数据是否有值
    const hasCharacterData =
      character &&
      (character.nickname ||
        character.sex !== undefined ||
        character.birthday ||
        character.aiUserExt?.userProfile)

    // 检查 dialogue 数据是否有值
    const hasDialogueData =
      dialogue &&
      (dialogue.aiUserExt?.userDialogueStyle ||
        dialogue.aiUserExt?.prologue ||
        dialogue.aiUserExt?.voice?.content)

    // 检查 image 数据是否有值
    const hasImageData =
      image && (image.imageUrl || image.avatarUrl || image.intro || image.imageDesc)

    return !hasTypeData && !hasCharacterData && !hasDialogueData && !hasImageData
  }, [getFormData])

  const updateHasPreferenceByAI = useCallback(
    (hasPreferenceByAI: boolean) => {
      updateFormData({ hasPreferenceByAI })
    },
    [updateFormData]
  )
  const updateHasStyleByAI = useCallback(
    (hasStyleByAI: boolean) => {
      updateFormData({ hasStyleByAI })
    },
    [updateFormData]
  )

  return {
    formData,
    updateFormData,
    updateTypeData,
    updateCharacterData,
    updateDialogueData,
    updateImageData,
    clearFormData,
    getTypeData,
    getCharacterData,
    getDialogueData,
    getImageData,
    getFormData,
    isFormDataEmpty,
    updateHasPreferenceByAI,
    updateHasStyleByAI,
  }
}

// 完整的创建表单数据类型
export interface EditFormData {
  type: TypeFormData
  character?: {
    nickname: string
    sex: Gender
    birthday: string
    aiUserExt: {
      userProfile: string
    }
  }
  dialogue?: {
    // 对话相关数据
    aiUserExt: {
      userDialogueStyle?: string
      prologue: string
      voice: {
        content: string
        tone: number
        speed: number
      }
    }
  }
  image?: {
    imageUrl: string
    avatarUrl: string
    intro: string
    isPublic: boolean
    imageStyleCode?: number
    imageDesc?: string
  }
  hasPreferenceByAI: boolean
  hasStyleByAI: boolean
}

// LocalStorage 键名
const EDIT_FORM_STORAGE_KEY = 'edit_form_data'

// 表单数据暂存 Hook
export function useEditFormStorage() {
  const [formData, setFormData] = useState<EditFormData>(() => {
    // 初始化时从 localStorage 读取数据
    if (typeof window !== 'undefined') {
      try {
        const saved = localStorage.getItem(EDIT_FORM_STORAGE_KEY)
        return saved
          ? JSON.parse(saved)
          : {
              type: { roleCode: '', characterCode: '', tagCode: '' },
              character: {
                nickname: '',
                sex: undefined,
                birthday: '',
                aiUserExt: { userProfile: '' },
              },
              dialogue: {
                aiUserExt: {
                  userDialogueStyle: '',
                  prologue: '',
                  voice: { content: '', tone: 5, speed: 5 },
                },
              },
              image: {
                imageUrl: '',
                avatarUrl: '',
                intro: '',
                isPublic: true,
                imageStyleCode: undefined,
                imageDesc: undefined,
              },
            }
      } catch (error) {
        console.error('读取表单数据失败:', error)
        return {
          type: { roleCode: '', characterCode: '', tagCode: '' },
          character: { nickname: '', sex: undefined, birthday: '', aiUserExt: { userProfile: '' } },
          dialogue: {
            aiUserExt: {
              userDialogueStyle: '',
              prologue: '',
              voice: { content: '', tone: 5, speed: 5 },
            },
          },
          image: {
            imageUrl: '',
            avatarUrl: '',
            intro: '',
            isPublic: true,
            imageStyleCode: undefined,
            imageDesc: undefined,
          },
        }
      }
    }
    return {
      type: { roleCode: '', characterCode: '', tagCode: '' },
      character: { nickname: '', sex: undefined, birthday: '', aiUserExt: { userProfile: '' } },
      dialogue: {
        aiUserExt: {
          userDialogueStyle: '',
          prologue: '',
          voice: { content: '', tone: 5, speed: 5 },
        },
      },
      image: {
        imageUrl: '',
        avatarUrl: '',
        intro: '',
        isPublic: true,
        imageStyleCode: undefined,
        imageDesc: undefined,
      },
    }
  })

  // 保存数据到 localStorage
  const saveToStorage = useCallback((data: EditFormData) => {
    if (typeof window !== 'undefined') {
      try {
        localStorage.setItem(EDIT_FORM_STORAGE_KEY, JSON.stringify(data))
      } catch (error) {
        console.error('保存表单数据失败:', error)
      }
    }
  }, [])

  // 更新表单数据
  const updateFormData = useCallback(
    (updates: Partial<EditFormData>) => {
      setFormData((prev) => {
        const newData = { ...prev, ...updates }
        saveToStorage(newData)
        return newData
      })
    },
    [saveToStorage]
  )

  // 更新特定步骤的数据
  const updateTypeData = useCallback(
    (typeData: TypeFormData) => {
      updateFormData({ type: typeData })
    },
    [updateFormData]
  )

  const updateCharacterData = useCallback(
    (characterData: EditFormData['character']) => {
      updateFormData({ character: characterData })
    },
    [updateFormData]
  )

  const updateDialogueData = useCallback(
    (dialogueData: EditFormData['dialogue']) => {
      updateFormData({ dialogue: dialogueData })
    },
    [updateFormData]
  )

  const updateImageData = useCallback(
    (imageData: EditFormData['image']) => {
      updateFormData({ image: imageData })
    },
    [updateFormData]
  )

  // 清除所有数据
  const clearFormData = useCallback(() => {
    const emptyData = {
      type: { roleCode: '', characterCode: '', tagCode: '' },
      hasPreferenceByAI: false,
      hasStyleByAI: false,
    }
    setFormData(emptyData)
    if (typeof window !== 'undefined') {
      localStorage.removeItem(EDIT_FORM_STORAGE_KEY)
    }
  }, [])

  // 获取特定步骤的数据
  const getTypeData = useCallback(() => formData.type, [formData.type])
  const getCharacterData = useCallback(() => formData.character, [formData.character])
  const getDialogueData = useCallback(() => formData.dialogue, [formData.dialogue])
  const getImageData = useCallback(() => {
    // 直接从 localStorage 读取最新数据，避免 React state 更新延迟
    if (typeof window !== 'undefined') {
      try {
        const saved = localStorage.getItem(EDIT_FORM_STORAGE_KEY)
        if (saved) {
          const data = JSON.parse(saved) as EditFormData
          return data.image
        }
      } catch (error) {
        console.error('读取 image 数据失败:', error)
      }
    }
    return formData.image
  }, [formData.image])
  const getFormData = useCallback(() => localStorage.getItem(EDIT_FORM_STORAGE_KEY), [])

  const isFormDataEmpty = useCallback(
    ({ checkEnum }: { checkEnum: 'all' | 'type' | 'character' | 'dialogue' | 'image' }) => {
      const formData = JSON.parse(getFormData() || '{}') as EditFormData
      const { type, character, dialogue, image } = formData || {}
      // 检查 type 数据是否有值
      const hasTypeData = type && (type.roleCode || type.characterCode || type.tagCode)

      // 检查 character 数据是否有值
      const hasCharacterData =
        character &&
        (character.nickname ||
          character.sex !== undefined ||
          character.birthday ||
          character.aiUserExt?.userProfile)

      // 检查 dialogue 数据是否有值
      const hasDialogueData =
        dialogue &&
        (dialogue.aiUserExt?.userDialogueStyle ||
          dialogue.aiUserExt?.prologue ||
          dialogue.aiUserExt?.voice?.content)

      // 检查 image 数据是否有值
      const hasImageData =
        image && (image.imageUrl || image.avatarUrl || image.intro || image.imageDesc)

      if (checkEnum === 'all') {
        return !hasTypeData && !hasCharacterData && !hasDialogueData && !hasImageData
      }
      if (checkEnum === 'type') {
        return !hasTypeData
      }
      if (checkEnum === 'character') {
        return !hasCharacterData
      }
      if (checkEnum === 'dialogue') {
        return !hasDialogueData
      }
      if (checkEnum === 'image') {
        return !hasImageData
      }
    },
    [getFormData]
  )

  const updateHasPreferenceByAI = useCallback(
    (hasPreferenceByAI: boolean) => {
      updateFormData({ hasPreferenceByAI })
    },
    [updateFormData]
  )
  const updateHasStyleByAI = useCallback(
    (hasStyleByAI: boolean) => {
      updateFormData({ hasStyleByAI })
    },
    [updateFormData]
  )

  return {
    formData,
    updateFormData,
    updateTypeData,
    updateCharacterData,
    updateDialogueData,
    updateImageData,
    clearFormData,
    getTypeData,
    getCharacterData,
    getDialogueData,
    getImageData,
    getFormData,
    isFormDataEmpty,
    updateHasPreferenceByAI,
    updateHasStyleByAI,
  }
}
