'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button, IconButton } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { cn } from '@/lib/utils'
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 ReferenceUpload from '../components/ReferenceUpload'
import GeneralImageList from '../components/GeneralImageList'
import {
  useCreateDict,
  useCreateFormStorage,
  useGenerateContent,
  useGenerateImage,
} 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 { GenderText, GenderTextMap } from '@/types/user'
import { ImageType } from '@/types/image'

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

type GenerateImageFormValues = z.infer<typeof generateImageFormSchema>

const GenerateImagePage = () => {
  const router = useRouter()
  const [batchNo, setBatchNo] = useState<string | null>(null)
  const [checkedImageUrl, setCheckedImageUrl] = useState<string | null>(null)
  const [allImagesCompleted, setAllImagesCompleted] = useState(false)

  const { mutateAsync: generateImage, isPending: isGenerating } = useGenerateImage()
  const { updateImageData, getImageData, getCharacterData } = useCreateFormStorage()
  const { data: dicts } = useCreateDict()
  const characterData = getCharacterData()
  const { mutateAsync: generateContent, isPending } = useGenerateContent()

  const { imageStyleDictList } = dicts || {}

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

  useEffect(() => {
    const batchInfo = localStorage.getItem('create-image-generate-batch')
    if (batchInfo) {
      const batchNo = JSON.parse(batchInfo)

      setBatchNo(batchNo.batchNo)
      form.reset({
        style: batchNo.style,
        prompt: batchNo.prompt,
      })
    }
  }, [form])

  const onSubmit = async (data: GenerateImageFormValues) => {
    setCheckedImageUrl(null)
    setBatchNo(null)
    setAllImagesCompleted(false)
    const imageData = getImageData()
    const { style, prompt } = data
    const { prompt: stylePrompt } = imageStyleDictList?.find((item) => item.id === style) || {}
    const result = {
      imageStylePrompt: stylePrompt,
      content: prompt,
      sex: characterData?.sex,
      birthday: characterData?.birthday,
      type: ImageType.CREATE_AI_IMAGE,
      introduction: imageData?.intro || '',
    }
    const res = await generateImage(result)
    if (res) {
      setBatchNo(res.batchNo || null)
      localStorage.setItem(
        'create-image-generate-batch',
        JSON.stringify({
          batchNo: res.batchNo,
          style: style,
          prompt: prompt,
        })
      )
    }
  }

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

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

  return (
    <div className="flex size-full flex-col">
      {/* 主要内容区域 - 左右分栏 */}
      <div className="flex flex-1 gap-6 overflow-hidden px-6">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex h-full flex-col">
            {/* 页面标题 */}
            <div className="flex items-center gap-2 py-6">
              <IconButton
                variant="ghost"
                size="small"
                onClick={() => router.back()}
                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="bg-surface-base-normal mb-6 flex h-full w-[404px] flex-1 flex-col overflow-hidden rounded-2xl">
              {/* 可滚动内容区域 */}
              <div className="flex-1 overflow-y-auto">
                <div className="space-y-6 p-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 imageData = getImageData()
                              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>
                    )}
                  />

                  {/* 参考图片上传 */}
                  {/* <FormField
                    control={form.control}
                    name="reference"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-txt-primary-normal txt-label-m">Reference<span className="text-txt-secondary-normal">(Optional)</span></FormLabel>
                        <FormControl>
                          <ReferenceUpload
                            value={field.value || ""}
                            onChange={field.onChange}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  /> */}
                </div>
              </div>

              {/* 底部固定按钮区域 */}
              <div className="mt-6 space-y-2 px-6 pb-6">
                <Button
                  type="submit"
                  block
                  loading={isGenerating}
                  disabled={
                    !form.formState.isValid || isGenerating || (!!batchNo && !allImagesCompleted)
                  }
                >
                  <i className="iconfont icon-beauty text-[24px]" />
                  Generate
                </Button>
              </div>
            </div>
          </form>
        </Form>

        {/* 右侧结果展示区域 */}
        <div className="relative h-full flex-1 pt-20">
          <div className="h-full overflow-y-auto pt-1 pb-40">
            <GeneralImageList
              batchNo={batchNo}
              setBatchNo={setBatchNo}
              value={checkedImageUrl}
              onChange={setCheckedImageUrl}
              onAllImagesCompleted={handleAllImagesCompleted}
            />
          </div>

          <div className="absolute right-0 bottom-0 left-0 z-10 flex justify-center px-12 py-6 backdrop-blur-[32px]">
            <div className="bg-background-default absolute inset-0 opacity-65" />
            <div className="relative mx-auto w-[752px] text-right">
              <Button
                variant="primary"
                size="large"
                disabled={!checkedImageUrl}
                onClick={handleConfirm}
              >
                Confirm
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default GenerateImagePage
