  "use client"

import { Button } from "@/components/ui/button"
import { Chip } from "@/components/ui/chip"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import ProgressIndicator from "@/app/(main)/create/components/ProgessIndicator"
import { useParams, useRouter } from "next/navigation"
import { useCreateDict, useEditFormStorage, useGetAI, type TypeFormData } from "@/hooks/create"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import React, { useEffect } from "react"
import { useNavigationGuard } from "@/hooks/useNavigationGuard"
import CloseIconButton from "@/app/(main)/edit/[aiId]/components/CloseIconButton"
import { cn } from "@/lib/utils"
import { useMainLayout } from "@/context/mainLayout"

// 表单验证模式
const typeFormSchema = z.object({
  roleCode: z.string().min(1, "Please select a role"),
  characterCode: z.string().min(1, "Please select a personality"),
  tagCode: z.string().min(1, "Please select a tag"),
})

type TypeFormValues = z.infer<typeof typeFormSchema>

interface ChipOption {
  label: string
  value: string
}

interface ChipGroupProps {
  options: ChipOption[]
  value: string | string[]
  onChange?: (value: string | string[]) => void
  multiple?: boolean
}

interface RoleChipGroupProps {
  options: {
    title: string
    options: ChipOption[]
  }[]
  value: string,
  onChange?: (value: string | string[]) => void
}

function ChipGroup({ options, value, onChange, multiple = false }: ChipGroupProps) {
  const handleClick = (optionValue: string) => {
    if (multiple) {
      const currentValues = Array.isArray(value) ? value : []
      const newValues = currentValues.includes(optionValue)
        ? currentValues.filter(v => v !== optionValue)
        : [...currentValues, optionValue]
      onChange?.(newValues)
    } else {
      onChange?.(optionValue)
    }
  }

  const isSelected = (optionValue: string) => {
    if (multiple) {
      return Array.isArray(value) && value.includes(optionValue)
    }
    return value === optionValue
  }

  return (
    <div className="flex flex-wrap gap-3">
      {options.map((option) => (
        <Chip
          key={option.value}
          state={isSelected(option.value) ? "active" : "inactive"}
          onClick={() => handleClick(option.value)}
        >
          {option.label}
        </Chip>
      ))}
    </div>
  )
}

const RoleChipGroup = ({ options, value, onChange }: RoleChipGroupProps) => {
  return (
    <div className="flex flex-col gap-6">
      {options.map((option) => (
        <div key={option.title}>
          <div className="txt-label-m mb-3">{option.title}</div>
          <ChipGroup options={option.options as ChipOption[]} value={value} onChange={onChange} />
        </div>
      ))}
    </div>
  )
}
  

export default function TypeForm() {
  const { aiId } = useParams<{ aiId: string }>()
  const router = useRouter()
  const { data: dict } = useCreateDict()
  const { data: ai } = useGetAI(Number(aiId));
  const { roleDictList, characterDictList, tagDictList } = dict || {}
  useNavigationGuard()
  // 使用表单数据暂存
  const { updateTypeData, getTypeData, isFormDataEmpty, updateCharacterData } = useEditFormStorage()
  const { isSidebarExpanded } = useMainLayout();
  
  // 初始化表单，使用暂存的数据作为默认值
  const savedData = getTypeData()
  const form = useForm<TypeFormValues>({
    resolver: zodResolver(typeFormSchema),
    defaultValues: {
      roleCode: savedData.roleCode || "",
      characterCode: savedData.characterCode || "",
      tagCode: savedData.tagCode || "",
    },
  })

  useEffect(() => {
    if (ai && isFormDataEmpty({ checkEnum: "type" })) {
      form.reset({
        roleCode: ai.roleCode,
        characterCode: ai.characterCode,
        tagCode: ai.tagCode,
      })
      const { birthday } = ai;
      const date = new Date(birthday || "");
      
      updateCharacterData({
        nickname: ai.nickname || "",
        sex: ai.sex ?? undefined,
        birthday: `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`,
        aiUserExt: {
          userProfile: ai.aiUserExt?.userProfile || "",
        },
      })
    }
  }, [ai, isFormDataEmpty])

  // 监听表单变化，自动暂存数据
  useEffect(() => {
    const subscription = form.watch((data) => {
      // 只有当数据不为空时才自动保存
      if (data.roleCode || data.characterCode || data.tagCode) {
        updateTypeData(data as TypeFormData)
      }
    })
    return () => {
      subscription.unsubscribe()
    }
  }, [form])

  // 表单提交处理
  const onSubmit = (data: TypeFormValues) => {
    // 暂存数据到 localStorage
    updateTypeData(data)
    // 跳转到下一步
    router.push(`/edit/${aiId}/character`)
  }

  const roleOptions = roleDictList?.map((item) => ({
    title: item.name || "",
    options: item.childDictList?.map((child) => ({
      label: child.name || "",
      value: child.code || "",
    })) || [],
  })) || []

  const personalityOptions = characterDictList?.map((item) => ({
    label: item.name || "",
    value: item.code || "",
  })) || []

  const watchCharacterCode = form.watch("characterCode")

  const tagOptions = React.useMemo(() => {
    // 如果 characterDictList 还没有加载完成，返回空数组
    if (!characterDictList || characterDictList.length === 0) {
      return []
    }
    
    const findCharacter = characterDictList.find((item) => item.code === watchCharacterCode);
    if (findCharacter) {
      return findCharacter.childDictList?.map((item) => ({
        label: item.name || "",
        value: item.code || "",
      })) || []
    }
    return []
  }, [watchCharacterCode, characterDictList])

  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">
          <h1 className="text-txt-primary-normal txt-title-l">
            Edit Character
          </h1>
        </div>
        <CloseIconButton />
      </div>

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

      {/* 主要内容区域 */}
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} 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 Type
            </h2>

            {/* Type选择 */}
            <FormField
              control={form.control}
              name="roleCode"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-txt-primary-normal txt-title-s">
                    Character
                  </FormLabel>
                  <FormControl>
                    <RoleChipGroup options={roleOptions} value={field.value} onChange={field.onChange} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Personality选择 */}
            <FormField
              control={form.control}
              name="characterCode"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-txt-primary-normal txt-title-s">
                    Personality
                  </FormLabel>
                  <FormControl>
                    <ChipGroup 
                      options={personalityOptions} 
                      value={field.value}
                      onChange={field.onChange}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Tags选择 */}
            <FormField
              control={form.control}
              name="tagCode"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-txt-primary-normal txt-title-s">
                    Tags
                  </FormLabel>
                  <FormControl>
                    <ChipGroup 
                      options={tagOptions} 
                      value={field.value}
                      onChange={field.onChange}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </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={!form.formState.isValid}>
                    Next
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </form>
      </Form>
    </div>
  )
}
