'use client'

import { Button, IconButton } from '@/components/ui/button'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { Textarea } from '@/components/ui/textarea'
import ProgressIndicator from '@/app/(main)/create/components/ProgessIndicator'
import { useState, useEffect } from 'react'
import VoiceCard from '@/app/(main)/create/components/Voice/VoiceCard'
import { useParams, useRouter } from 'next/navigation'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { useForm } from 'react-hook-form'
import AIGenerateButton from '@/components/features/ai-generate-button'
import {
  CreateFormData,
  useCreateDict,
  useEditFormStorage,
  useGenerateContent,
  useGetAI,
} from '@/hooks/create'
import { useAudioPlayer } from '@/hooks/useAudioPlayer'
import { GenerateContentRequest, PtType } from '@/services/create'
import VoiceSelector from '@/app/(main)/create/components/Voice/VoiceSelector'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import CloseIconButton from '@/app/(main)/edit/[aiId]/components/CloseIconButton'
import { useMainLayout } from '@/context/mainLayout'
import { cn } from '@/lib/utils'
import { useCheckText } from '@/hooks/auth'

const dialogueFormSchema = z
  .object({
    userDialogueStyle: z.string().trim().optional(),
    prologue: z
      .string()
      .trim()
      .min(1, 'Please enter opening')
      .min(10, 'Please enter at least 10 characters')
      .max(250, 'Please enter less than 250 characters'),
    voice: z.object({
      content: z.string().optional(),
      tone: z.number().min(-50).max(100),
      speed: z.number().min(-50).max(100),
    }),
  })
  .refine(
    (data) => {
      return data.voice.content
    },
    {
      message: 'Please select voice',
      path: ['voice'],
    }
  )
  .refine(
    (data) => {
      if (data.userDialogueStyle) {
        if (data.userDialogueStyle.trim().length > 400) {
          return false
        }
      }
      return true
    },
    {
      message: 'Please enter less than 400 characters',
      path: ['userDialogueStyle'],
    }
  )
  .refine(
    (data) => {
      if (data.userDialogueStyle) {
        if (data.userDialogueStyle.trim().length < 10) {
          return false
        }
      }
      return true
    },
    {
      message: 'Please enter at least 10 characters',
      path: ['userDialogueStyle'],
    }
  )

type DialogueFormValues = z.infer<typeof dialogueFormSchema>

export default function DialogueForm() {
  const { aiId } = useParams<{ aiId: string }>()
  const router = useRouter()

  // 根据AI详情中的声音信息设置初始gender选择
  const getInitialGender = (ai: any, timbreDictList: any[]) => {
    if (!ai?.aiUserExt?.dialogueTimbreCode || !timbreDictList.length) {
      return 'male' // 默认选择男性
    }

    // 根据dialogueTimbreCode查找对应的声音类型
    const timbreDict = timbreDictList.find(
      (item) => item.code?.toString() === ai.aiUserExt.dialogueTimbreCode
    )
    if (timbreDict?.type === 2) {
      return 'female' // type=2表示女性声音
    }
    return 'male' // type=1或其他情况都选择男性
  }

  const [selectedGender, setSelectedGender] = useState('male')
  const [loading, setLoading] = useState(false)
  const { mutateAsync: generateContent } = useGenerateContent()
  const audioPlayer = useAudioPlayer()
  const { data: ai } = useGetAI(Number(aiId))
  const {
    updateDialogueData,
    updateImageData,
    getDialogueData,
    formData,
    isFormDataEmpty,
    updateHasStyleByAI,
  } = useEditFormStorage()
  const { isSidebarExpanded } = useMainLayout()
  const { mutateAsync: checkText } = useCheckText()
  const { data: dict } = useCreateDict()
  const timbreDictList = dict?.timbreDictList || []

  const savedData = getDialogueData() || {
    aiUserExt: {
      userDialogueStyle: '',
      prologue: '',
      voice: {
        tone: 0,
        speed: 25,
        content: undefined,
      },
    },
  }
  const form = useForm<DialogueFormValues>({
    resolver: zodResolver(dialogueFormSchema),
    defaultValues: {
      userDialogueStyle: savedData.aiUserExt?.userDialogueStyle || '',
      prologue: savedData.aiUserExt?.prologue || '',
      voice: {
        tone: savedData.aiUserExt?.voice?.tone || 0,
        speed: savedData.aiUserExt?.voice?.speed || 25,
        content: savedData.aiUserExt?.voice?.content || undefined,
      },
    },
  })

  useEffect(() => {
    if (ai && isFormDataEmpty({ checkEnum: 'dialogue' })) {
      form.reset({
        userDialogueStyle: ai.aiUserExt?.userDialogueStyle || '',
        prologue: ai.aiUserExt?.dialoguePrologue || '',
        voice: {
          tone: Number(ai.aiUserExt?.dialoguePitch) || 0,
          speed: Number(ai.aiUserExt?.dialogueSpeechRate) || 25,
          content: ai.aiUserExt?.dialogueTimbreCode || undefined,
        },
      })
    }
  }, [ai, isFormDataEmpty])

  // 监听AI数据和声音字典数据变化，动态更新gender tab选择
  useEffect(() => {
    if (ai && timbreDictList.length > 0) {
      const initialGender = getInitialGender(ai, timbreDictList)
      setSelectedGender(initialGender)
    }
  }, [ai, timbreDictList])

  useEffect(() => {
    if (isFormDataEmpty({ checkEnum: 'all' })) {
      router.push(`/edit/${aiId}/type`)
    }
  }, [isFormDataEmpty])

  // 监听表单变化，自动暂存数据
  useEffect(() => {
    const subscription = form.watch((data) => {
      // 只有当数据不为空时才自动保存
      updateDialogueData({
        aiUserExt: {
          userDialogueStyle: data.userDialogueStyle,
          prologue: data.prologue,
          voice: {
            content: data.voice?.content || undefined,
            tone: data.voice?.tone,
            speed: data.voice?.speed,
          },
        },
      } as CreateFormData['dialogue'])
    })
    return () => {
      subscription.unsubscribe()
    }
  }, [form])

  async function onSubmit(data: DialogueFormValues) {
    if (!data.voice.content) {
      return
    }
    setLoading(true)
    try {
      // if (!formData.image?.intro) {
      //   const resp = await generateContent({
      //     ptType: PtType.GenAIIntroduction,
      //     nickname: formData.character?.nickname || '',
      //     sex: formData.character?.sex || 0,
      //     birthday: formData.character?.birthday || '',
      //     characterCode: formData.type.characterCode,
      //     tagCode: formData.type.tagCode,
      //     figure: formData.character?.aiUserExt?.profile || '',
      //     dialogue: formData.dialogue?.aiUserExt?.dialogue || '',
      //   })
      //   if (resp) {
      //     updateImageData({
      //       imageUrl: formData.image?.imageUrl || '',
      //       avatarUrl: formData.image?.avatarUrl || '',
      //       isPublic: formData.image?.isPublic || true,
      //       imageStyleCode: formData.image?.imageStyleCode || undefined,
      //       imageDesc: formData.image?.imageDesc || undefined,
      //       intro: resp.content || '',
      //     })
      //   }
      // }
      // if (data.prologue !== ai?.aiUserExt?.dialoguePrologue && data.prologue.trim() !== "") {
      //   const resp = await checkText({
      //     content: data.prologue,
      //   })
      //   if (resp) {
      //     form.setError("prologue", {
      //       message: resp,
      //     })
      //     setLoading(false)
      //     return;
      //   }
      // }
      // if (data.userDialogueStyle !== ai?.aiUserExt?.dialogueStyle && data.userDialogueStyle?.trim() !== "") {
      //   const resp = await checkText({
      //     content: data.userDialogueStyle || "",
      //   })
      //   if (resp) {
      //     form.setError("userDialogueStyle", {
      //       message: resp,
      //     })
      //     setLoading(false)
      //     return;
      //   }
      // }
      updateDialogueData({
        aiUserExt: {
          userDialogueStyle: data.userDialogueStyle,
          prologue: data.prologue,
          voice: {
            content: data.voice.content,
            tone: data.voice.tone,
            speed: data.voice.speed,
          },
        },
      })
      router.push(`/edit/${aiId}/image`)
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

  const selectedVoice = form.watch('voice').content
  const voice1 = form.watch('voice')

  // 播放示例声音
  const handlePlayVoice = (code: string, audioUrl?: string) => {
    if (audioUrl) {
      audioPlayer.play(code, audioUrl)
    } else {
      // 找到对应的音色信息
      const timbre = timbreDictList.find((item) => item.code?.toString() === code)
      if (timbre?.url) {
        audioPlayer.play(code, timbre.url)
      } else {
        console.warn('Audio URL not found for voice:', code)
      }
    }
  }

  // 选择声音
  const handleSelectVoice = (voiceId: string) => {
    audioPlayer.stop()
    const timbre = timbreDictList.find((item) => item.code?.toString() === voiceId)
    form.setValue(
      'voice',
      {
        tone: timbre?.pitchRate || 0,
        speed: timbre?.speechRate || 25,
        content: voiceId,
      },
      {
        shouldValidate: false,
        shouldTouch: false,
      }
    )
  }

  // 取消选择声音
  const handleDeselectVoice = () => {
    audioPlayer.stop()
    form.setValue(
      'voice',
      {
        tone: 0,
        speed: 25,
        content: undefined,
      },
      {
        shouldValidate: false,
        shouldTouch: false,
      }
    )
  }

  return (
    <div className="mx-auto flex w-[752px] flex-col gap-6 pt-28 pb-[200px]">
      {/* 标题区域 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <IconButton
            iconfont="icon-arrow-left"
            size="small"
            variant="ghost"
            onClick={() => {
              router.back()
            }}
          />
          <h1 className="text-txt-primary-normal txt-title-l">Edit Character</h1>
        </div>
        <CloseIconButton />
      </div>

      {/* 进度指示器 */}
      <ProgressIndicator currentStep={3} totalSteps={4} />

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)}>
          {/* 主要内容区域 */}
          <div className="bg-surface-base-normal flex flex-col gap-6 rounded-[16px] p-6">
            <div className="flex flex-col gap-6">
              <h2 className="text-txt-primary-normal txt-title-m">Conversation</h2>

              <FormField
                control={form.control}
                name="prologue"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex justify-between">
                      <FormLabel className="text-txt-primary-normal txt-label-m">
                        Greeting
                      </FormLabel>
                      <AIGenerateButton
                        showAlert={!!field.value.trim()}
                        onConfirm={async () => {
                          const result = {
                            ptType: PtType.GenAIPrologueByNon,
                            characterCode: formData.type.characterCode,
                            tagCode: formData.type.tagCode,
                            sex: formData.character?.sex ?? undefined,
                            birthday: formData.character?.birthday ?? undefined,
                            nickname: formData.character?.nickname ?? undefined,
                            figure: formData.character?.aiUserExt?.userProfile ?? undefined,
                          } as GenerateContentRequest
                          const resp = await generateContent(result)
                          form.setValue('prologue', resp.content)
                        }}
                      />
                    </div>
                    <FormControl>
                      <Textarea
                        placeholder="Set the character's greeting"
                        maxLength={250}
                        showCount
                        rows={4}
                        error={!!form.formState.errors.prologue}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="userDialogueStyle"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex justify-between">
                      <FormLabel className="text-txt-primary-normal txt-label-m">
                        Conversation Style
                        <span className="text-txt-secondary-normal">(Optional)</span>
                      </FormLabel>
                      <AIGenerateButton
                        showAlert={!!field.value?.trim()}
                        onConfirm={async () => {
                          const result = {
                            ptType: PtType.GenAIDialogStyleByNon,
                            characterCode: formData.type.characterCode,
                            tagCode: formData.type.tagCode,
                            sex: formData.character?.sex ?? undefined,
                            birthday: formData.character?.birthday ?? undefined,
                            nickname: formData.character?.nickname ?? undefined,
                            figure: formData.character?.aiUserExt?.userProfile ?? undefined,
                          } as GenerateContentRequest
                          const resp = await generateContent(result)
                          form.setValue('userDialogueStyle', resp.content)
                          updateHasStyleByAI(true)
                        }}
                      />
                    </div>
                    <FormControl>
                      <Textarea
                        placeholder="Describe the character’s conversation style"
                        maxLength={400}
                        showCount
                        rows={4}
                        error={!!form.formState.errors.userDialogueStyle}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* 分隔线 */}
            <div className="bg-outline-normal h-px" />

            {/* 语音设置 */}
            <FormField
              control={form.control}
              name="voice"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-txt-primary-normal txt-label-m">Voice</FormLabel>
                  <FormControl>
                    <VoiceSelector
                      value={field.value}
                      onChange={field.onChange}
                      error={!!form.formState.errors.voice}
                      onPlay={handlePlayVoice}
                      playing={audioPlayer.isPlaying(
                        (field.value.content?.toString() || '') + 'TTS'
                      )}
                      onStop={() => audioPlayer.stop()}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 语音建议 */}
            <div className="flex flex-col gap-3">
              <label className="text-txt-primary-normal txt-label-m">Recommend</label>

              {/* Gender Tabs */}
              <Tabs
                value={selectedGender}
                onValueChange={(value) => {
                  setSelectedGender(value)
                  audioPlayer.stop()
                }}
                className="w-full gap-3"
              >
                <TabsList className="h-8 gap-3 bg-transparent p-0">
                  <TabsTrigger
                    value="male"
                    className="bg-surface-element-normal text-txt-primary-normal txt-body-m data-[state=active]:bg-primary-normal data-[state=active]:border-primary-variant-normal data-[state=active]:text-txt-primary-normal hover:bg-surface-element-hover h-8 cursor-pointer rounded-full border border-transparent px-4 py-0 transition-colors"
                  >
                    Male
                  </TabsTrigger>
                  <TabsTrigger
                    value="female"
                    className="bg-surface-element-normal text-txt-primary-normal txt-body-m data-[state=active]:bg-primary-normal data-[state=active]:border-primary-variant-normal data-[state=active]:text-txt-primary-normal hover:bg-surface-element-hover h-8 cursor-pointer rounded-full border border-transparent px-4 py-0 transition-colors"
                  >
                    Female
                  </TabsTrigger>
                </TabsList>

                <TabsContent value="male" className="mt-0">
                  <div className="grid grid-cols-2 gap-4">
                    {timbreDictList
                      .filter((item) => item.type === 1)
                      .map((item) => (
                        <VoiceCard
                          key={item.code}
                          selected={selectedVoice === item.code?.toString()}
                          playing={audioPlayer.isPlaying(item.code?.toString() || '')}
                          title={item.name || ''}
                          description={item.description || ''}
                          onSelect={() => handleSelectVoice(item.code?.toString() || '')}
                          onDeselect={() => handleDeselectVoice()}
                          onPlay={() => handlePlayVoice(item.code?.toString() || '')}
                        />
                      ))}
                  </div>
                </TabsContent>

                <TabsContent value="female" className="mt-0">
                  <div className="grid grid-cols-2 gap-4">
                    {timbreDictList
                      .filter((item) => item.type === 2)
                      .map((item) => (
                        <VoiceCard
                          key={item.code}
                          selected={selectedVoice === item.code?.toString()}
                          playing={audioPlayer.isPlaying(item.code?.toString() || '')}
                          title={item.name || ''}
                          description={item.description || ''}
                          onSelect={() => handleSelectVoice(item.code?.toString() || '')}
                          onDeselect={() => handleDeselectVoice()}
                          onPlay={() => handlePlayVoice(item.code?.toString() || '')}
                        />
                      ))}
                  </div>
                </TabsContent>
              </Tabs>
            </div>
          </div>

          {/* 底部导航栏 */}
          <div
            className={cn(
              'fixed right-0 bottom-0 backdrop-blur-[32px]',
              isSidebarExpanded ? 'left-[319px]' : 'left-20'
            )}
          >
            <div className="bg-background-default absolute inset-0 opacity-65" />
            <div className="relative flex items-center justify-center px-12 py-6">
              <div className="flex w-full max-w-[752px] items-center justify-between gap-4">
                <div className="flex items-center justify-start"></div>
                <div className="flex items-center justify-end">
                  <Button type="submit" loading={loading}>
                    Next
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </form>
      </Form>
    </div>
  )
}
