"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 { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import ProgressIndicator from "@/app/(main)/create/components/ProgessIndicator"
import GenderInput from "@/components/features/genderInput"
import { Gender } from "@/types/user"
import { calculateAge, cn, getDaysInMonth } from "@/lib/utils"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import dayjs from "dayjs"
import { useEffect, useState } from "react"
import { useParams, useRouter } from "next/navigation"
import { CreateFormData, useEditFormStorage, useGenerateContent, useGetAI } from "@/hooks/create"
import AIGenerateButton from "@/components/features/ai-generate-button"
import { GenerateContentRequest, PtType } from "@/services/create"
import CloseIconButton from "@/app/(main)/edit/[aiId]/components/CloseIconButton"
import { useCheckNickname, useCheckText } from "@/hooks/auth"
import { useMainLayout } from "@/context/mainLayout"

const currentYear = dayjs().year()
const years = Array.from({ length: currentYear - 1950 + 1 }, (_, i) => `${1950 + i}`)
const months = Array.from({ length: 12 }, (_, i) => `${i + 1}`.padStart(2, "0"))
const monthTexts = Array.from({ length: 12 }, (_, i) => dayjs().month(i).format('MMM'))

const characterFormSchema = z.object({
  nickname: z.string().trim().min(1, "Please enter character name").min(2, "Nickname must be between 2 and 20 characters").max(20, "Nickname must be less than 20 characters"),
  sex: z.enum(Gender, { message: "Please select gender" }),
  year: z.string().min(1, "Please select year"),
  month: z.string().min(1, "Please select month"),
  day: z.string().min(1, "Please select day"),
  userProfile: z.string().trim().min(10, "At least 10 characters").max(4000, "Description must be less than 4000 characters"),
}).refine((data) => {
  const age = calculateAge(data.year, data.month, data.day)
  return age >= 18
}, {
  message: "Character age must be at least 18 years old",
  path: ["year"]
})

type CharacterFormValues = z.infer<typeof characterFormSchema>

export default function CharacterForm() {
  const { aiId } = useParams<{ aiId: string }>()
  const { data: ai } = useGetAI(Number(aiId));
  const [loading, setLoading] = useState(false)
  const router = useRouter()
  const { updateCharacterData, getCharacterData, formData, isFormDataEmpty, updateHasPreferenceByAI } = useEditFormStorage()
  const { mutateAsync: generateContent } = useGenerateContent()
  const { isSidebarExpanded } = useMainLayout();

  const { mutateAsync: checkNickname } = useCheckNickname({
    onError: (error) => {
      form.setError("nickname", {
        message: error.errorMsg,
      })
    }
  });
  const { mutateAsync: checkText } = useCheckText();

  const savedData = getCharacterData() || {
    nickname: "",
    sex: undefined,
    birthday: "",
    aiUserExt: { userProfile: "" },
  }
  const form = useForm<CharacterFormValues>({
    resolver: zodResolver(characterFormSchema),
    defaultValues: {
      nickname: savedData.nickname || "",
      sex: savedData.sex ?? undefined,
      year: savedData.birthday.split("-")[0] || "2000",
      month: savedData.birthday.split("-")[1] || "01",
      day: savedData.birthday.split("-")[2] || "01",
      userProfile: savedData.aiUserExt.userProfile || "",
    }
  })

  const selectedYear = form.watch("year")
  const selectedMonth = form.watch("month")
  const days = selectedYear && selectedMonth ? getDaysInMonth(selectedYear, selectedMonth) : []

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

  // 监听表单变化，自动暂存数据
  useEffect(() => {
    const subscription = form.watch((data) => {
      // 只有当数据不为空时才自动保存
      if (data.nickname || data.sex || data.year || data.month || data.day || data.userProfile) {
        updateCharacterData({
          nickname: data.nickname,
          sex: data.sex ?? undefined,
          birthday: `${data.year}-${data.month}-${data.day}`,
          aiUserExt: {
            userProfile: data.userProfile,
          },
        } as CreateFormData['character'])
      }
    })
    return () => {
      subscription.unsubscribe()
    }
  }, [form])

  useEffect(() => {
    const currentDay = form.getValues("day")
    const maxDay = days[days.length - 1]
    if (parseInt(currentDay) > parseInt(maxDay)) {
      form.setValue("day", maxDay)
    }
  }, [selectedYear, selectedMonth, days, form])

  async function onSubmit(data: CharacterFormValues) {
    setLoading(true)
    try {
      // 如果nickname没有变化，则不进行重复检测
      if (data.nickname.trim() !== ai?.nickname) {
        const { nickname } = data
        // 检测名字是否重复
        const isExist = await checkNickname({
          nickname: nickname.trim(),
          exUserId: Number(aiId),
        })
        if (isExist) {
          form.setError("nickname", {
            message: "This nickname is already taken",
          })
          return;
        }
      }
      if (data.userProfile !== ai?.aiUserExt?.userProfile) {
        const resp = await checkText({
          content: data.userProfile,
        })
        if (resp) {
          form.setError("userProfile", {
            message: resp,
          })
          return;
        }
      }
      router.push(`/edit/${aiId}/dialogue`)  
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex flex-col gap-6 w-[752px] mx-auto 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={2} totalSteps={4} />

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

              {/* 名字输入 */}
              <FormField
                control={form.control}
                name="nickname"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-txt-primary-normal txt-label-m">Name</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter character name"
                        maxLength={20}
                        error={!!form.formState.errors.nickname}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Gender */}
              <FormField
                control={form.control}
                name="sex"
                disabled={true}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-txt-primary-normal txt-label-m">Gender</FormLabel>
                    <FormControl>
                      <GenderInput
                        value={field.value as Gender}
                        onChange={field.onChange}
                        disabled={true}
                      />
                    </FormControl>
                    <FormMessage />
                    <div className="txt-body-s text-txt-secondary-normal">Please note: gender cannot be changed after setting</div>
                  </FormItem>
                )}
              />

              <FormItem>
                <FormLabel className="text-txt-primary-normal txt-label-m">Birthday</FormLabel>
                <div className="flex gap-2">
                  <FormField
                    control={form.control}
                    name="year"
                    render={({ field }) => (
                      <Select onValueChange={field.onChange} value={field.value}>
                        <SelectTrigger className="w-full" error={!!form.formState.errors.year}><SelectValue placeholder="Year" /></SelectTrigger>
                        <SelectContent>
                          {years.map(y => <SelectItem key={`${y}`} value={`${y}`}>{`${y}`}</SelectItem>)}
                        </SelectContent>
                      </Select>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="month"
                    render={({ field }) => (
                      <Select onValueChange={field.onChange} value={field.value}>
                        <SelectTrigger className="w-full" error={!!form.formState.errors.year}><SelectValue placeholder="Month" /></SelectTrigger>
                        <SelectContent>
                          {months.map((m, index) => <SelectItem key={`${m}`} value={`${m}`}>{monthTexts[index]}</SelectItem>)}
                        </SelectContent>
                      </Select>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="day"
                    render={({ field }) => (
                      <Select onValueChange={field.onChange} value={field.value}>
                        <SelectTrigger className="w-full" error={!!form.formState.errors.year || !!form.formState.errors.day}><SelectValue placeholder="Day" /></SelectTrigger>
                        <SelectContent>
                          {days.map(d => <SelectItem key={`${d}`} value={`${d}`}>{`${d}`}</SelectItem>)}
                        </SelectContent>
                      </Select>
                    )}
                  />
                </div>
                <FormMessage>
                  {form.formState.errors.year?.message || form.formState.errors.month?.message || form.formState.errors.day?.message}
                </FormMessage>
              </FormItem>

              {/* 描述输入 */}
              <FormField
                control={form.control}
                name="userProfile"
                render={({ field }) => (
                  <FormItem>
                    <div className="flex justify-between">
                      <FormLabel className="text-txt-primary-normal txt-label-m">Profile</FormLabel>
                      <AIGenerateButton
                        showAlert={!!field.value.trim()}
                        getNickName={() => form.getValues("nickname")}
                        onConfirm={async () => {
                          const result = {
                            ptType: PtType.GenAIProfileByNon,
                            sex: form.getValues("sex") ?? '',
                            birthday: form.getValues("year") + "-" + form.getValues("month") + "-" + form.getValues("day"),
                            nickname: form.getValues("nickname") || '',
                            characterCode: formData.type.characterCode,
                            tagCode: formData.type.tagCode,
                          } as GenerateContentRequest;
                          const resp = await generateContent(result)
                          form.setValue("userProfile", resp.content || "")
                          updateHasPreferenceByAI(true)
                        }}
                      />
                    </div>
                    <FormControl>
                      <Textarea 
                        placeholder="Describe the character's background, personality, and identity" 
                        showCount
                        error={!!form.formState.errors.userProfile}
                        maxLength={4000}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </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"
                    loading={loading}
                  >
                    Next
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </form>
      </Form>
    </div>
  )
}
