"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { Button, IconButton } from "@/components/ui/button"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import { Textarea } from "@/components/ui/textarea"
import { useRouter } from "next/navigation"
import { useCreateAI, useCreateDict, useCreateFormStorage, useGenerateContent } from "@/hooks/create"
import { useEffect, useState } from "react"
import Image from "next/image"
import AIGenerateButton from "@/components/features/ai-generate-button"
import { Chip } from "@/components/ui/chip"
import ImageSelector from "./ImageSelector"
import { AvatarCropModal } from "@/components/ui/avatar-crop-modal"
import { AIPermission, CreateOrEditAiRequest, PtType } from "@/services/create"
import CopyrightRuleModal from "./CopyrightRuleModal"
import { BizTypeEnum } from "@/services/common"
import ProgressIndicator from "./ProgessIndicator"
import CloseIconButton from "./CloseIconButton"
import { useMainLayout } from "@/context/mainLayout"
import { cn } from "@/lib/utils"
import { toast } from "sonner"
import { useQueryClient } from "@tanstack/react-query"
import { authKeys } from "@/lib/query-keys"
import { User } from "@/services/auth"
import { useCheckText, useCurrentUser } from "@/hooks/auth"
import { AlertDialog, AlertDialogAction, AlertDialogContent, AlertDialogFooter, AlertDialogDescription, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"
import { isVipDrawerOpenAtom } from "@/atoms/im"
import { useSetAtom } from "jotai"
import { VipType } from "@/services/wallet"
import { isCreateAiLimitReachedDialogOpenAtom } from "@/atoms/global"

// 表单验证模式
const imageFormSchema = z.object({
  imageUrl: z.string(),
  avatarUrl: z.string(),
  intro: z.string().min(10, "Please enter at least 10 characters").max(300, "Please enter less than 300 characters"),
  isPublic: z.boolean(),
}).refine((data) => {
  return !!data.imageUrl && !!data.avatarUrl
}, {
  message: "Please upload or generate an image",
  path: ["imageUrl", "avatarUrl"]
})

type ImageFormValues = {
  imageUrl: string
  avatarUrl: string
  intro: string
  isPublic: boolean
}

type ImageFormSchemaType = z.infer<typeof imageFormSchema>

export default function ImageForm() {
  const router = useRouter()
  const { updateImageData, getImageData, formData, isFormDataEmpty, clearFormData } = useCreateFormStorage()
  const { mutateAsync: generateContent, isPending: isGeneratingContent } = useGenerateContent()
  const { mutateAsync: createAI } = useCreateAI();
  const { data: dict } = useCreateDict();
  const { isSidebarExpanded } = useMainLayout();
  const queryClient = useQueryClient()

  const [showCropModal, setShowCropModal] = useState(false)
  const [showCopyrightRuleModal, setShowCopyrightRuleModal] = useState(false)
  const [loading, setLoading] = useState(false)
  const savedData = getImageData()
  const { data: currentUser } = useCurrentUser()
  const setIsVipDrawerOpen = useSetAtom(isVipDrawerOpenAtom)
  const setIsCreateAiLimitReachedDialogOpen = useSetAtom(isCreateAiLimitReachedDialogOpenAtom)
  const { isMember, canCreateAiCount, createdAiCount } = currentUser || {}

  const { mutateAsync: checkText } = useCheckText();

  const form = useForm<ImageFormSchemaType>({
    resolver: zodResolver(imageFormSchema),
    defaultValues: {
      imageUrl: savedData?.imageUrl || undefined,
      avatarUrl: savedData?.avatarUrl || undefined,
      intro: savedData?.intro || "",
      isPublic: savedData?.isPublic ?? true,
    }
  })
  const watchImageUrl = form.watch('imageUrl')
  const imageUrl = form.watch('imageUrl');

  useEffect(() => {
    if (isFormDataEmpty()) {
      router.push('/create/type');
    }
  }, [isFormDataEmpty])

  // 监听表单变化，自动暂存数据
  useEffect(() => {
    const subscription = form.watch((data) => {
      if (data.imageUrl || data.avatarUrl || data.intro || data.isPublic !== undefined) {
        updateImageData({
          imageUrl: data.imageUrl || "",
          avatarUrl: data.avatarUrl || "",
          intro: data.intro || "",
          isPublic: data.isPublic ?? true,
          imageStyleCode: savedData?.imageStyleCode,
          imageDesc: savedData?.imageDesc,
        })
      }
    })
    return () => {
      subscription.unsubscribe()
    }
  }, [form, updateImageData])

  function onSubmit(data: ImageFormValues) {
    // 创建的AI数量达到上限
    if ((createdAiCount ?? 0) >= (canCreateAiCount ?? 0)) {
      if (isMember) {
        setIsCreateAiLimitReachedDialogOpen(true)
        return;
      } else {
        setIsVipDrawerOpen({ open: true, vipType: VipType.ADD_CREATE_AI })
        return;
      }
    }

    setShowCopyrightRuleModal(true)
  }

  const handleConfirm = async () => {
    setLoading(true)
    try {
      const { type, character, dialogue, image, hasPreferenceByAI, hasStyleByAI } = formData;
      const timbreDictList = dict?.timbreDictList || [];
      const timbreDict = timbreDictList.find(item => item.code === dialogue?.aiUserExt?.voice?.content);
      const { url } = timbreDict || {};
      const { intro, isPublic, avatarUrl, imageUrl, imageStyleCode, imageDesc } = image || {};
      
      // 如果hasPreferenceByAI为false，hasStyleByAI为false，需要调用AI增强。
      // const preferencePromise = hasPreferenceByAI ? Promise.resolve({
      //   content: character?.aiUserExt?.userProfile,
      // }) : generateContent({
      //   ptType: PtType.GenAIProfileByContent,
      //   nickname: character?.nickname || '',
      //   sex: character?.sex || 0,
      //   birthday: character?.birthday || '',
      //   characterCode: type.characterCode,
      //   tagCode: type.tagCode,
      //   content: character?.aiUserExt?.userProfile,
      // })
      // const stylePromise = hasStyleByAI ? Promise.resolve({
      //   content: dialogue?.aiUserExt?.userDialogueStyle,
      // }) : generateContent({
      //   ptType: PtType.GenAIProfileByContent,
      //   nickname: character?.nickname || '',
      //   sex: character?.sex || 0,
      //   birthday: character?.birthday || '',
      //   characterCode: type.characterCode,
      //   tagCode: type.tagCode,
      //   content: dialogue?.aiUserExt?.userDialogueStyle,
      // })
      // const [preference, style] = await Promise.all([preferencePromise, stylePromise])
      const preference = {
        content: character?.aiUserExt?.userProfile,
      };
      const style = {
        content: dialogue?.aiUserExt?.userDialogueStyle,
      };

      if (intro) {
        const resp = await checkText({
          content: intro,
        })
        if (resp) {
          form.setError("intro", {
            message: resp,
          })
          return;
        }
      }

      const extractJsonResp = await generateContent({
        ptType: PtType.ExtractJsonContent,
        figure: character?.aiUserExt?.userProfile || '',
      })

      const result = {
        ...type,
        ...character,
        headImg: avatarUrl,
        birthday: new Date(character?.birthday || '').getTime(),
        imageUrl,
        introduction: intro,
        permission: isPublic ? AIPermission.Public : AIPermission.Private,
        imageHeight: 1024,
        imageWidth: 1024,
        aiUserExt: {
          profile: preference.content?.slice(0, 2000),
          dialogueStyle: style.content?.slice(0, 300),
          userProfile: character?.aiUserExt?.userProfile,
          userDialogueStyle: dialogue?.aiUserExt?.userDialogueStyle,
          dialoguePrologue: dialogue?.aiUserExt?.prologue,
          dialogueTimbreCode: dialogue?.aiUserExt?.voice?.content,
          dialoguePitch: dialogue?.aiUserExt?.voice?.tone,
          dialogueSpeechRate: dialogue?.aiUserExt?.voice?.speed,
          dialogueTimbreUrl: url,
          imageStyleCode,
          imageDesc,
          userProfileExtJson: extractJsonResp?.content || '',
        }
      }

      const resp = await createAI(result as unknown as CreateOrEditAiRequest)
      await queryClient.setQueryData(authKeys.currentUser(), (old: User) => {
        return {
          ...old,
          createdAiCount: old.createdAiCount ?? 0 + 1,
        }
      })
      clearFormData();
      toast.success("Character created successfully!");
      localStorage.removeItem('create-image-generate-batch');
      localStorage.setItem('create-ai-show-guide', 'true');
      router.push(`/chat/${resp.aiId}`);
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false)
    }
    
  }

  return (
    <div className="flex flex-col gap-6 w-[752px] mx-auto pt-[111px] pb-[200px]">
      {/* 标题区域 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <IconButton 
            variant="ghost" 
            size="small" 
            onClick={() => router.back()}
            className="w-8 h-8 p-2 rounded-full hover:bg-white/10"
          >
            <i className="iconfont icon-arrow-left text-white" />
          </IconButton>
          <h1 className="text-white text-2xl font-semibold leading-7">
          Create a Character
          </h1>
        </div>
        <CloseIconButton />
      </div>

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

      {/* 主要内容区域 */}
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <div className="bg-[#352e3e] rounded-2xl p-6 flex flex-col gap-6">
            <div className="flex flex-col gap-6">
              <h2 className="text-white text-xl font-semibold leading-6">
                Create
              </h2>

              {/* 图片上传/预览区域 */}
              <FormField
                control={form.control}
                name="imageUrl"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex items-center justify-between">
                      <FormLabel className="txt-label-m">Image</FormLabel>
                      {watchImageUrl && <div
                        className="txt-label-m text-primary-variant-normal cursor-pointer"
                        onClick={() => {
                          if (loading) return;
                          router.push("/generate/image")
                        }}
                      >Regenerate</div>}
                    </div>
                    <FormControl>
                      <ImageSelector
                        value={field.value}
                        onChange={field.onChange}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {watchImageUrl && <FormField
                control={form.control}
                name="avatarUrl"
                render={({ field }) => (
                  <FormItem>
                    <div className="">
                      <div className="flex items-center justify-between">
                        <FormLabel className="txt-label-m">Avatar</FormLabel>
                        {imageUrl && (
                          <div 
                            className="txt-label-m text-primary-variant-normal cursor-pointer"
                            onClick={() => {
                              if (loading) return;
                              setShowCropModal(true)
                            }}
                          >
                            Crop
                          </div>
                        )}
                      </div>
                      <FormControl>
                        {field.value ? (
                          <Image src={field.value} alt="Avatar" width={80} height={80} className="rounded-full w-20 h-20 mt-3 object-cover" />
                        ) : (
                          <div className="w-20 h-20 mt-3 rounded-full bg-surface-element-normal border-2 border-dashed border-outline-normal flex items-center justify-center">
                            <i className="iconfont icon-user text-txt-secondary-normal text-xl" />
                          </div>
                        )}
                      </FormControl>
                    </div>
                  </FormItem>
                )}
              />}

              {/* 简介输入 */}
              <FormField
                control={form.control}
                name="intro"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex items-center justify-between">
                      <FormLabel className="txt-label-m">Introduction</FormLabel>
                      <AIGenerateButton
                        showAlert={!!field.value.trim()}
                        disabled={loading}
                        onConfirm={async () => {
                          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?.userProfile || '',
                            dialogue: formData.dialogue?.aiUserExt?.userDialogueStyle || '',
                          })
                          if (resp) {
                            form.setValue('intro', resp.content || "")
                          }
                        }}
                        loading={isGeneratingContent}
                      />
                    </div>
                    <FormControl>
                      <Textarea
                        placeholder="Introduce the virtual character to the user"
                        maxLength={300}
                        showCount
                        error={!!form.formState.errors.intro}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 隐私设置 */}
              <FormField
                control={form.control}
                name="isPublic"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="">Private</FormLabel>
                    <div className="flex gap-3">
                      <Chip state={field.value ? "active" : "inactive"} onClick={() => form.setValue('isPublic', true)}>
                        <i className="iconfont icon-eye-on" />
                        Public
                      </Chip>
                      <Chip state={!field.value ? "active" : "inactive"} onClick={() => form.setValue('isPublic', false)}>
                        <i className="iconfont icon-eye-off" />
                        Private
                      </Chip>
                    </div>
                  </FormItem>
                )}
              />
            </div>
          </div>

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

      {/* 头像裁剪弹窗 */}
      {imageUrl && (
        <AvatarCropModal
          isOpen={showCropModal}
          bizType={BizTypeEnum.Album}
          onClose={() => setShowCropModal(false)}
          image={imageUrl}
          onConfirm={(croppedImageUrl) => {
            form.setValue('avatarUrl', croppedImageUrl)
            setShowCropModal(false)
          }}
          onCancel={() => setShowCropModal(false)}
        />
      )}

      <CopyrightRuleModal
        isOpen={showCopyrightRuleModal}
        onOpenChange={setShowCopyrightRuleModal}
        onConfirm={handleConfirm}
      />
    </div>
  )
}