"use client"

import { useEffect, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Button, IconButton } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import AIGenerateButton from "@/components/features/ai-generate-button"
import StyleSelector from "../components/StyleSelector"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { Form, FormControl, FormField, FormItem, FormLabel } from "@/components/ui/form"
import GeneralImageList from "../components/GeneralImageList"
import { useCreateDict, useEditFormStorage, useGenerateContent, useGenerateImage, useGetAI } from "@/hooks/create"
import { toast } from "sonner"
import { GenerateContentRequest, PtType } from "@/services/create"
import { useImageGenerationGuard } from "@/hooks/useImageGenerationGuard"
import AbandonCreationDialog from "@/components/features/abandon-creation-dialog"
import { GenderTextMap } from "@/types/user"
import { ImageType } from "@/types/image"
import GeneralImageWithCountButton from "../components/GeneralImageWithCountButton"
import { userKeys } from "@/lib/query-keys"
import { useQueryClient } from "@tanstack/react-query"

const generateImageFormSchema = z.object({
  style: z.number().min(1, { message: "Style is required" }),
  prompt: z.string().trim().min(1, { message: "Please enter" }),
  reference: z.string().optional(),
})

type GenerateImageFormValues = z.infer<typeof generateImageFormSchema>

const ImageEditPage = () => {
  const router = useRouter()
  const [batchNo, setBatchNo] = useState<string | null>(null)
  const [checkedImageUrl, setCheckedImageUrl] = useState<string | null>(null)
  const [loading, setLoading] = useState(false);
  const [allImagesCompleted, setAllImagesCompleted] = useState(false);
  const searchParams = useSearchParams()
  const aiId = searchParams.get("id")
  const { data: dicts } = useCreateDict();
  const { mutateAsync: generateImage, isPending: isGenerating } = useGenerateImage()
  const { updateImageData, getImageData, getCharacterData } = useEditFormStorage()
  const imageData = getImageData()
  const characterData = getCharacterData()
  const { mutateAsync: generateContent, isPending } = useGenerateContent()
  const queryClient = useQueryClient();

  const { data: ai } = useGetAI(Number(aiId));

  const { imageStyleDictList } = dicts || {}

  const form = useForm<GenerateImageFormValues>({
    resolver: zodResolver(generateImageFormSchema),
    defaultValues: {
      style: undefined,
      prompt: undefined,
      reference: undefined,
    },
  })

  useEffect(() => {
    if (ai) {
      form.reset({
        style: Number(ai.aiUserExt?.imageStyleCode) || undefined,
        prompt: ai.aiUserExt?.imageDesc || "",
      })
    }
  }, [ai])

  // 处理图片生成时的导航守卫
  const {
    showAbandonDialog,
    actionType,
    handleBackClick,
    handleGenerateClick,
    handleDialogCancel,
    handleRegenerate,
  } = useImageGenerationGuard({
    isGenerating,
    batchNo,
    allImagesCompleted,
    onRegenerate: () => {
      setBatchNo(null);
      setCheckedImageUrl(null);
      setAllImagesCompleted(false);
    },
  });

  const handleAllImagesCompleted = (completed: boolean) => {
    setAllImagesCompleted(completed);
  };

 

  const onSubmit = async (data: GenerateImageFormValues) => {
    const originalGenerate = async () => {
      setLoading(true)
      try {
        setBatchNo(null)
        setCheckedImageUrl(null)
        const imageData = getImageData();
        const { style, prompt } = data
        const { prompt: stylePrompt } = imageStyleDictList?.find(item => item.id === style) || {}
        const res = await generateImage({
          aiId: Number(aiId),
          hl: true,
          imageStylePrompt: stylePrompt,
          content: prompt,
          sex: characterData?.sex,
          birthday: characterData?.birthday,
          type: ImageType.EDIT_AI_IMAGE,
          introduction: imageData?.intro || '',
        })
        await queryClient.invalidateQueries({ queryKey: userKeys.albumCreateCount() })
        if (res) {
          setBatchNo(res.batchNo || null)
        }
      } catch (error) {
        console.error(error)
      } finally {
        setLoading(false)
      }
    }
    
    handleGenerateClick(originalGenerate);
  }

  const handleConfirm = () => {
    if (checkedImageUrl) {
      updateImageData({
        avatarUrl: checkedImageUrl || "",
        intro: imageData?.intro || "",
        isPublic: imageData?.isPublic || true,
        imageUrl: checkedImageUrl,
        imageStyleCode: form.getValues("style"),
        imageDesc: form.getValues("prompt"),
      })
      router.back();
    }
  }

  return (
    <div className="flex flex-col size-full">
      
      {/* 主要内容区域 - 左右分栏 */}
      <div className="flex flex-1 gap-6 px-6 overflow-hidden">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="h-full flex flex-col">
            {/* 页面标题 */}
            <div className="flex items-center gap-2 py-6">
              <IconButton
                variant="ghost"
                size="small"
                onClick={handleBackClick}
                className="size-8 p-2"
              >
                <i className="iconfont icon-arrow-left text-txt-primary-normal" />
              </IconButton>
              <h1 className="text-txt-primary-normal txt-title-l">
                Generate Image
              </h1>
            </div>
            {/* 左侧控制面板 */}
            <div className="flex-1 w-[404px] bg-surface-base-normal rounded-2xl flex flex-col overflow-hidden h-full mb-6">
              {/* 可滚动内容区域 */}
              <div className="flex-1 overflow-y-auto">
                <div className="p-6 space-y-6">
                  <FormField
                    control={form.control}
                    name="style"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-txt-primary-normal txt-label-m">Style</FormLabel>
                        <FormControl>
                        {/* 样式选择 */}
                          <StyleSelector
                            value={field.value}
                            onChange={field.onChange}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="prompt"
                    render={({ field }) => (
                      <FormItem>
                        <div className="flex justify-between">
                          <FormLabel className="text-txt-primary-normal txt-label-m">Prompt</FormLabel>
                          <AIGenerateButton
                            loading={false}
                            showAlert={!!field.value && !!field.value.trim()}
                            onConfirm={async () => {
                              const hasValue = field.value && !!field.value.trim();
                              const result: GenerateContentRequest = {
                                sex: characterData?.sex,
                                birthday: characterData?.birthday,
                                introduction: imageData?.intro || '',
                                ptType: hasValue ? PtType.GenAIImageDescByContent : PtType.GenAIImageDescByNon,
                              }
                              if (hasValue) {
                                result.content = field.value.trim();
                              }
                              const resp = await generateContent(result)
                              if (resp) {
                                form.setValue("prompt", resp.content || "", {
                                  shouldValidate: true,
                                })
                              }
                            }}
                          />
                        </div>
                        <FormControl>
                          <Textarea
                            placeholder="Describe the character’s appearance — skin tone, outfit, hairstyle, facial features, pose, and background."
                            maxLength={1000}
                            showCount
                            rows={4}
                            {...field}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
              
                  <div>
                    <div className="txt-label-m">Reference</div>
                    <div className="txt-body-l text-txt-secondary-normal mt-3">
                      AI will generate images based on the character’s original appearance
                    </div>
                  </div>
                </div>
              </div>

              {/* 底部固定按钮区域 */}
              <div className="mt-6 space-y-2 px-6 pb-6">
                <GeneralImageWithCountButton isGenerating={loading} disabled={!form.formState.isValid} />
              </div>
            </div>
          </form>
        </Form>

        {/* 右侧结果展示区域 */}
        <div className="flex-1 h-full pt-20 relative">
          <div className="overflow-y-auto h-full pb-40 pt-1">
            <GeneralImageList 
              batchNo={batchNo} 
              setBatchNo={setBatchNo} 
              value={checkedImageUrl} 
              onChange={setCheckedImageUrl}
              onAllImagesCompleted={handleAllImagesCompleted}
            />
          </div>
          <div className="absolute left-0 right-0 bottom-0 backdrop-blur-[32px] px-12 pt-6 pb-6 flex justify-center z-10">
            <div className="absolute bg-background-default inset-0 opacity-65" />
            <div className="w-[752px] mx-auto text-right relative">
              <Button variant="primary" size="large" disabled={!checkedImageUrl} onClick={handleConfirm}>Confirm</Button>
            </div>
          </div>
        </div>
      </div>

      {/* 放弃创作确认弹窗 */}
      <AbandonCreationDialog
        open={showAbandonDialog}
        onOpenChange={(open) => {
          if (!open) {
            handleDialogCancel();
          }
        }}
        onCancel={handleDialogCancel}
        onRegenerate={handleRegenerate}
        actionType={actionType}
      />
    </div>
  )
}

export default ImageEditPage;