"use client"

import type { FamilyMember } from "@/types/family"
import { cn } from "@/lib/utils"
import { useAvatarCache } from "@/hooks/use-avatar-cache"
import { CircleUser, CircleUserRound, Heart, UserPlus, Users, Baby } from "lucide-react"
import { MemberNameWithStatus } from "@/components/member-name-with-status"
import { useRouter } from "next/navigation"
import { useFamily } from "@/context/family-context"
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuLabel,
  ContextMenuTrigger,
} from "@/components/ui/context-menu"

interface FamilyNodeProps {
  member: FamilyMember
  spouse?: FamilyMember
  spouses?: FamilyMember[]
  isRoot?: boolean
  onSelect?: (member: FamilyMember) => void
  isHighlighted?: boolean
  relationMode?: boolean
  isSelected?: boolean
  canEdit?: boolean
  onAddRelation?: (type: "child" | "spouse") => void
}

// 格式化日期显示（只显示年份）
function formatYear(dateString?: string): string {
  if (!dateString) return ''
  const year = dateString.split('-')[0]
  return year
}

// 计算年龄
function calculateAge(birthDate?: string, deathDate?: string): number | null {
  if (!birthDate) return null
  
  const birth = new Date(birthDate)
  const end = deathDate ? new Date(deathDate) : new Date()
  
  let age = end.getFullYear() - birth.getFullYear()
  const monthDiff = end.getMonth() - birth.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && end.getDate() < birth.getDate())) {
    age--
  }
  
  return age
}

// 单个人员卡片组件
function PersonCard({ 
  member, 
  isRoot, 
  isSpouse, 
  onSelect, 
  isHighlighted, 
  relationMode, 
  isSelected,
  canEdit = true,
  onAddRelation
}: { 
  member: FamilyMember
  isRoot?: boolean
  isSpouse?: boolean
  onSelect?: (member: FamilyMember) => void
  isHighlighted?: boolean
  relationMode?: boolean
  isSelected?: boolean
  canEdit?: boolean
  onAddRelation?: (type: "child" | "spouse") => void
}) {
  const { avatarUrl: avatarBlobUrl } = useAvatarCache(member?.avatarUrl)
  const router = useRouter()
  const { currentTree } = useFamily()
  
  const birthYear = formatYear(member.birthDate)
  const deathYear = formatYear(member.deathDate)
  const age = calculateAge(member.birthDate, member.deathDate)
  
  const lifeSpan = birthYear
    ? deathYear
      ? `${birthYear}-${deathYear}`
      : `${birthYear}-`
    : ''
  
  const ageText = age !== null
    ? member.deathDate
      ? `享年${age}岁`
      : `${age}岁`
    : ''

  // 判断可以添加的关系
  const canAddFather = !member.fatherId
  const canAddMother = !member.motherId
  const canAddSpouse = true // 配偶总是可以添加
  const canAddChild = true // 子女总是可以添加

  // 构建新增成员的 URL
  const buildAddUrl = (type: 'father' | 'mother' | 'spouse' | 'child') => {
    const params = new URLSearchParams()
    if (currentTree?.id) {
      params.set('treeId', currentTree.id)
    }
    
    switch (type) {
      case 'father':
        params.set('childId', member.id)
        params.set('gender', 'MALE')
        params.set('generation', (member.generation - 1).toString())
        // 如果已有母亲，设为配偶
        if (member.motherId) {
          params.set('spouseId', member.motherId)
        }
        break
      case 'mother':
        params.set('childId', member.id)
        params.set('gender', 'FEMALE')
        params.set('generation', (member.generation - 1).toString())
        // 如果已有父亲，设为配偶
        if (member.fatherId) {
          params.set('spouseId', member.fatherId)
        }
        break
      case 'spouse':
        params.set('spouseId', member.id)
        params.set('generation', member.generation.toString())
        // 配偶性别与当前成员相反
        params.set('gender', member.gender === 'MALE' ? 'FEMALE' : 'MALE')
        
        // 如果当前成员有子女，将他们也作为新配偶的子女
        if (member.childrenIds && member.childrenIds.length > 0) {
          // 传递所有子女ID
          member.childrenIds.forEach(id => {
            params.append('childrenIds', id)
          })
        }
        break
      case 'child':
        // 根据当前成员性别设置父/母
        if (member.gender === 'MALE') {
          params.set('fatherId', member.id)
          // 如果父亲有配偶，设置配偶为母亲
          if (member.spouseIds && member.spouseIds.length > 0) {
            params.set('motherId', member.spouseIds[0])
          }
        } else {
          params.set('motherId', member.id)
          // 如果母亲有配偶，设置配偶为父亲
          if (member.spouseIds && member.spouseIds.length > 0) {
            params.set('fatherId', member.spouseIds[0])
          }
        }
        params.set('generation', (member.generation + 1).toString())
        break
    }
    
    return `/members/new?${params.toString()}`
  }

  const handleAddMember = (type: 'father' | 'mother' | 'spouse' | 'child') => {
    const url = buildAddUrl(type)
    console.log('handleAddMember called:', type, url)
    // 使用 setTimeout 延迟跳转，确保菜单关闭后再执行
    setTimeout(() => {
      console.log('Navigating to:', url)
      window.location.href = url
    }, 100)
  }

  // 是否显示右键菜单（有可添加的选项时才显示）
  const hasAddOptions = canEdit && (canAddFather || canAddMother || canAddSpouse || canAddChild)
  
  // 调试日志
  console.log('PersonCard render:', member.fullName, { canEdit, hasAddOptions, relationMode })

  const cardContent = (
    <div
      className={cn(
        "family-node-card relative flex flex-col items-center gap-2 p-3 rounded-lg transition-all cursor-pointer hover:scale-105 shadow-sm w-32",
        isSelected
          ? "border-4 border-blue-500 bg-blue-50 dark:bg-blue-900/20 ring-4 ring-blue-200 dark:ring-blue-800"
          : isHighlighted
            ? "border-4 border-yellow-400 bg-yellow-50 dark:bg-yellow-900/20 ring-4 ring-yellow-200 dark:ring-yellow-800 animate-pulse"
            : isRoot 
              ? "border-2 border-primary bg-primary/5" 
              : isSpouse
                ? "border-2 border-dashed border-border/60 bg-muted/30"
                : "border-2 border-border bg-card",
        relationMode && "hover:border-blue-400 hover:shadow-lg"
      )}
      onClick={() => onSelect?.(member)}
    >
      <div className="absolute -top-3 bg-background border border-border px-2 py-0.5 rounded-full text-[10px] text-muted-foreground font-mono">
        {member.generation}世
      </div>

      <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center text-muted-foreground overflow-hidden border border-border/50">
        {avatarBlobUrl ? (
          <img
            src={avatarBlobUrl}
            alt={member.fullName}
            className="h-full w-full object-cover"
          />
        ) : (
          member.gender === 'FEMALE' ? (
            <CircleUserRound className="h-8 w-8 text-pink-400" />
          ) : (
            <CircleUser className="h-8 w-8 text-blue-400" />
          )
        )}
      </div>

      <div className="text-center w-full">
        <div className="font-serif font-bold text-foreground leading-tight flex items-center justify-center gap-1">
          <MemberNameWithStatus 
            name={`${member.surname}${member.givenName}`}
            isDead={!!member.deathDate}
          />
        </div>
        {member.courtesyName && (
          <div className="text-[10px] text-muted-foreground mt-0.5">字 {member.courtesyName}</div>
        )}
        {lifeSpan && (
          <div className="text-[9px] text-muted-foreground/70 mt-1 font-mono">
            {lifeSpan}
          </div>
        )}
        {ageText && (
          <div className="text-[9px] text-muted-foreground/60 font-mono">
            {ageText}
          </div>
        )}
        {member.phone && (
          <div className="text-[9px] text-muted-foreground/60 font-mono truncate">
            📱 {member.phone}
          </div>
        )}
      </div>
    </div>
  )

  // 如果没有可添加的选项或在关系模式下，直接返回卡片
  if (!hasAddOptions || relationMode) {
    return cardContent
  }

  // 有可添加选项时，包裹右键菜单
  return (
    <ContextMenu>
      <ContextMenuTrigger>
        {cardContent}
      </ContextMenuTrigger>
      <ContextMenuContent className="w-48">
        <ContextMenuLabel className="text-xs text-muted-foreground">
          为 {member.fullName} 添加
        </ContextMenuLabel>
        <ContextMenuSeparator />
        
        {canAddFather && (
          <ContextMenuItem 
            className="gap-2 cursor-pointer"
            onPointerDown={(e) => {
              e.preventDefault()
              handleAddMember('father')
            }}
          >
            <UserPlus className="h-4 w-4 text-blue-500" />
            添加父亲
          </ContextMenuItem>
        )}
        
        {canAddMother && (
          <ContextMenuItem 
            className="gap-2 cursor-pointer"
            onPointerDown={(e) => {
              e.preventDefault()
              handleAddMember('mother')
            }}
          >
            <UserPlus className="h-4 w-4 text-pink-500" />
            添加母亲
          </ContextMenuItem>
        )}
        
        {(canAddFather || canAddMother) && (canAddSpouse || canAddChild) && (
          <ContextMenuSeparator />
        )}
        
        {canAddSpouse && (
          <ContextMenuItem 
            className="gap-2 cursor-pointer"
            onPointerDown={(e) => {
              e.preventDefault()
              if (onAddRelation) {
                onAddRelation('spouse')
              } else {
                handleAddMember('spouse')
              }
            }}
          >
            <Users className="h-4 w-4 text-red-500" />
            添加配偶
          </ContextMenuItem>
        )}
        
        {canAddChild && (
          <ContextMenuItem 
            className="gap-2 cursor-pointer"
            onPointerDown={(e) => {
              e.preventDefault()
              if (onAddRelation) {
                onAddRelation('child')
              } else {
                handleAddMember('child')
              }
            }}
          >
            <Baby className="h-4 w-4 text-green-500" />
            添加子女
          </ContextMenuItem>
        )}
      </ContextMenuContent>
    </ContextMenu>
  )
}

export function FamilyNode({ member, spouse, spouses, isRoot, onSelect, isHighlighted, relationMode, isSelected, canEdit = true, onAddRelation }: FamilyNodeProps) {
  // 优先使用 spouses 数组，如果没有则使用单个 spouse
  const spouseList = spouses || (spouse ? [spouse] : [])
  
  if (spouseList.length === 0) {
    return <PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} canEdit={canEdit} onAddRelation={onAddRelation} />
  }
  
  // 有配偶时，并排显示所有配偶
  return (
    <div className="flex items-center gap-2">
      <PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} canEdit={canEdit} onAddRelation={onAddRelation} />
      {spouseList.map((spouseMember, index) => (
        <div key={spouseMember.id} className="flex items-center gap-2">
          <Heart className="h-4 w-4 text-red-400 flex-shrink-0" />
          <PersonCard member={spouseMember} isSpouse={true} onSelect={onSelect} relationMode={relationMode} canEdit={canEdit} />
        </div>
      ))}
    </div>
  )
}
