"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, useEffect } from "react"
import { useSession } from "next-auth/react"

export default function NewMemberPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { addMember, treeData, getMember } = useFamily()
  const { data: session, status } = useSession()
  
  // 未登录时重定向到登录页
  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin')
    }
  }, [status, router])

  const existingMembers = Object.values(treeData.members)
  const isFirstMember = existingMembers.length === 0
  
  // 从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
    }
    
    if (motherId) {
      data.motherId = motherId
    }
    
    // 如果只有父亲没有母亲，尝试自动获取母亲（父亲的配偶）
    if (fatherId && !motherId) {
      const father = getMember(fatherId)
      console.log('Looking for mother (father\'s spouse):', { fatherId, father, spouseIds: father?.spouseIds })
      if (father?.spouseIds && father.spouseIds.length > 0) {
        data.motherId = father.spouseIds[0]
        console.log('Found mother:', data.motherId)
      }
    }
    
    // 如果只有母亲没有父亲，尝试自动获取父亲（母亲的配偶）
    if (motherId && !fatherId) {
      const mother = getMember(motherId)
      console.log('Looking for father (mother\'s spouse):', { motherId, mother, spouseIds: mother?.spouseIds })
      if (mother?.spouseIds && mother.spouseIds.length > 0) {
        data.fatherId = mother.spouseIds[0]
        console.log('Found father:', data.fatherId)
      }
    }
    
    // 处理配偶信息
    if (spouseId) {
      data.spouseIds = [spouseId]
    }
    
    // 处理子女信息
    const childrenIds = searchParams.getAll('childrenIds')
    
    if (childrenIds.length > 0) {
      data.childrenIds = childrenIds
    } else 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 {
      // 如果是第一个成员，自动设置为始祖
      const memberData = isFirstMember ? {
        ...newMember,
        generation: 1,
        isFounder: true,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      } : {
        ...newMember,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      }
      
      await addMember(memberData)
      // 跳转到成员列表页，保留treeId参数
      const params = new URLSearchParams(window.location.search)
      router.push(`/members?${params.toString()}`)
    } 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>
          
          {isFirstMember && (
            <div className="mb-6 p-6 bg-gradient-to-br from-amber-50 via-orange-50 to-amber-50 border-2 border-amber-400 rounded-xl shadow-md">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-14 h-14 bg-gradient-to-br from-amber-200 to-orange-200 rounded-full flex items-center justify-center shadow-sm">
                  <span className="text-3xl">👑</span>
                </div>
                <div className="flex-1">
                  <h2 className="text-2xl font-serif font-bold text-amber-900 mb-3">
                    立家族之根基
                  </h2>
                  <p className="text-base text-amber-800 leading-relaxed font-serif">
                    此为家族树之<span className="font-bold text-amber-900">始祖</span>，
                    <span className="font-bold text-amber-900">第一世</span>传人。
                    <br />
                    血脉由此而始，世系因此而传。
                  </p>
                </div>
              </div>
            </div>
          )}
          
          <h1 className="text-3xl font-serif font-bold mb-2">
            {isFirstMember ? '添加家族始祖' : '新增家族成员'}
          </h1>
          <p className="text-muted-foreground">
            {isFirstMember 
              ? '请认真填写始祖信息，这将是家族历史的起点' 
              : '填写成员信息，完善家族树'}
          </p>
        </div>
        <MemberForm 
          initialData={initialData} 
          existingMembers={existingMembers} 
          onSubmit={handleSave} 
          onCancel={() => router.back()}
          isFounder={isFirstMember}
        />
      </div>
    </div>
  )
}
