"use client"

import { useRouter, useSearchParams } from "next/navigation"
import { useFamily } from "@/context/family-context"
import { SiteHeader } from "@/components/site-header"
import { MemberForm } from "@/components/members/member-form"
import { Button } from "@/components/ui/button"
import { ArrowLeft } from "lucide-react"
import type { FamilyMember } from "@/types/family"
import { useMemo } from "react"

export default function NewMemberPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { addMember, treeData, getMember } = useFamily()

  const existingMembers = Object.values(treeData.members)
  
  // 从URL参数获取预填信息
  const initialData = useMemo(() => {
    const fatherId = searchParams.get('fatherId')
    const motherId = searchParams.get('motherId')
    const spouseId = searchParams.get('spouseId')
    const childId = searchParams.get('childId')
    const generation = searchParams.get('generation')
    const gender = searchParams.get('gender')
    
    if (!fatherId && !motherId && !spouseId && !childId && !generation && !gender) return undefined
    
    const data: Partial<FamilyMember> = {}
    
    // 处理父母信息
    if (fatherId) {
      data.fatherId = fatherId
      // 如果有父亲，尝试获取母亲（父亲的配偶）
      const father = getMember(fatherId)
      if (father?.spouseIds && father.spouseIds.length > 0) {
        data.motherId = father.spouseIds[0]
      }
    }
    
    if (motherId) {
      data.motherId = motherId
      // 如果有母亲，尝试获取父亲（母亲的配偶）
      const mother = getMember(motherId)
      if (mother?.spouseIds && mother.spouseIds.length > 0) {
        data.fatherId = mother.spouseIds[0]
      }
    }
    
    // 处理配偶信息
    if (spouseId) {
      data.spouseIds = [spouseId]
    }
    
    // 处理子女信息（添加父母时使用）
    if (childId) {
      data.childrenIds = [childId]
    }
    
    // 处理世代
    if (generation) {
      data.generation = parseInt(generation)
    }
    
    // 处理性别
    if (gender) {
      data.gender = gender.toUpperCase() as 'MALE' | 'FEMALE'
    }
    
    return data
  }, [searchParams, getMember])

  const handleSave = async (newMember: FamilyMember) => {
    try {
      await addMember({
        ...newMember,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      })
      // 跳转到成员列表页
      router.push('/members')
    } catch (error) {
      console.error('添加成员失败:', error)
      alert('添加成员失败: ' + (error as Error).message)
    }
  }

  return (
    <div className="min-h-screen flex flex-col bg-background">
      <SiteHeader />
      <div className="container mx-auto py-8">
        <div className="mb-6">
          <Button variant="ghost" onClick={() => router.back()} className="mb-4">
            <ArrowLeft className="mr-2 h-4 w-4" /> 返回
          </Button>
          <h1 className="text-3xl font-serif font-bold mb-2">新增家族成员</h1>
          <p className="text-muted-foreground">
            填写成员信息，完善家族树
          </p>
        </div>
        <MemberForm initialData={initialData} existingMembers={existingMembers} onSubmit={handleSave} onCancel={() => router.back()} />
      </div>
    </div>
  )
}
