"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 { useCreateDict, useGenerateContent, useGenerateImage, useGetAI } from "@/hooks/create"
import GeneralImageListMultiple from "../components/GeneralImageListMultiple"
import { useImageViewer } from "@/hooks/useImageViewer"
import { ImageViewer } from "@/components/ui/image-viewer"
import { useBatchAddBackground } from "@/hooks/useIm"
import MultipleViewerAction from "../components/MultipleViewerAction"
import { useImageGenerationGuard } from "@/hooks/useImageGenerationGuard"
import AbandonCreationDialog from "@/components/features/abandon-creation-dialog"
import dayjs from "dayjs"
import { GenerateContentRequest, PtType } from "@/services/create"
import { useGetAIUserBaseInfo } from "@/hooks/aiUser"
import { ImageType } from "@/types/image"
import Image from "next/image"
import { ChatPriceType, ChatPriceTypeMap, useGetWalletBalance, useUpdateWalletBalance } from "@/hooks/useWallet"
import { useQueryClient } from "@tanstack/react-query"
import { isChargeDrawerOpenAtom } from "@/atoms/im"
import { useSetAtom } from "jotai"
import { walletKeys } from "@/lib/query-keys"

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

type GenerateImageFormValues = z.infer<typeof generateImageFormSchema>

type SelectedImage = {
  url: string;
  width: number;
  height: number;
}


const Image2BackgroundPage = () => {
  const router = useRouter()
  const [batchNo, setBatchNo] = useState<string | null>(null)
  const [selectedImages, setSelectedImages] = useState<string | null>(null)
  // 临时数据，用于查看大图时候的图片
  const [lockPriceImages, setLockPriceImages] = useState<Array<SelectedImage & { unlockPrice: number }>>([]);
  const [allImagesCompleted, setAllImagesCompleted] = useState(false);
  const imageViewer = useImageViewer({ autoCloseOnChoose: true })
  const { data: dicts } = useCreateDict();

  const searchParams = useSearchParams()
  const aiId = searchParams.get('id')

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

  const { mutateAsync: batchAddBackground, isPending: isAdding } = useBatchAddBackground({ aiId: Number(aiId) })
  const { mutateAsync: generateImage, isPending: isGenerating } = useGenerateImage()
  const { mutateAsync: generateContent } = useGenerateContent()
  const { imageStyleDictList } = dicts || {}
  const walletUpdate = useUpdateWalletBalance();
  const queryClient = useQueryClient();
  const setIsChargeDrawerOpen = useSetAtom(isChargeDrawerOpenAtom);

  useEffect(() => {
    queryClient.invalidateQueries({ queryKey: walletKeys.getWalletBalance() });
  }, [])

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

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

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

  const aiBirthday = ai?.birthday ? dayjs(ai.birthday).format("YYYY-MM-DD") : undefined

  const onSubmit = async (data: GenerateImageFormValues) => {
    if (!walletUpdate.checkSufficientByType(ChatPriceType.BACKGROUND_IMAGE)) {
      setIsChargeDrawerOpen(true);
      return;
    }

    const originalGenerate = async () => {
      setBatchNo(null)
      setSelectedImages(null);
      setLockPriceImages([])
      const { style, prompt } = data
      const { prompt: stylePrompt } = imageStyleDictList?.find(item => item.id === style) || {}
      const res = await generateImage({
        aiId: Number(aiId),
        hl: true,
        imageStylePrompt: stylePrompt,
        sex: ai?.sex,
        birthday: aiBirthday,
        content: prompt,
        type: ImageType.BACKGROUND,
        introduction: ai?.introduction || '',
      })
      if (res) {
        setBatchNo(res.batchNo || null)
      }
    };
    
    handleGenerateClick(originalGenerate);
  }

  const handleConfirm = async () => {
    if (selectedImages) {
      const targetImages = [{
        url: selectedImages,
        width: 1440,
        height: 2560,
      }]
      await batchAddBackground({
        aiId: Number(aiId),
        images: targetImages,
      })
      router.back();
      localStorage.setItem('image-2-background-set', "1")
    }
  }

  const handleChange = (image: string) => {
    setSelectedImages(image);
  }

  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
                            showAlert={!!field.value && !!field.value.trim()}
                            onConfirm={async () => {
                              const hasValue = field.value && !!field.value.trim();
                              const result: GenerateContentRequest = {
                                sex: ai?.sex,
                                birthday: aiBirthday,
                                introduction: ai?.introduction || '',
                                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">
                <Button
                  type="submit"
                  block
                  loading={isGenerating}
                  disabled={!form.formState.isValid}
                >
                  <Image src="/icons/diamond.svg" alt="Diamond" width={24} height={24} />{`${ChatPriceTypeMap[ChatPriceType.BACKGROUND_IMAGE]} to Generate`}
                </Button>
              </div>
            </div>
          </form>
        </Form>

        {/* 右侧结果展示区域 */}
        <div className="flex-1 h-full pt-20 relative">
          <div className="overflow-y-auto h-full pb-40 pt-1">
            <GeneralImageListMultiple
              batchNo={batchNo}
              setBatchNo={setBatchNo}
              value={selectedImages}
              imageViewer={imageViewer}
              onChange={setSelectedImages}
              showPrice={false}
              lockPriceImages={lockPriceImages}
              setLockPriceImages={setLockPriceImages}
              onAllImagesCompleted={handleAllImagesCompleted}
            />
          </div>

          <div className="absolute left-0 right-0 bottom-0 backdrop-blur-[32px] px-12 py-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={!selectedImages} loading={isAdding} onClick={handleConfirm}>Confirm</Button>
            </div>
          </div>
        </div>
      </div>

      {/* 图片查看器 */}
      <ImageViewer
        images={imageViewer.images}
        currentIndex={imageViewer.currentIndex}
        open={imageViewer.isOpen}
        onClose={imageViewer.closeViewer}
        onIndexChange={imageViewer.handleIndexChange}
        showChooseButton={false}
        ActionComponent={() => {
          const viewerImage = imageViewer.images[imageViewer.currentIndex];
          
          return (
            <MultipleViewerAction
              currentImage={viewerImage}
              isSelected={selectedImages === viewerImage}
              onChange={handleChange}
              lockPriceImages={lockPriceImages}
              setLockPriceImages={setLockPriceImages}
              showPrice={false}
            />
          )
        }}
      />

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

export default Image2BackgroundPage;